@hamsa-ai/voice-agents-sdk 0.5.0-beta.1 → 0.5.1-beta.1
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/index.umd.js
CHANGED
|
@@ -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).HamsaVoiceAgent={})}(this,(function(e){"use strict";function t(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)}"function"==typeof SuppressedError&&SuppressedError;var i,n={exports:{}};var s=function(){if(i)return n.exports;i=1;var e,t="object"==typeof Reflect?Reflect:null,s=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var o=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}n.exports=r,n.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}f(e,t,o,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&f(e,"error",t,i)}(e,s,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function d(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function l(e,t,i,n){var s,o,r,a;if(c(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),r=o[t]),void 0===r)r=o[t]=i,++e._eventsCount;else if("function"==typeof r?r=o[t]=n?[i,r]:[r,i]:n?r.unshift(i):r.push(i),(s=d(e))>0&&r.length>s&&!r.warned){r.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=r.length,a=l,console&&console.warn&&console.warn(a)}return e}function u(){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 h(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=u.bind(n);return s.listener=i,n.wrapFn=s,s}function p(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):g(s,s.length)}function m(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 g(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function f(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(o){n.once&&e.removeEventListener(t,s),i(o)}))}}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||o(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),r.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},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||o(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},r.prototype.getMaxListeners=function(){return d(this)},r.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,o=this._events;if(void 0!==o)n=n&&void 0===o.error;else if(!n)return!1;if(n){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)s(c,this,t);else{var d=c.length,l=g(c,d);for(i=0;i<d;++i)s(l[i],this,t)}return!0},r.prototype.addListener=function(e,t){return l(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return l(this,e,t,!0)},r.prototype.once=function(e,t){return c(t),this.on(e,h(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,h(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,s,o,r;if(c(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,o=i.length-1;o>=0;o--)if(i[o]===t||i[o].listener===t){r=i[o].listener,s=o;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,r||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,o=Object.keys(i);for(n=0;n<o.length;++n)"removeListener"!==(s=o[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},r.prototype.listeners=function(e){return p(this,e,!0)},r.prototype.rawListeners=function(e){return p(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},r.prototype.listenerCount=m,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},n.exports}();class o extends Error{}function r(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i})))}(t)}catch(e){return atob(t)}}function a(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)}o.prototype.name="InvalidTokenError";var c=Object.defineProperty,d=(e,t,i)=>((e,t,i)=>t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class l{constructor(){d(this,"_locking"),d(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function u(e,t){if(!e)throw new Error(t)}function h(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function p(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function m(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const g=Symbol("@bufbuild/protobuf/enum-type");function f(e){const t=e[g];return u(t,"missing enum type on enum object"),t}function v(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),s=Object.create(null),o=[];for(const e of t){const t=y(e);o.push(t),n[e.name]=t,s[e.no]=t}return{typeName:e,values:o,findName:e=>n[e],findNumber:e=>s[e]}}function k(e,t,i){const n={};for(const e of t){const t=y(e);n[t.localName]=t.no,n[t.no]=t.localName}return v(n,e,t),n}function y(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class T{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(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}}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,!(128&n))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function S(e,t,i){for(let n=0;n<28;n+=7){const s=e>>>n,o=!(s>>>7==0&&0==t),r=255&(o?128|s:s);if(i.push(r),!o)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),o=255&(s?128|n:n);if(i.push(o),!s)return}i.push(t>>>31&1)}}const w=4294967296;function E(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function o(t,o){const r=Number(e.slice(t,o));s*=i,n=n*i+r,n>=w&&(s+=n/w|0,n%=w)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?I(n,s):R(n,s)}function P(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(w*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,o=i+8147497*n,r=2*n;const a=1e7;return s>=a&&(o+=Math.floor(s/a),s%=a),o>=a&&(r+=Math.floor(o/a),o%=a),r.toString()+M(o)+M(s)}function R(e,t){return{lo:0|e,hi:0|t}}function I(e,t){return t=~t,e?e=1+~e:t+=1,R(e,t)}const M=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 A(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const D=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>u(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>u(/^[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),E(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),E(e)),dec:(e,t)=>function(e,t){let i=R(e,t);const n=2147483648&i.hi;n&&(i=I(i.lo,i.hi));const s=P(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>P(e,t)}}();var L,x,_;function N(e,t,i){if(t===i)return!0;if(e==L.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 L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return t==i}return!1}function U(e,t){switch(e){case L.BOOL:return!1;case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return 0==t?D.zero:"0";case L.DOUBLE:case L.FLOAT:return 0;case L.BYTES:return new Uint8Array(0);case L.STRING:return"";default:return 0}}function j(e,t){switch(e){case L.BOOL:return!1===t;case L.STRING:return""===t;case L.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!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"}(L||(L={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(x||(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"}(_||(_={}));class F{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(p(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return h(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){m(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){p(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){h(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return h(e),O(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=D.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=D.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=D.enc(e);return S(t.lo,t.hi,this.buf),this}sint64(e){let t=D.enc(e),i=t.hi>>31;return S(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=D.uEnc(e);return S(t.lo,t.hi,this.buf),this}}class B{constructor(e,t){this.varint64=C,this.uint32=A,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case _.Varint:for(;128&this.buf[this.pos++];);break;case _.Bit64:this.pos+=4;case _.Bit32:this.pos+=4;break;case _.LengthDelimited:let i=this.uint32();this.pos+=i;break;case _.StartGroup:for(;;){const[e,i]=this.tag();if(i===_.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return D.dec(...this.varint64())}uint64(){return D.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,D.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 D.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return D.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 V(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return U(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),K=[];for(let e=0;e<q.length;e++)K[q[e].charCodeAt(0)]=e;K["-".charCodeAt(0)]=q.indexOf("+"),K["_".charCodeAt(0)]=q.indexOf("/");const H={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,o=0,r=0;for(let t=0;t<e.length;t++){if(i=K[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":o=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(o){case 0:r=i,o=1;break;case 1:n[s++]=r<<2|(48&i)>>4,r=i,o=2;break;case 2:n[s++]=(15&r)<<4|(60&i)>>2,r=i,o=3;break;case 3:n[s++]=(3&r)<<6|i,o=0}}if(1==o)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let o=0;o<e.length;o++)switch(t=e[o],n){case 0:i+=q[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=q[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=q[s|t>>6],i+=q[63&t],n=0}return n&&(i+=q[s],i+="=",1==n&&(i+="=")),i}};function G(e,t,i){J(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[o,r]=V(t);for(const e of s)t.runtime.bin.readField(o,n.readerFactory(e.data),t.field,e.wireType,n);return r()}function z(e,t,i,n){J(t,e);const s=t.runtime.bin.makeReadOptions(n),o=t.runtime.bin.makeWriteOptions(n);if(W(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const r=o.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,r,o);const c=s.readerFactory(r.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function W(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function J(e,t){u(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function Q(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!j(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function $(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?U(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Y(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(T.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function X(e,t){return Y(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}L.DOUBLE,L.FLOAT,L.INT64,L.UINT64,L.INT32,L.UINT32,L.BOOL,L.STRING,L.BYTES;const Z={ignoreUnknownFields:!1},ee={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function te(e){return e?Object.assign(Object.assign({},Z),e):Z}function ie(e){return e?Object.assign(Object.assign({},ee),e):ee}const ne=Symbol(),se=Symbol();function oe(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 re(e,t,i,n,s){let o=i.localName;if(i.repeated){if(u("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const r=e[o];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(e)));switch(i.kind){case"message":r.push(i.T.fromJson(e,n));break;case"enum":const t=de(i.T,e,n.ignoreUnknownFields,!0);t!==se&&r.push(t);break;case"scalar":try{r.push(ce(i.T,e,i.L,!0))}catch(t){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),new Error(n)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const r=e[o];for(const[e,o]of Object.entries(t)){if(null===o)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let a;try{a=ae(i.K,e)}catch(e){let n="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}switch(i.V.kind){case"message":r[a]=i.V.T.fromJson(o,n);break;case"enum":const e=de(i.V.T,o,n.ignoreUnknownFields,!0);e!==se&&(r[a]=e);break;case"scalar":try{r[a]=ce(i.V.T,o,x.BIGINT,!0)}catch(e){let n="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:o},o="value"),i.kind){case"message":const r=i.T;if(null===t&&"google.protobuf.Value"!=r.typeName)return;let a=e[o];Y(a)?a.fromJson(t,n):(e[o]=a=r.fromJson(t,n),r.fieldWrapper&&!i.oneof&&(e[o]=r.fieldWrapper.unwrapField(a)));break;case"enum":const c=de(i.T,t,n.ignoreUnknownFields,!1);switch(c){case ne:$(i,e);break;case se:break;default:e[o]=c}break;case"scalar":try{const n=ce(i.T,t,i.L,!1);if(n===ne)$(i,e);else e[o]=n}catch(e){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}}}function ae(e,t){if(e===L.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return ce(e,t,x.BIGINT,!0).toString()}function ce(e,t,i,n){if(null===t)return n?U(e,i):ne;switch(e){case L.DOUBLE:case L.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==L.FLOAT&&m(n),n;case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==L.UINT32||e==L.FIXED32?p(s):h(s),s;case L.INT64:case L.SFIXED64:case L.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=D.parse(t);return i?o.toString():o;case L.FIXED64:case L.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const r=D.uParse(t);return i?r.toString():r;case L.BOOL:if("boolean"!=typeof t)break;return t;case L.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case L.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return H.dec(t)}throw new Error}function de(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:ne;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return se}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(oe(t)))}function le(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function ue(e,t,i){if("map"==e.kind){u("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,i]of s)n[t.toString()]=pe(e.V.T,i);break;case"message":for(const[e,t]of s)n[e.toString()]=t.toJson(i);break;case"enum":const t=e.V.T;for(const[e,o]of s)n[e.toString()]=he(t,o,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){u(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(pe(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(he(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return pe(e.T,t);case"enum":return he(e.T,t,i.enumAsInteger);case"message":return X(e.T,t).toJson(i)}}function he(e,t,i){var n;if(u("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function pe(e,t){switch(e){case L.INT32:case L.SFIXED32:case L.SINT32:case L.FIXED32:case L.UINT32:return u("number"==typeof t),t;case L.FLOAT:case L.DOUBLE:return u("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case L.STRING:return u("string"==typeof t),t;case L.BOOL:return u("boolean"==typeof t),t;case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return u("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case L.BYTES:return u(t instanceof Uint8Array),H.enc(t)}}const me=Symbol("@bufbuild/protobuf/unknown-fields"),ge={readUnknownFields:!0,readerFactory:e=>new B(e)},fe={writeUnknownFields:!0,writerFactory:()=>new F};function ve(e){return e?Object.assign(Object.assign({},ge),e):ge}function be(e){return e?Object.assign(Object.assign({},fe),e):fe}function ke(e,t,i,n,s){let{repeated:o,localName:r}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=r&&delete e.value,e.case=r,r="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?L.INT32:i.T;let c=Ce;if("scalar"==i.kind&&i.L>0&&(c=Te),o){let i=e[r];if(n==_.LengthDelimited&&a!=L.STRING&&a!=L.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[r]=c(t,a);break;case"message":const d=i.T;o?e[r].push(ye(t,new d,s,i)):Y(e[r])?ye(t,e[r],s,i):(e[r]=ye(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[r]=d.fieldWrapper.unwrapField(e[r])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let o,r;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:o=Ce(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=Ce(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=ye(t,new e.V.T,i,void 0)}}}void 0===o&&(o=U(e.K,x.BIGINT));"string"!=typeof o&&"number"!=typeof o&&(o=o.toString());if(void 0===r)switch(e.V.kind){case"scalar":r=U(e.V.T,x.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[o,r]}(i,t,s);e[r][l]=u}}function ye(e,t,i,n){const s=t.getType().runtime.bin,o=null==n?void 0:n.delimited;return s.readMessage(t,e,o?n.no:e.uint32(),i,o),t}function Te(e,t){const i=Ce(e,t);return"bigint"==typeof i?i.toString():i}function Ce(e,t){switch(t){case L.STRING:return e.string();case L.BOOL:return e.bool();case L.DOUBLE:return e.double();case L.FLOAT:return e.float();case L.INT32:return e.int32();case L.INT64:return e.int64();case L.UINT64:return e.uint64();case L.FIXED64:return e.fixed64();case L.BYTES:return e.bytes();case L.FIXED32:return e.fixed32();case L.SFIXED32:return e.sfixed32();case L.SFIXED64:return e.sfixed64();case L.SINT64:return e.sint64();case L.UINT32:return e.uint32();case L.SINT32:return e.sint32()}}function Se(e,t,i,n){u(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?L.INT32:e.T;if(s)if(u(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,_.LengthDelimited).fork();let[,s]=Re(t);for(let t=0;t<n.length;t++)e[s](n[t]);e.join()}(i,o,e.no,t);else for(const n of t)Pe(i,o,e.no,n);else Pe(i,o,e.no,t);break;case"message":if(s){u(Array.isArray(t));for(const s of t)Ee(i,n,e,s)}else Ee(i,n,e,t);break;case"map":u("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))we(i,n,e,s,o)}}function we(e,t,i,n,s){e.tag(i.no,_.LengthDelimited),e.fork();let o=n;switch(i.K){case L.INT32:case L.FIXED32:case L.UINT32:case L.SFIXED32:case L.SINT32:o=Number.parseInt(n);break;case L.BOOL:u("true"==n||"false"==n),o="true"==n}switch(Pe(e,i.K,1,o),i.V.kind){case"scalar":Pe(e,i.V.T,2,s);break;case"enum":Pe(e,L.INT32,2,s);break;case"message":u(void 0!==s),e.tag(2,_.LengthDelimited).bytes(s.toBinary(t))}e.join()}function Ee(e,t,i,n){const s=X(i.T,n);i.delimited?e.tag(i.no,_.StartGroup).raw(s.toBinary(t)).tag(i.no,_.EndGroup):e.tag(i.no,_.LengthDelimited).bytes(s.toBinary(t))}function Pe(e,t,i,n){u(void 0!==n);let[s,o]=Re(t);e.tag(i,s)[o](n)}function Re(e){let t=_.Varint;switch(e){case L.BYTES:case L.STRING:t=_.LengthDelimited;break;case L.DOUBLE:case L.FIXED64:case L.SFIXED64:t=_.Bit64;break;case L.FIXED32:case L.SFIXED32:case L.FLOAT:t=_.Bit32}return[t,L[e].toLowerCase()]}function Ie(e){if(void 0===e)return e;if(Y(e))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 Oe{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 Ae(e,t){const i=Le(e);return t?i:je(Ue(i))}const De=Le;function Le(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const xe=new Set(["constructor","toString","toJSON","valueOf"]),_e=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ne=e=>"".concat(e,"$"),Ue=e=>_e.has(e)?Ne(e):e,je=e=>xe.has(e)?Ne(e):e;class Fe{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Ae(e,!1)}addField(e){u(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 Be=(Ve=e=>new Oe(e,(e=>function(e){var t,i,n,s,o,r;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Ae(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:De(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:x.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(o=d.req)&&void 0!==o&&o,e.opt=null!==(r=d.opt)&&void 0!==r&&r,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=L.BYTES&&d.T!=L.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Fe(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e))),qe=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]=U(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:te,makeWriteOptions:ie,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(oe(t)));n=null!=n?n:new e;const s=new Map,o=i.typeRegistry;for(const[r,a]of Object.entries(t)){const t=e.fields.findJsonName(r);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(r,'"'));s.set(t.oneof,r)}re(n,a,t,i,e)}else{let t=!1;if((null==o?void 0:o.findExtension)&&r.startsWith("[")&&r.endsWith("]")){const s=o.findExtension(r.substring(1,r.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,o]=V(s);re(e,a,s.field,i,s),z(n,s,o(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(r,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!Q(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!le(s))continue}const i=ue(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const o=t.typeRegistry;if(null==o?void 0:o.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const r=o.findExtensionFor(i.typeName,s.no);if(r&&W(e,r)){const i=G(e,r,t),s=ue(r.field,i,t);void 0!==s&&(n[r.field.jsonName]=s)}}}catch(e){const t=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),n=e instanceof Error?e.message:String(e);throw new Error(t+(n.length>0?": ".concat(n):""))}return n},readScalar:(e,t,i)=>ce(e,t,null!=i?i:x.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||j(e,t)?pe(e,t):void 0},debug:oe},bin:{makeReadOptions:ve,makeWriteOptions:be,listUnknownFields(e){var t;return null!==(t=e[me])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[me]},writeUnknownFields(e,t){const i=e[me];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[me])||(s[me]=[]),s[me].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const o=e.getType(),r=s?t.len:t.pos+i;let a,c;for(;t.pos<r&&([a,c]=t.tag(),!0!==s||c!=_.EndGroup);){const i=o.fields.find(a);if(i)ke(e,t,i,c,n);else{const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i)}}if(s&&(c!=_.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:ke,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(Q(s,e))Se(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Se(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:v,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,o=e;if(null!=o[i])switch(n.kind){case"oneof":const e=o[i].case;if(void 0===e)continue;const t=n.findField(e);let r=o[i].value;t&&"message"==t.kind&&!Y(r,t.T)?r=new t.T(r):t&&"scalar"===t.kind&&t.T===L.BYTES&&(r=Me(r)),s[i]={case:e,value:r};break;case"scalar":case"enum":let a=o[i];n.T===L.BYTES&&(a=n.repeated?a.map(Me):Me(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===L.BYTES)for(const[e,t]of Object.entries(o[i]))s[i][e]=Me(t);else Object.assign(s[i],o[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(o[i])){let n=o[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=o[i].map((e=>Y(e,c)?e:new c(e)));else{const e=o[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=Me(e):s[i]=e:s[i]=Y(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>N(e.T,t,s[i])));case"enum":return n.every(((e,t)=>N(L.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=n,i=s;return e.T.fieldWrapper&&(void 0===t||Y(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===i||Y(i)||(i=e.T.fieldWrapper.wrapField(i))),e.T.equals(t,i);case"enum":return N(L.INT32,n,s);case"scalar":return N(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const o=e.findField(n.case);if(void 0===o)return!0;switch(o.kind){case"message":return o.T.equals(n.value,s.value);case"enum":return N(L.INT32,n.value,s.value);case"scalar":return N(o.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const r=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return r.every((e=>t.equals(n[e],s[e])));case"enum":return r.every((e=>N(L.INT32,n[e],s[e])));case"scalar":const i=e.V.T;return r.every((e=>N(i,n[e],s[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 s;if(i.repeated)s=t.map(Ie);else if("map"==i.kind){s=n[i.localName];for(const[e,i]of Object.entries(t))s[e]=Ie(i)}else s="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:Ie(t.value)}:{case:void 0}:Ie(t);n[i.localName]=s}for(const i of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,i.no,i.wireType,i.data);return i}}),{newFieldList:Ve,initFields:qe}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const o=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),r={[o]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[o];return Object.setPrototypeOf(r.prototype,new T),Object.assign(r,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new r).fromBinary(e,t),fromJson:(e,t)=>(new r).fromJson(e,t),fromJsonString:(e,t)=>(new r).fromJsonString(e,t),equals:(t,i)=>e.util.equals(r,t,i)}),r}(this,e,t,i)},makeEnum:k,makeEnumType:b,getEnumType:f,makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Ve,qe;class Ke extends T{constructor(e){super(),this.seconds=D.zero,this.nanos=0,Be.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Be.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=D.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:D.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 Be.util.equals(Ke,e,t)}}Ke.runtime=Be,Ke.typeName="google.protobuf.Timestamp",Ke.fields=Be.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const He=Be.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ge,repeated:!0},{no:5,name:"events",kind:"message",T:We,repeated:!0}])),Ge=Be.makeMessageType("livekit.TimeSeriesMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:ze,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),ze=Be.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"value",kind:"scalar",T:2}])),We=Be.makeMessageType("livekit.EventMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Ke},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ke,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Je=Be.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Qe=Be.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),$e=Be.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Ye=Be.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Xe=Be.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ze=Be.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),et=Be.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),tt=Be.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),it=Be.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),nt=Be.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),st=Be.makeMessageType("livekit.Room",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:ot,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:Nt}])),ot=Be.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),rt=Be.makeMessageType("livekit.ParticipantPermission",(()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:Be.getEnumType($e),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}])),at=Be.makeMessageType("livekit.ParticipantInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Be.getEnumType(ct)},{no:4,name:"tracks",kind:"message",T:pt,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:rt},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Be.getEnumType(dt)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Be.getEnumType(et)},{no:18,name:"kind_details",kind:"enum",T:Be.getEnumType(lt),repeated:!0}])),ct=Be.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),dt=Be.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),lt=Be.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),ut=Be.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ht=Be.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:mt,repeated:!0}])),pt=Be.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Be.getEnumType(Qe)},{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:Be.getEnumType($e)},{no:10,name:"layers",kind:"message",T:mt,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:ht,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:Be.getEnumType(ut)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Nt},{no:19,name:"audio_features",kind:"enum",T:Be.getEnumType(nt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Be.getEnumType(Je)}])),mt=Be.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Be.getEnumType(Ye)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}])),gt=Be.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Be.getEnumType(ft)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:kt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:vt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:yt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Tt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:He,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:St,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:wt,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Et,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Pt,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Bt,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Vt,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:qt,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),ft=Be.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),vt=Be.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:bt,repeated:!0}])),bt=Be.makeMessageType("livekit.SpeakerInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}])),kt=Be.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}])),yt=Be.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Tt=Be.makeMessageType("livekit.Transcription",(()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Ct,repeated:!0}])),Ct=Be.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),St=Be.makeMessageType("livekit.ChatMessage",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}])),wt=Be.makeMessageType("livekit.RpcRequest",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}])),Et=Be.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Pt=Be.makeMessageType("livekit.RpcResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Rt,oneof:"value"}])),Rt=Be.makeMessageType("livekit.RpcError",(()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}])),It=Be.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Mt=Be.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Be.getEnumType(Ot)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}])),Ot=Be.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),At=Be.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Be.getEnumType(Dt)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}])),Dt=Be.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),Lt=Be.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:xt},{no:2,name:"screen",kind:"message",T:xt},{no:3,name:"resume_connection",kind:"enum",T:Be.getEnumType(Ze)},{no:4,name:"disabled_codecs",kind:"message",T:_t},{no:5,name:"force_relay",kind:"enum",T:Be.getEnumType(Ze)}])),xt=Be.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Be.getEnumType(Ze)}])),_t=Be.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ot,repeated:!0},{no:2,name:"publish",kind:"message",T:ot,repeated:!0}])),Nt=Be.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Ut=Be.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),jt=Be.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Be.getEnumType(Ut)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}]),{localName:"DataStream_TextHeader"}),Ft=Be.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Bt=Be.makeMessageType("livekit.DataStream.Header",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:Be.getEnumType(ut)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:jt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Ft,oneof:"content_header"}]),{localName:"DataStream_Header"}),Vt=Be.makeMessageType("livekit.DataStream.Chunk",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}]),{localName:"DataStream_Chunk"}),qt=Be.makeMessageType("livekit.DataStream.Trailer",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]),{localName:"DataStream_Trailer"}),Kt=Be.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Ht=Be.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Gt=Be.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),zt=Be.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:ii,oneof:"message"},{no:2,name:"answer",kind:"message",T:ii,oneof:"message"},{no:3,name:"trickle",kind:"message",T:$t,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Qt,oneof:"message"},{no:5,name:"mute",kind:"message",T:Yt,oneof:"message"},{no:6,name:"subscription",kind:"message",T:si,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:oi,oneof:"message"},{no:8,name:"leave",kind:"message",T:ci,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:li,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Si,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Pi,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Mi,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:ui,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Oi,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ri,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ai,oneof:"message"}])),Wt=Be.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Xt,oneof:"message"},{no:2,name:"answer",kind:"message",T:ii,oneof:"message"},{no:3,name:"offer",kind:"message",T:ii,oneof:"message"},{no:4,name:"trickle",kind:"message",T:$t,oneof:"message"},{no:5,name:"update",kind:"message",T:ni,oneof:"message"},{no:6,name:"track_published",kind:"message",T:ei,oneof:"message"},{no:8,name:"leave",kind:"message",T:ci,oneof:"message"},{no:9,name:"mute",kind:"message",T:Yt,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:pi,oneof:"message"},{no:11,name:"room_update",kind:"message",T:mi,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:fi,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:bi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Ti,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:wi,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ti,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Zt,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Ai,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:xi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:_i,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Ui,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Ei,oneof:"message"}])),Jt=Be.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),Qt=Be.makeMessageType("livekit.AddTrackRequest",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:Be.getEnumType(Qe)},{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:Be.getEnumType($e)},{no:9,name:"layers",kind:"message",T:mt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Jt,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:Be.getEnumType(ut)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Be.getEnumType(Je)},{no:17,name:"audio_features",kind:"enum",T:Be.getEnumType(nt),repeated:!0}])),$t=Be.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Be.getEnumType(Kt)},{no:3,name:"final",kind:"scalar",T:8}])),Yt=Be.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Xt=Be.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:st},{no:2,name:"participant",kind:"message",T:at},{no:3,name:"other_participants",kind:"message",T:at,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:hi,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:Lt},{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:Mt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ot,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),Zt=Be.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:hi,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Lt},{no:3,name:"server_info",kind:"message",T:Mt},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),ei=Be.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:pt}])),ti=Be.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),ii=Be.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}])),ni=Be.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:at,repeated:!0}])),si=Be.makeMessageType("livekit.UpdateSubscription",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:It,repeated:!0}])),oi=Be.makeMessageType("livekit.UpdateTrackSettings",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:Be.getEnumType(Ye)},{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}])),ri=Be.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Be.getEnumType(nt),repeated:!0}])),ai=Be.makeMessageType("livekit.UpdateLocalVideoTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}])),ci=Be.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Be.getEnumType(et)},{no:3,name:"action",kind:"enum",T:Be.getEnumType(di)},{no:4,name:"regions",kind:"message",T:Di}])),di=Be.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),li=Be.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:mt,repeated:!0}])),ui=Be.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}])),hi=Be.makeMessageType("livekit.ICEServer",(()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}])),pi=Be.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:bt,repeated:!0}])),mi=Be.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:st}])),gi=Be.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Be.getEnumType(Xe)},{no:3,name:"score",kind:"scalar",T:2}])),fi=Be.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:gi,repeated:!0}])),vi=Be.makeMessageType("livekit.StreamStateInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Be.getEnumType(Ht)}])),bi=Be.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:vi,repeated:!0}])),ki=Be.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Be.getEnumType(Ye)},{no:2,name:"enabled",kind:"scalar",T:8}])),yi=Be.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ki,repeated:!0}])),Ti=Be.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ki,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:yi,repeated:!0}])),Ci=Be.makeMessageType("livekit.TrackPermission",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}])),Si=Be.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Ci,repeated:!0}])),wi=Be.makeMessageType("livekit.SubscriptionPermissionUpdate",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}])),Ei=Be.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:st},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:at},{no:4,name:"other_participants",kind:"message",T:at,repeated:!0}])),Pi=Be.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:ii},{no:2,name:"subscription",kind:"message",T:si},{no:3,name:"publish_tracks",kind:"message",T:ei,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ii,repeated:!0},{no:5,name:"offer",kind:"message",T:ii},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Ri,repeated:!0}])),Ri=Be.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Ii=Be.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:Be.getEnumType(Kt)}])),Mi=Be.makeMessageType("livekit.SimulateScenario",(()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:Be.getEnumType(Gt),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}])),Oi=Be.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Ai=Be.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Di=Be.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Li,repeated:!0}])),Li=Be.makeMessageType("livekit.RegionInfo",(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}])),xi=Be.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Be.getEnumType(it)}])),_i=Be.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Be.getEnumType(Ni)},{no:3,name:"message",kind:"scalar",T:9}])),Ni=Be.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Ui=Be.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));function ji(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Fi,Bi={exports:{}},Vi=Bi.exports;var qi,Ki,Hi=(Fi||(Fi=1,function(e){var t,i;t=Vi,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},o=null;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 a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var o=n[s];this[o]=s<i?e:this.methodFactory(o,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,o){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?r(console,n):void 0!==console.log?r(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var r,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:r},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(o!==u&&(r=m(o.getLevel())),c.call(u),o===u)for(var e in s)s[e].rebuild()},r=m(o?o.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(o=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,o.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=h),o},o.getLoggers=function(){return s},o.default=o,o},e.exports?e.exports=i():t.log=i()}(Bi)),Bi.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(qi||(qi={})),function(e){e.Default="livekit",e.Room="livekit-room",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(Ki||(Ki={}));let Gi=Hi.getLogger("livekit");function zi(e){const t=Hi.getLogger(e);return t.setDefaultLevel(Gi.getLevel()),t}Object.values(Ki).map((e=>Hi.getLogger(e))),Gi.setDefaultLevel(qi.info);const Wi=Hi.getLogger("lk-e2ee"),Ji=7e3,Qi=[0,300,1200,2700,4800,Ji,Ji,Ji,Ji,Ji];function $i(e,t,i,n){return new(i||(i=Promise))((function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}function Yi(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 Xi(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Yi(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,s){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var Zi,en={exports:{}};var tn=function(){if(Zi)return en.exports;Zi=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}en.exports=s,en.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,s,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,o,c,d;if(r(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),c=o[t]),void 0===c)c=o[t]=i,++e._eventsCount;else if("function"==typeof c?c=o[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(o){n.once&&e.removeEventListener(t,s),i(o)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,o=this._events;if(void 0!==o)s=s&&void 0===o.error;else if(!s)return!1;if(s){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return r(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,o,a;if(r(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,o=i.length-1;o>=0;o--)if(i[o]===t||i[o].listener===t){a=i[o].listener,s=o;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,o=Object.keys(i);for(n=0;n<o.length;++n)"removeListener"!==(s=o[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},en.exports}();let nn=!0,sn=!0;function on(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function rn(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const o=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,o),s.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.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,o.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 an(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(nn=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function cn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(sn=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function dn(){if("object"==typeof window){if(nn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function ln(e,t){sn&&console.warn(e+" is deprecated, please use "+t+" instead.")}function un(e){return"[object Object]"===Object.prototype.toString.call(e)}function hn(e){return un(e)?Object.keys(e).reduce((function(t,i){const n=un(e[i]),s=n?hn(e[i]):e[i],o=n&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[i]:s})}),{}):e}function pn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?pn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{pn(e,e.get(t),i)}))})))}function mn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&pn(e,i,s)}))})),s}const gn=dn;function fn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const r=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||r)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let r=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!r&&i.length&&t.includes("back")&&(r=i[i.length-1]),r&&(e.video.deviceId=o.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=n(e.video),gn("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return gn("chrome: "+JSON.stringify(e)),s(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function vn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function bn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else rn(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function kn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function yn(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=>mn(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}),rn(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>mn(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 Tn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Cn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Tn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const r=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),r.apply(this,arguments)):r.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:o(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 Sn(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 wn(e,t){rn(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var En=Object.freeze({__proto__:null,fixNegotiationNeeded:wn,shimAddTrackRemoveTrack:Cn,shimAddTrackRemoveTrackWithNative:Tn,shimGetSendersWithDtmf:kn,shimGetUserMedia:fn,shimMediaStream:vn,shimOnTrack:bn,shimPeerConnection:Sn,shimSenderReceiverGetStats:yn});function Pn(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){ln("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 Rn(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 In(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,o]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(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(s,o)}}function Mn(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 On(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}),rn(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function An(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){ln("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Dn(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ln(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 xn(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 _n(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 Nn(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 Un=Object.freeze({__proto__:null,shimAddTransceiver:Ln,shimCreateAnswer:Nn,shimCreateOffer:_n,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:xn,shimGetUserMedia:Pn,shimOnTrack:Rn,shimPeerConnection:In,shimRTCDataChannel:Dn,shimReceiverGetStats:On,shimRemoveStream:An,shimSenderGetStats:Mn});function jn(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function Fn(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 Bn(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,o=t.setRemoteDescription,r=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Vn(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(qn(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function qn(e){return e&&void 0!==e.video?Object.assign({},e,{video:hn(e.video)}):e}function Kn(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?(ln("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 Hn(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 Gn(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 zn(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Wn,Jn=Object.freeze({__proto__:null,shimAudioContext:zn,shimCallbacksAPI:Bn,shimConstraints:qn,shimCreateOfferLegacy:Gn,shimGetUserMedia:Vn,shimLocalStreamsAPI:jn,shimRTCIceServerUrls:Kn,shimRemoteStreamsAPI:Fn,shimTrackEventTransceiver:Hn}),Qn={exports:{}};var $n=(Wn||(Wn=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let 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],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let s=3;s<n.length;s++){const o=n[s],r=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(r){const n=t.parseRtpMap(r),s=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(n.parameters=s.length?t.parseFmtp(s[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=r.length>0&&r[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),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const r=t.matchPrefix(e,"a=sctpmap:");if(r.length>0){const e=r[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const o=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+o+" 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}(Qn)),Qn.exports),Yn=ji($n),Xn=a({__proto__:null,default:Yn},[$n]);function Zn(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=Yn.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,rn(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function es(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||rn(e,"icecandidate",(e=>{if(e.candidate){const t=Yn.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function ts(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=Yn.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Yn.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=Yn.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>s}),this._sctp=o}return i.apply(this,arguments)}}function is(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},rn(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function ns(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 ss(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)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 os(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 rs(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 as=Object.freeze({__proto__:null,removeExtmapAllowMixed:ss,shimAddIceCandidateNullOrEmpty:os,shimConnectionState:ns,shimMaxMessageSize:ts,shimParameterlessSetLocalDescription:rs,shimRTCIceCandidate:Zn,shimRTCIceCandidateRelayProtocol:es,shimSendThrowTypeError:is});!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=dn,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=parseInt(on(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(on(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=parseInt(on(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=on(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),s={browserDetails:n,commonShim:as,extractVersion:on,disableLog:an,disableWarnings:cn,sdp:Xn};switch(n.browser){case"chrome":if(!En||!Sn||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=En,os(e,n),rs(e),fn(e,n),vn(e),Sn(e,n),bn(e),Cn(e,n),kn(e),yn(e),wn(e,n),Zn(e),es(e),ns(e),ts(e,n),is(e),ss(e,n);break;case"firefox":if(!Un||!In||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Un,os(e,n),rs(e),Pn(e,n),In(e,n),Rn(e),An(e),Mn(e),On(e),Dn(e),Ln(e),xn(e),_n(e),Nn(e),Zn(e),ns(e),ts(e,n),is(e);break;case"safari":if(!Jn||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=Jn,os(e,n),rs(e),Kn(e),Gn(e),Bn(e),jn(e),Fn(e),Hn(e),Vn(e),zn(e),Zn(e),es(e),ts(e,n),is(e),ss(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const cs="lk_e2ee";var ds,ls,us,hs,ps,ms,gs,fs,vs,bs,ks;function ys(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||Ts()}function Ts(){return void 0!==window.RTCRtpScriptTransform}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(ds||(ds={})),function(e){e.KeyRatcheted="keyRatcheted"}(ls||(ls={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(us||(us={})),function(e){e.Error="cryptorError"}(hs||(hs={}));tn.EventEmitter;class Cs extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"}(ps||(ps={}));class Ss extends Cs{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=ps[t]}}class ws extends Cs{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Es extends Cs{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Ps extends Cs{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Rs extends Cs{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Is extends Cs{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Ms extends Cs{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Os extends Cs{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:Ni[t]}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(ms||(ms={})),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}}(ms||(ms={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(gs||(gs={})),function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"}(fs||(fs={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(vs||(vs={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"}(bs||(bs={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(ks||(ks={}));const As=/version\/(\d+(\.?_?\d+)+)/i;let Ds;function Ls(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const i=navigator.userAgent.toLowerCase();if(void 0===Ds||t){const e=xs.find((e=>{let{test:t}=e;return t.test(i)}));Ds=null==e?void 0:e.describe(i)}return Ds}const xs=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:_s(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Ns(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:_s(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Ns(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:_s(As,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Ns(e)})}];function _s(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function Ns(e){return e.includes("mac os")?_s(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class Us{}Us.setTimeout=function(){return setTimeout(...arguments)},Us.setInterval=function(){return setInterval(...arguments)},Us.clearTimeout=function(){return clearTimeout(...arguments)},Us.clearInterval=function(){return clearInterval(...arguments)};const js=[];var Fs;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(Fs||(Fs={}));class Bs extends tn.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=Bs.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Gi,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=zi(null!==(n=i.loggerName)&&void 0!==n?n:Ki.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Bs.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Jo(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Bs.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===Bs.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(js.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&js.splice(js.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Vs(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?ks.AudioPlaybackStarted:ks.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?ks.AudioPlaybackFailed:ks.VideoPlaybackFailed,t):"AbortError"===t.name?Gi.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Gi.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(ks.ElementAttached,e),e}detach(e){try{if(e){qs(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(ks.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{qs(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(ks.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=zi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),js.forEach((e=>{e.parentElement||(t=!1)})),t&&js.push(e)}}handleAppVisibilityChanged(){return $i(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Bs.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){co()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){co()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Vs(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)),oo()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(oo()||so())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function qs(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t,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 Qe.AUDIO;case t.Video:return Qe.VIDEO;default:return Qe.DATA}},e.kindFromProto=function(e){switch(e){case Qe.AUDIO:return t.Audio;case Qe.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return $e.CAMERA;case i.Microphone:return $e.MICROPHONE;case i.ScreenShare:return $e.SCREEN_SHARE;case i.ScreenShareAudio:return $e.SCREEN_SHARE_AUDIO;default:return $e.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case $e.CAMERA:return i.Camera;case $e.MICROPHONE:return i.Microphone;case $e.SCREEN_SHARE:return i.ScreenShare;case $e.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Ht.ACTIVE:return n.Active;case Ht.PAUSED:return n.Paused;default:return n.Unknown}}}(Bs||(Bs={}));class Ks{constructor(e,t,i,n,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Hs=["vp8","h264"],Gs=["vp8","h264","vp9","av1","h265"];function zs(e){return!!Hs.find((t=>t===e))}var Ws,Js;!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(Ws||(Ws={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(Js||(Js={}));const Qs={h90:new Ks(160,90,9e4,20),h180:new Ks(320,180,16e4,20),h216:new Ks(384,216,18e4,20),h360:new Ks(640,360,45e4,20),h540:new Ks(960,540,8e5,25),h720:new Ks(1280,720,17e5,30),h1080:new Ks(1920,1080,3e6,30),h1440:new Ks(2560,1440,5e6,30),h2160:new Ks(3840,2160,8e6,30)},$s={h120:new Ks(160,120,7e4,20),h180:new Ks(240,180,125e3,20),h240:new Ks(320,240,14e4,20),h360:new Ks(480,360,33e4,20),h480:new Ks(640,480,5e5,20),h540:new Ks(720,540,6e5,25),h720:new Ks(960,720,13e5,30),h1080:new Ks(1440,1080,23e5,30),h1440:new Ks(1920,1440,38e5,30)},Ys={h360fps3:new Ks(640,360,2e5,3,"medium"),h360fps15:new Ks(640,360,4e5,15,"medium"),h720fps5:new Ks(1280,720,8e5,5,"medium"),h720fps15:new Ks(1280,720,15e5,15,"medium"),h720fps30:new Ks(1280,720,2e6,30,"medium"),h1080fps15:new Ks(1920,1080,25e5,15,"medium"),h1080fps30:new Ks(1920,1080,5e6,30,"medium"),original:new Ks(0,0,7e6,30,"medium")},Xs="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Zs(e){return $i(this,void 0,void 0,(function*(){return new Promise((t=>Us.setTimeout(t,e)))}))}function eo(){return"addTransceiver"in RTCPeerConnection.prototype}function to(){return"addTrack"in RTCPeerConnection.prototype}function io(e){return"av1"===e||"vp9"===e}function no(e){return!(!document||ro())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function so(){var e;return"Firefox"===(null===(e=Ls())||void 0===e?void 0:e.name)}function oo(){var e;return"Safari"===(null===(e=Ls())||void 0===e?void 0:e.name)}function ro(){const e=Ls();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function ao(){var e,t;return!!co()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function co(){return"undefined"!=typeof document}function lo(){return"ReactNative"==navigator.product}function uo(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function ho(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function po(){if(!lo())return;let e=ho();return e?e.platform:void 0}function mo(){if(co())return window.devicePixelRatio;if(lo()){let e=ho();if(e)return e.devicePixelRatio}return 1}function go(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let e=0;e<s;++e){const t=parseInt(i[e],10),o=parseInt(n[e],10);if(t>o)return 1;if(t<o)return-1;if(e===s-1&&t===o)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function fo(e){for(const t of e)t.target.handleResize(t)}function vo(e){for(const t of e)t.target.handleVisibilityChanged(t)}let bo=null;const ko=()=>(bo||(bo=new ResizeObserver(fo)),bo);let yo=null;const To=()=>(yo||(yo=new IntersectionObserver(vo,{root:null,rootMargin:"0px"})),yo);function Co(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const o=s.getContext("2d");null==o||o.fillRect(0,0,s.width,s.height),n&&o&&(o.beginPath(),o.arc(e/2,t/2,50,0,2*Math.PI,!0),o.closePath(),o.fillStyle="grey",o.fill());const r=s.captureStream(),[a]=r.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let So;function wo(){if(!So){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(),[So]=n.stream.getAudioTracks(),!So)throw Error("Could not get empty media stream audio track");So.enabled=!1}return So.clone()}class Eo{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,i)=>$i(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)}))}}function Po(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Ro(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Io(e){switch(e.reason){case ps.LeaveRequest:return e.context;case ps.Cancelled:return et.CLIENT_INITIATED;case ps.NotAllowed:return et.USER_REJECTED;case ps.ServerUnreachable:return et.JOIN_FAILURE;default:return et.UNKNOWN_REASON}}function Mo(e){return void 0!==e?Number(e):void 0}function Oo(e){return void 0!==e?BigInt(e):void 0}function Ao(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Do(e){return!!e&&e.kind==Bs.Kind.Audio}function Lo(e){return!!e&&e.kind==Bs.Kind.Video}function xo(e){return Ao(e)&&Lo(e)}function _o(e){return Ao(e)&&Do(e)}function No(e){return!!e&&!e.isLocal}function Uo(e){return!!e&&!e.isLocal}function jo(e){return No(e)&&Lo(e)}function Fo(e,t,i){var n,s,o,r;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=Qo(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(Bo(h.audio,t),null!==(n=(o=h.audio).deviceId)&&void 0!==n||(o.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(Bo(h.video,i),null!==(s=(r=h.video).deviceId)&&void 0!==s||(r.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function Bo(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function Vo(e){var t,i,n,s;const o={};if(e.video)if("object"==typeof e.video){const i={},s=i,r=e.video;Object.keys(r).forEach((e=>{if("resolution"===e)Bo(s,r.resolution);else s[e]=r[e]})),o.video=i,null!==(t=(n=o.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else o.video=!!e.video&&{deviceId:{ideal:"default"}};else o.video=!1;return e.audio?"object"==typeof e.audio?(o.audio=e.audio,null!==(i=(s=o.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):o.audio={deviceId:{ideal:"default"}}:o.audio=!1,o}function qo(e){return $i(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Ko();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield Zs(t),n.getByteTimeDomainData(o);const r=o.some((e=>128!==e&&0!==e));return i.close(),!r}return!1}()}))}function Ko(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>$i(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}));window.document.body.addEventListener("click",e)}return i}}function Ho(e){return"audioinput"===e?Bs.Source.Microphone:"videoinput"===e?Bs.Source.Camera:Bs.Source.Unknown}function Go(e){return e===Bs.Source.Microphone?"audioinput":e===Bs.Source.Camera?"videoinput":void 0}function zo(e){return e.split("/")[1].toLowerCase()}function Wo(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new ei({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function Jo(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?Jo(e.track):{})}}function Qo(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function $o(e,t){return e.width*e.height<t.width*t.height}class Yo extends tn.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":Gi.error(s.error.message),this.emit(us.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(us.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(us.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(ds.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex)}},this.onWorkerError=e=>{Gi.error("e2ee worker encountered an error:",{error:e.error}),this.emit(us.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!ys())throw new ws("tried to setup end-to-end encryption on an unsupported browser");if(Gi.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Wi.getLevel()}};this.worker&&(Gi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Gi.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Gi.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(bs.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on(fs.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ut.NONE,t.identity))),e.on(fs.ConnectionStateChanged,(t=>{t===_a.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==ut.NONE,e.identity)}))}))})).on(fs.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(fs.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(fs.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach((e=>{this.postKey(e)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),e.localParticipant.on(vs.LocalSenderCreated,((e,t)=>$i(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.on(ds.SetKey,(e=>this.postKey(e))).on(ds.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(o)}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?zo(i.mimeType):void 0)}}setupE2EESender(e,t){Ao(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Gi.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return $i(this,void 0,void 0,(function*(){if(this.worker){if(Ts()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(cs in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,o=e.readableStream;if(!s||!o){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,o=t.readable}const r={kind:"decode",data:{readableStream:o,writableStream:s,trackId:t,codec:n,participantIdentity:i,isReuse:cs in e}};this.worker.postMessage(r,[o,s])}e[cs]=!0}}))}handleSender(e,t,i){var n;if(!(cs 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(Ts()){Gi.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{Gi.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(s,[n.readable,n.writable])}e[cs]=!0}}}const Xo="default";class Zo{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Zo),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=Zo.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Gi.debug("awaiting getUserMedia promise");try{e?yield Zo.userMediaPromiseMap.get(e):yield Promise.all(Zo.userMediaPromiseMap.values())}catch(e){Gi.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!oo()||!t.hasDeviceInUse(e))){if(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return $i(this,void 0,void 0,(function*(){if(t!==Xo)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===Xo));if(!s)return void Gi.warn("could not reliably determine default device");const o=n.find((e=>e.deviceId!==Xo&&e.groupId===(null!=i?i:s.groupId)));if(o)return null==o?void 0:o.deviceId;Gi.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Zo.userMediaPromiseMap.has(e):Zo.userMediaPromiseMap.size>0}}var er;Zo.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Zo.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(er||(er={}));class tr{constructor(){this.pendingTasks=new Map,this.taskMutex=new l,this.nextTaskIndex=0}run(e){return $i(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:er.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=er.RUNNING,yield e()}finally{t.status=er.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return $i(this,void 0,void 0,(function*(){return this.run((()=>$i(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function ir(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const nr=["syncState","trickle","offer","answer","simulate","leave"];var sr;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(sr||(sr={}));class or{get currentState(){return this.state}get isDisconnected(){return this.state===sr.DISCONNECTING||this.state===sr.DISCONNECTED}get isEstablishingConnection(){return this.state===sr.CONNECTING||this.state===sr.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=sr.DISCONNECTED,this.log=Gi,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=zi(null!==(i=t.loggerName)&&void 0!==i?i:Ki.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new tr,this.queuedRequests=[],this.closingLock=new l,this.connectionLock=new l,this.state=sr.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return $i(this,void 0,void 0,(function*(){this.state=sr.CONNECTING,this.options=i;return yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return $i(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=sr.RECONNECTING,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;const s=function(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",lo()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return s}(t,function(){var e;const t=new At({sdk:Dt.JS,protocol:16,version:"2.15.4"});return lo()&&(t.os=null!==(e=po())&&void 0!==e?e:""),t}(),i),o=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{i.searchParams.set(t,e)})),ir(i,"rtc")}(e,s),r=ir(new URL(Ro(o)),"validate");return new Promise(((e,t)=>$i(this,void 0,void 0,(function*(){const s=yield this.connectionLock.lock();try{const s=()=>$i(this,void 0,void 0,(function*(){this.close(),clearTimeout(a),t(new Ss("room connection has been cancelled (signal)",ps.Cancelled))})),a=setTimeout((()=>{this.close(),t(new Ss("room connection has timed out (signal)",ps.ServerUnreachable))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&s(),null==n||n.addEventListener("abort",s);const c=new URL(o);c.searchParams.has("access_token")&&c.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(c),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(a)},this.ws.onerror=e=>$i(this,void 0,void 0,(function*(){if(this.state===sr.CONNECTED)this.handleWSError(e);else{this.state=sr.DISCONNECTED,clearTimeout(a);try{const i=yield fetch(r);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();t(new Ss(e,ps.NotAllowed,i.status))}else t(new Ss("Encountered unknown websocket error during connection: ".concat(e.toString()),ps.InternalError,i.status))}catch(e){t(new Ss(e instanceof Error?e.message:"server was not reachable",ps.ServerUnreachable))}}})),this.ws.onmessage=o=>$i(this,void 0,void 0,(function*(){var r,a,c;let d;if("string"==typeof o.data){const e=JSON.parse(o.data);d=Wt.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(o.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof o.data),this.logContext);d=Wt.fromBinary(new Uint8Array(o.data))}if(this.state!==sr.CONNECTED){let o=!1;if("join"===(null===(r=d.message)||void 0===r?void 0:r.case)?(this.state=sr.CONNECTED,null==n||n.removeEventListener("abort",s),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),e(d.message.value)):this.state===sr.RECONNECTING&&"leave"!==d.message.case?(this.state=sr.CONNECTED,null==n||n.removeEventListener("abort",s),this.startPingInterval(),"reconnect"===(null===(a=d.message)||void 0===a?void 0:a.case)?e(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),o=!0)):this.isEstablishingConnection&&"leave"===d.message.case?t(new Ss("Received leave request while trying to (re)connect",ps.LeaveRequest,void 0,d.message.value.reason)):i.reconnect||t(new Ss("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"),ps.InternalError)),!o)return}this.signalLatency&&(yield Zs(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new Ss("Websocket got closed during a (re)connection attempt",ps.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{s()}}))))}close(){return $i(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=sr.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,Zs(250)])),e.ws=void 0}}finally{t&&(e.state=sr.DISCONNECTED),i()}}()}))}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:ar(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:ar(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new $t({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Yt({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return $i(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new ui({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new li({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Si({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:D.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Oi({timestamp:D.parse(Date.now()),rtt:D.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new ri({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ci({reason:et.CLIENT_INITIATED,action:di.DISCONNECT})})}sendRequest(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=nr.indexOf(e.case)>=0;return Gi.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===sr.RECONNECTING)return void t.queuedRequests.push((()=>$i(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield Zs(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new zt({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=rr(n.value);this.onAnswer&&this.onAnswer(e,n.value.id)}else if("offer"===n.case){const e=rr(n.value);this.onOffer&&this.onOffer(e,n.value.id)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return $i(this,void 0,void 0,(function*(){if(this.state===sr.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Us.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&Us.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Us.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Us.clearInterval(this.pingInterval)}}function rr(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 ar(e,t){return new ii({sdp:e.sdp,type:e.type,id:t})}class cr{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class dr{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[n,s]of i.entries())t.push(e(s,n,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var lr,ur,hr,pr,mr,gr={},fr={},vr={exports:{}};function br(){if(lr)return vr.exports;lr=1;var e=vr.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"]}]};return Object.keys(e).forEach((function(t){e[t].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),vr.exports}function kr(){return ur||(ur=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(i[n[o]]=t(e[o+1]))}(n.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},n=br(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],r=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),r=o[o.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,r,s)}})),t.media=o,t};var o=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(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},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}}))}))}}(fr)),fr}function yr(){if(pr)return hr;pr=1;var e=br(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,(function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var r=t.names[o];t.name?s.push(n[t.name][r]):s.push(n[t.names[o]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return hr=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=i.outerOrder||s,a=i.innerOrder||o,c=[];return r.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))})),t.media.forEach((function(t){c.push(n("m",e.m[0],t)),a.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))}))})),c.join("\r\n")+"\r\n"},hr}var Tr=function(){if(mr)return gr;mr=1;var e=kr(),t=yr(),i=br();return gr.grammar=i,gr.write=t,gr.parse=e.parse,gr.parseParams=e.parseParams,gr.parseFmtpConfig=e.parseFmtpConfig,gr.parsePayloads=e.parsePayloads,gr.parseRemoteCandidates=e.parseRemoteCandidates,gr.parseImageAttributes=e.parseImageAttributes,gr.parseSimulcastStreamList=e.parseSimulcastStreamList,gr}();function Cr(e,t,i){var n,s,o;void 0===t&&(t=50),void 0===i&&(i={});var r=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[];function u(){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,s){var c=r&&void 0===o;if(void 0!==o&&clearTimeout(o),o=setTimeout((function(){if(o=void 0,d=Date.now(),!r){var n=e.apply(i,t);a&&a(n),l.forEach((function(e){return(0,e.resolve)(n)})),l=[]}}),u()),c){var h=e.apply(i,t);return a&&a(h),n(h)}l.push({resolve:n,reject:s})}))};return h.cancel=function(e){void 0!==o&&clearTimeout(o),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},h}const Sr="negotiationStarted",wr="negotiationComplete",Er="rtpVideoPayloadTypes";class Pr extends tn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Gi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Cr((e=>$i(this,void 0,void 0,(function*(){this.emit(Sr);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=zi(null!==(i=t.loggerName)&&void 0!==i?i:Ki.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new l}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return $i(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e,t){return $i(this,void 0,void 0,(function*(){var i;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Tr.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let o=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(o=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===o&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===o&&(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 t=Tr.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),n=Tr.write(t)}if(yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(wr),e.sdp)){Tr.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Er,e.rtp)}))}return!0}))}createAndSendOffer(e){return $i(this,void 0,void 0,(function*(){var t;const i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=this.latestOfferId+1;this.latestOfferId=i;const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=Tr.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(s.media.forEach((e=>{Ir(e),"audio"===e.type?Rr(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(io(t.codec)&&!oo()&&this.ensureVideoDDExtensionForSVC(e,s),"av1"!==t.codec)return!0;const n=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0}))})),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,Tr.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}}))}createAndSetAnswer(){return $i(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=Tr.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Ir(e),"audio"===e.type&&Rr(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Tr.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Rs("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Rs("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return $i(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return $i(this,void 0,void 0,(function*(){if(t){const n=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let n="unknown error";t instanceof Error?n=t.message:"string"==typeof t&&(n=t);const s={error:n,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Is(n)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Xs)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:Xs})}}}function Rr(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Ir(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}const Mr="vp8",Or={audioPreset:Js.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ys.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Mr,backupCodec:!0,preConnectBuffer:!1},Ar={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Dr={deviceId:{ideal:"default"},resolution:Qs.h720.resolution},Lr={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Qi}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1},xr={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var _r;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(_r||(_r={}));class Nr{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=xr.peerConnectionTimeout,this.log=Gi,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=_r.CONNECTED:i.some((e=>"failed"===e))?this.state=_r.FAILED:i.some((e=>"connecting"===e))?this.state=_r.CONNECTING:i.every((e=>"closed"===e))?this.state=_r.CLOSED:i.some((e=>"closed"===e))?this.state=_r.CLOSING:i.every((e=>"new"===e))&&(this.state=_r.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(_r[t]," to ").concat(_r[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=zi(null!==(n=i.loggerName)&&void 0!==n?n:Ki.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Pr(e,i),this.subscriber=new Pr(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Kt.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Kt.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=_r.NEW,this.connectionLock=new l,this.remoteOfferLock=new l}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return $i(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return $i(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return $i(this,void 0,void 0,(function*(){t===Kt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return $i(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{if(!(yield this.subscriber.setRemoteDescription(e,t)))return;return yield this.subscriber.createAndSetAnswer()}finally{i()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return $i(this,void 0,void 0,(function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return $i(this,void 0,void 0,(function*(){return new Promise(((t,i)=>$i(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(Sr,(()=>{e.signal.aborted||this.publisher.once(wr,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Kt.PUBLISHER||e===Kt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return $i(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,s)=>$i(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Us.clearTimeout(o),s(new Ss("room connection has been cancelled",ps.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const o=Us.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new Ss("could not establish pc connection",ps.InternalError))}),n);for(;this.state!==_r.CONNECTED;)if(yield Zs(50),null==t?void 0:t.signal.aborted)return void s(new Ss("room connection has been cancelled",ps.Cancelled));Us.clearTimeout(o),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}class Ur extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Fr(t,Ur.MAX_MESSAGE_BYTES),this.data=i?Fr(i,Ur.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ur(e.code,e.message,e.data)}toProto(){return new Rt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Ur(Ur.ErrorCode[e],Ur.ErrorMessage[e],t)}}Ur.MAX_MESSAGE_BYTES=256,Ur.MAX_DATA_BYTES=15360,Ur.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Ur.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};function jr(e){return(new TextEncoder).encode(e).length}function Fr(e,t){if(jr(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const o=Math.floor((i+n+1)/2);s.encode(e.slice(0,o)).length<=t?i=o:n=o-1}return e.slice(0,i)}const Br=2e3;function Vr(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)}const qr="undefined"!=typeof MediaRecorder;const Kr=qr?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class Hr extends Kr{constructor(e,t){if(!qr)throw new Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([e.mediaStreamTrack]),t);const s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),null==n||n.close(),n=void 0},o=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>$i(this,void 0,void 0,(function*(){let i;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();i=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");i=t.data.byteArray}void 0!==n&&e.enqueue(i)})),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",o)}}class Gr extends Bs{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Cr((()=>$i(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>$i(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(ks.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new l,this.pauseUpstreamLock=new l,this.processorLock=new l,this.restartLock=new l,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Bs.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return $i(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{qs(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Vs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Vs(null!=n?n:e,t)})))}))}waitForDimensions(){return $i(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===Bs.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=Ls())||void 0===i?void 0:i.os)&&(yield Zs(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield Zs(50)}throw new Es("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return $i(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Po(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Po(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return $i(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===Bs.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===Bs.Kind.Audio?"audioinput":"videoinput";return t?Zo.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return $i(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return $i(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return $i(this,void 0,void 0,(function*(){if(!this.sender)throw new Es("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this}))}restart(e){return $i(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===Bs.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||{deviceId:t},this.attachedElements.forEach((e=>{qs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield o.applyConstraints(n),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o),this._constraints=e,this.emit(ks.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}}))}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ks.Muted:ks.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 $i(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ao()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return $i(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(ks.UpstreamPaused,this);const t=Ls();if("Safari"===(null==t?void 0:t.name)&&go(t.version,"12.0")<0)throw new ws("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}}))}resumeUpstream(){return $i(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(ks.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}}))}getRTCStatsReport(){return $i(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),o={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(o),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(Vs(t._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout((()=>{s.play().catch((e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))}))}),100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))})),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(qs(t._mediaStreamTrack,e),Vs(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(ks.TrackProcessorUpdate,t.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return $i(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(ks.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(qr)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new Hr(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout((()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()}),1e4)}else this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class zr extends Gr{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,Bs.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>$i(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 this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=Vr(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ks.AudioTrackFeatureUpdate,this,nt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ks.AudioTrackFeatureUpdate,this,nt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return $i(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Bs.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return $i(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Po(this._constraints.deviceId);return this.source!==Bs.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return $i(this,void 0,void 0,(function*(){let t;if(e){const i=Vo({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 $i(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){co()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Br)))}setProcessor(e){return $i(this,void 0,void 0,(function*(){var t;const i=yield this.processorLock.lock();try{if(!lo()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(ks.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return $i(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return $i(this,void 0,void 0,(function*(){const e=yield qo(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(ks.AudioSilenceDetected)),e}))}}const Wr=Object.values(Qs),Jr=Object.values($s),Qr=Object.values(Ys),$r=[Qs.h180,Qs.h360],Yr=[$s.h180,$s.h360],Xr=["q","h","f"];function Zr(e,t,i,n){var s,o;let r=null==n?void 0:n.videoEncoding;e&&(r=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!r&&!a&&!c||!t||!i)return[{}];r||(r=function(e,t,i,n){const s=function(e,t,i){if(e)return Qr;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return Wr;return Jr}(e,t,i);let{encoding:o}=s[0];const r=Math.max(t,i);for(let e=0;e<s.length;e+=1){const t=s[e];if(o=t.encoding,t.width>=r)break}if(n)switch(n){case"av1":case"h265":o=Object.assign({},o),o.maxBitrate=.7*o.maxBitrate;break;case"vp9":o=Object.assign({},o),o.maxBitrate=.85*o.maxBitrate}return o}(e,t,i,d),Gi.debug("using video encoding",r));const l=r.maxFramerate,u=new Ks(t,i,r.maxBitrate,r.maxFramerate,r.priority);if(c&&io(d)){const e=new na(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=Ls();if(ro()||lo()||"Chrome"===(null==i?void 0:i.name)&&go(null==i?void 0:i.version,"113")<0){const n="h"==e.suffix?2:3,s=function(e){return e||(e=Ls()),"Safari"===(null==e?void 0:e.name)&&go(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&go(e.osVersion,"18.3")>0}(i);for(let i=0;i<e.spatial;i+=1)t.push({rid:Xr[2-i],maxBitrate:r.maxBitrate/Math.pow(n,i),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,i):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:r.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),Gi.debug("using svc encoding",{encodings:t}),t}if(!a)return[r];let h,p=[];if(p=e?null!==(s=ia(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:ea(e,u):null!==(o=ia(null==n?void 0:n.videoSimulcastLayers))&&void 0!==o?o:ea(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return ta(t,i,[e,h,u],l);if(n>=480)return ta(t,i,[e,u],l)}return ta(t,i,[u])}function ea(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new Ks(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)}));var i;const{width:n,height:s}=t,o=n>s?n/s:s/n;return Math.abs(o-16/9)<Math.abs(o-4/3)?$r:Yr}function ta(e,t,i,n){const s=[];if(i.forEach(((i,o)=>{if(o>=Xr.length)return;const r=Math.min(e,t),a={rid:Xr[o],scaleResolutionDownBy:Math.max(1,r/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=so()||0===o;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)})),lo()&&"ios"===po()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,Gi.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Gi.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function ia(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 na{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 sa extends Gr{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,Bs.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>$i(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 this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const t=new Map(e.map((e=>[e.rid,e]))),i=e.some((e=>"cpu"===e.qualityLimitationReason));if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(ks.CpuConstrained)),this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=Vr(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new l}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!co())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()}),Br))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return $i(this,void 0,void 0,(function*(){var t,i,n,s,o;yield e.pauseUpstream.call(this);try{for(var r,a=!0,c=Xi(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.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}});return $i(this,void 0,void 0,(function*(){var t,i,n,s,o;yield e.resumeUpstream.call(this);try{for(var r,a=!0,c=Xi(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.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 $i(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==Bs.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return $i(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Bs.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return $i(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},o=i.get(e.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(e){const t=[];for(let i=Fs.LOW;i<=Fs.HIGH;i+=1)t.push(new ki({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(io(this.codec),t)}restartTrack(e){return $i(this,void 0,void 0,(function*(){var t,i,n,s,o;let r;if(e){const t=Vo({video:e});"boolean"!=typeof t.video&&(r=t.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var a,c=!0,d=Xi(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(o=e.sender.transport)||void 0===o?void 0:o.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){i={error:e}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return $i(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,o,r,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Xi(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(e){o={error:e}}finally{try{u||s||!(r=h.return)||(yield r.call(h))}finally{if(o)throw o.error}}}()}))}setDegradationPreference(e){return $i(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return $i(this,void 0,void 0,(function*(){var t,i,n,s,o,r,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(io(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Xi(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield oa(t.sender,t.encodings,e.qualities,this.senderLock,io(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(io(e.codec),e.qualities)}}catch(e){o={error:e}}finally{try{t||s||!(r=i.return)||(yield r.call(i))}finally{if(o)throw o.error}}return c}))}setPublishingLayers(e,t){return $i(this,void 0,void 0,(function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield oa(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return $i(this,void 0,void 0,(function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const e=this.sender.getParameters();e.encodings=e.encodings.map(((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&io(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})})),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return $i(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ao()&&this.isInBackground&&this.source===Bs.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function oa(e,t,i,n,s,o,r){return $i(this,void 0,void 0,(function*(){const a=yield n.lock();o.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void o.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(s){i.some((e=>e.enabled))&&i.forEach((e=>e.enabled=!0))}a.forEach(((e,n)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=ra(a),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,o.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),so()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}))}c&&(n.encodings=a,o.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}}))}function ra(e){switch(e){case"f":default:return Fs.HIGH;case"h":return Fs.MEDIUM;case"q":return Fs.LOW}}function aa(e,t,i,n){if(!i)return[new mt({quality:Fs.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new na(n),o=[],r="h"==s.suffix?1.5:2,a="h"==s.suffix?2:3;for(let n=0;n<s.spatial;n+=1)o.push(new mt({quality:Math.min(Fs.HIGH,s.spatial-1)-n,width:Math.ceil(e/Math.pow(r,n)),height:Math.ceil(t/Math.pow(r,n)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,n)):0,ssrc:0}));return o}return i.map((i=>{var n,s,o;const r=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=ra(null!==(s=i.rid)&&void 0!==s?s:"");return new mt({quality:a,width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:null!==(o=i.maxBitrate)&&void 0!==o?o:0,ssrc:0})}))}const ca="_lossy",da="_reliable",la="leave-reconnect";var ua;!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"}(ua||(ua={}));class ha extends tn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=xr.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=ua.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Gi,this.reliableDataSequence=1,this.reliableMessageBuffer=new cr,this.reliableReceivedState=new dr(3e4),this.handleDataChannel=e=>$i(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===da)t.reliableDCSub=i;else{if(i.label!==ca)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=e=>$i(this,void 0,void 0,(function*(){var t,i;const n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));n=yield e.data.arrayBuffer()}const s=gt.fromBinary(new Uint8Array(n));if(s.sequence>0&&""!==s.participantSid){const e=this.reliableReceivedState.get(s.participantSid);if(e&&s.sequence<=e)return;this.reliableReceivedState.set(s.participantSid,s.sequence)}"speaker"===(null===(t=s.value)||void 0===t?void 0:t.case)?this.emit(bs.ActiveSpeakersUpdate,s.value.value.speakers):("user"===(null===(i=s.value)||void 0===i?void 0:i.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(s,s.value.value),this.emit(bs.DataPacketReceived,s))}finally{n()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?ft.LOSSY:ft.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(bs.Disconnected),this.close()},n=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==s?(e===la&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Us.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),s)):i(n)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===ua.Connected&&e();const i=()=>{this.off(bs.Disconnected,n),e()},n=()=>{this.off(bs.Restarted,i),t()};this.once(bs.Restarted,i),this.once(bs.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(bs.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return e===ft.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount),t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===sr.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(tt.RR_SIGNAL_DISCONNECTED))},this.log=zi(null!==(t=e.loggerName)&&void 0!==t?t:Ki.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new or(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new l,this.dataProcessLock=new l,this.dcBufferStatus=new Map([[ft.LOSSY,!0],[ft.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(bs.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(bs.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(bs.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(bs.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(bs.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(bs.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(bs.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(bs.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,o;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(o=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===o?void 0:o.identity,pID:this.participantSid}}join(e,t,i,n){return $i(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,this.emit(bs.SignalConnected,s),s}catch(s){if(s instanceof Ss&&s.reason===ps.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}}))}close(){return $i(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(bs.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return $i(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new cr,this.reliableDataSequence=1,this.reliableReceivedState.clear()}))}cleanupClient(){return $i(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Es("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 Ss("publication of local track timed out, no response from server",ps.Timeout))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return $i(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return $i(this,void 0,void 0,(function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==_r.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new Nr(n,e.subscriberPrimary,this.loggerOptions),this.emit(bs.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>$i(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===_r.CONNECTED){const t=this.pcState===ua.New;this.pcState=ua.Connected,t&&this.emit(bs.Connected,e)}else t===_r.FAILED&&this.pcState===ua.Connected&&(this.pcState=ua.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?tt.RR_SUBSCRIBER_FAILED:tt.RR_PUBLISHER_FAILED));const s=this.client.isDisconnected||this.client.currentState===sr.RECONNECTING,o=[_r.FAILED,_r.CLOSING,_r.CLOSED].includes(t);s&&o&&!this._isClosed&&this.emit(bs.Offline)})),this.pcManager.onTrack=e=>{this.emit(bs.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=(e,t)=>$i(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,t))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t)=>$i(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);i&&this.client.sendAnswer(i,t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(bs.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(bs.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(bs.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(bs.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(bs.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",tt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case di.DISCONNECT:this.emit(bs.Disconnected,null==e?void 0:e.reason),this.close();break;case di.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(la);break;case di.RESUME:this.handleDisconnect(la)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ze.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(ca,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(da,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,i){return $i(this,void 0,void 0,(function*(){if(eo()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(to()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new Rs("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return $i(this,void 0,void 0,(function*(){if(eo())return this.createSimulcastTransceiverSender(e,t,i,n);if(to())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Rs("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return $i(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Rs("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Lo(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};i&&(s.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return $i(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Rs("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender}))}createRTCRtpSender(e){return $i(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Rs("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return $i(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)Gi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Ze.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:_r.NEW)!==_r.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof Rs?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof pa||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",tt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(bs.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return $i(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new Rs("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(bs.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new pa;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof Ss&&e.reason===ps.NotAllowed)throw new Rs("could not reconnect, token might be expired");throw new pa}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(bs.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==sr.CONNECTED)throw new pa("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(bs.Restarted)}catch(e){const t=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),e}}))}resumeConnection(e){return $i(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new Rs("could not reconnect, url or token not saved");if(!this.pcManager)throw new Rs("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(bs.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t="";if(e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof Ss&&e.reason===ps.NotAllowed)throw new Rs("could not reconnect, token might be expired");if(e instanceof Ss&&e.reason===ps.LeaveRequest)throw e;throw new pa(t)}if(this.emit(bs.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==sr.CONNECTED)throw new pa("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(bs.Resumed)}))}waitForPCInitialConnection(e,t){return $i(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Rs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return $i(this,void 0,void 0,(function*(){this.pcState=ua.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Zs(2e3),!this.pcManager)throw new Rs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ua.Connected}catch(e){throw this.pcState=ua.Disconnected,new Ss("could not establish PC connection, ".concat(e.message),ps.InternalError)}}))}publishRpcResponse(e,t,i,n){return $i(this,void 0,void 0,(function*(){const s=new gt({destinationIdentities:[e],kind:ft.RELIABLE,value:{case:"rpcResponse",value:new Pt({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,ft.RELIABLE)}))}publishRpcAck(e,t){return $i(this,void 0,void 0,(function*(){const i=new gt({destinationIdentities:[e],kind:ft.RELIABLE,value:{case:"rpcAck",value:new Et({requestId:t})}});yield this.sendDataPacket(i,ft.RELIABLE)}))}sendDataPacket(e,t){return $i(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(t),t===ft.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===ft.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)}))}resendReliableMessagesForResume(e){return $i(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(ft.RELIABLE);const t=this.dataChannelForKind(ft.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach((e=>{t.send(e.data)}))),this.updateAndEmitDCBufferStatus(ft.RELIABLE)}))}waitForBufferStatusLow(e){return new Promise(((t,i)=>$i(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(bs.Closing,n);!this.dcBufferStatus.get(e);)yield Zs(10);this.off(bs.Closing,n),t()}}))))}ensureDataTransportConnected(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new Rs("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new Ss("".concat(o," connection not set"),ps.InternalError);let r=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),r=!0),r||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(r=!0),r&&t.negotiate();const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield Zs(50)}throw new Ss("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),ps.InternalError)}()}))}ensurePublisherConnected(e){return $i(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===_r.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return $i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>$i(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new Is("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(bs.Closing,n),this.pcManager.publisher.once(Er,(e=>{const t=new Map;e.forEach((e=>{const i=e.codec.toLowerCase();var n;n=i,Gs.includes(n)&&t.set(e.payload,i)})),this.emit(bs.RTPVideoMapUpdate,t)}));try{yield this.pcManager.negotiate(i),e()}catch(e){e instanceof Is&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",tt.RR_UNKNOWN),t(e)}finally{this.off(bs.Closing,n)}}))))}))}dataChannelForKind(e,t){if(t){if(e===ft.LOSSY)return this.lossyDCSub;if(e===ft.RELIABLE)return this.reliableDCSub}else{if(e===ft.LOSSY)return this.lossyDC;if(e===ft.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),r=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array,c=new Array;e.forEach((e=>{e.isDesired!==r&&a.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new Pi({answer:s?ar({sdp:s.sdp,type:s.type}):void 0,offer:o?ar({sdp:o.sdp,type:o.type}):void 0,subscription:new si({trackSids:a,subscribe:!r,participantTracks:[]}),publishTracks:Wo(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new Ri({publisherSid:t,lastSeq:e})))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Ii({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(ft.LOSSY),Kt.PUBLISHER),t(this.dataChannelForKind(ft.RELIABLE),Kt.PUBLISHER),t(this.dataChannelForKind(ft.LOSSY,!0),Kt.SUBSCRIBER),t(this.dataChannelForKind(ft.RELIABLE,!0),Kt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Us.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){co()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){co()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class pa extends Error{}class ma{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 uo(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return $i(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),Gi.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return $i(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 Ss("Could not fetch region settings: ".concat(t.statusText),401===t.status?ps.NotAllowed:ps.InternalError,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class ga{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class fa extends ga{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>$i(this,void 0,void 0,(function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch(e){return{done:!0,value:void 0}}})),return(){return $i(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return $i(this,void 0,void 0,(function*(){var e,t,i,n;let s=new Set;try{for(var o,r=!0,a=Xi(this);!(e=(o=yield a.next()).done);r=!0){n=o.value,r=!1;const e=n;s.add(e)}}catch(e){t={error:e}}finally{try{r||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return Array.from(s)}))}}class va extends ga{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Mo(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>$i(this,void 0,void 0,(function*(){try{const{done:i,value:n}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)})}catch(e){return{done:!0,value:void 0}}})),return(){return $i(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return $i(this,void 0,void 0,(function*(){var e,t,i,n;let s="";try{for(var o,r=!0,a=Xi(this);!(e=(o=yield a.next()).done);r=!0){n=o.value,r=!1;s+=n}}catch(e){t={error:e}}finally{try{r||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return s}))}}class ba{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return $i(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class ka extends ba{}class ya extends ba{}class Ta extends Bs{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ks.Muted:ks.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(ks.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return $i(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),Br)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame((()=>e()));const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(ks.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Ca extends Ta{constructor(e,t,i,n,s,o){super(e,t,Bs.Kind.Audio,i,o),this.monitorReceiver=()=>$i(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=Vr(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;lo()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(lo())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return $i(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(no(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&no(e)&&e.setSinkId(this.sinkId).catch((e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)})),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then((()=>{"running"!==e.state&&this.emit(ks.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(ks.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return $i(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Sa extends Ta{constructor(e,t,i,n,s){super(e,t,Bs.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>$i(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=Vr(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Cr((()=>{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?qs(this._mediaStreamTrack,t):Vs(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 wa(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const 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 $i(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return $i(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!n||s;this.lastVisible!==o&&(!o&&Date.now()-i<100?Us.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(ks.VisibilityChanged,o,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,o=e.height()*s;t+o>i+n&&(i=t,n=o)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(ks.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return mo();if(!t){return mo()>2?2:1}return t}}class wa{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=Ea(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ea(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=Ea(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Pa(e),this.isPiP=co()&&Ea(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Pa(this.element),this.isPiP=Ea(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,To().observe(this.element),ko().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=To())||void 0===e||e.unobserve(this.element),null===(t=ko())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function Ea(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Pa(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Pa(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const o=e.offsetWidth,r=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+r>i.pageYOffset&&s+o>i.pageXOffset&&!a&&"none"!==c}class Ra extends tn.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=ut.NONE,this.log=Gi,this.handleMuted=()=>{this.emit(ks.Muted)},this.handleUnmuted=()=>{this.emit(ks.Unmuted)},this.log=zi(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:Ki.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=Bs.Source.Unknown}setTrack(e){this.track&&(this.track.off(ks.Muted,this.handleMuted),this.track.off(ks.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ks.Muted,this.handleMuted),e.on(ks.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Jo(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ut.NONE}get audioTrack(){if(Do(this.track))return this.track}get videoTrack(){if(Lo(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Bs.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Bs.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}!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"}(Ra||(Ra={}));class Ia extends Ra{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(ks.Ended)},this.handleCpuConstrained=()=>{this.track&&Lo(this.track)&&this.emit(ks.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(ks.Ended,this.handleTrackEnded),this.track.off(ks.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ks.Ended,this.handleTrackEnded),e.on(ks.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return $i(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return $i(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return $i(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return $i(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(Do(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(nt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(nt.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(nt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(nt.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(nt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(nt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function Ma(e,t){return $i(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:o}=Qo(e);let r=o.audio,a=o.video;if(n&&"object"==typeof o.audio&&(o.audio.processor=n),s&&"object"==typeof o.video&&(o.video.processor=s),e.audio&&"object"==typeof o.audio&&"string"==typeof o.audio.deviceId){const e=o.audio.deviceId;o.audio.deviceId={exact:e},i=!0,r=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&"object"==typeof o.video&&"string"==typeof o.video.deviceId){const e=o.video.deviceId;o.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}(!0===o.audio||"object"==typeof o.audio&&!o.audio.deviceId)&&(o.audio={deviceId:"default"}),!0===o.video?o.video={deviceId:"default"}:"object"!=typeof o.video||o.video.deviceId||(o.video.deviceId="default");const c=Fo(o,Ar,Dr),d=Vo(c),l=navigator.mediaDevices.getUserMedia(d);o.audio&&(Zo.userMediaPromiseMap.set("audioinput",l),l.catch((()=>Zo.userMediaPromiseMap.delete("audioinput")))),o.video&&(Zo.userMediaPromiseMap.set("videoinput",l),l.catch((()=>Zo.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>$i(this,void 0,void 0,(function*(){const o="audio"===i.kind;let r,a=o?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=o?d.audio:d.video;"boolean"!=typeof l&&(r=l);const u=i.getSettings().deviceId;(null==r?void 0:r.deviceId)&&Po(r.deviceId)!==u?r.deviceId=u:r||(r={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new zr(e,t,!1,void 0,i);case"video":return new sa(e,t,!1,i);default:throw new Es("unsupported track type: ".concat(e.kind))}}(i,r,t);return h.kind===Bs.Kind.Video?h.source=Bs.Source.Camera:h.kind===Bs.Kind.Audio&&(h.source=Bs.Source.Microphone),h.mediaStream=e,Do(h)&&n?yield h.setProcessor(n):Lo(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(n){if(!i)throw n;return Ma(Object.assign(Object.assign({},e),{audio:r,video:a}),t)}}))}var Oa;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(Oa||(Oa={}));class Aa extends tn.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===dt.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===ct.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,o){let r=arguments.length>6&&void 0!==arguments[6]?arguments[6]:dt.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Oa.Unknown,this.log=Gi,this.log=zi(null!==(a=null==o?void 0:o.loggerName)&&void 0!==a?a:Ki.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=r,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Eo,this.once(vs.Active,(()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0}))),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(Bs.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Bs.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Bs.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===ct.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==ct.ACTIVE&&this.emit(vs.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(vs.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(vs.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const o of n)e[o]!==t[o]&&(s[o]=null!==(i=t[o])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(vs.AttributesChanged,t)}setPermissions(e){var t,i,n,s,o,r;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(r=this.permissions)||void 0===r?void 0:r.canSubscribeMetrics);return this.permissions=e,c&&this.emit(vs.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(vs.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case Xe.EXCELLENT:return Oa.Excellent;case Xe.GOOD:return Oa.Good;case Xe.POOR:return Oa.Poor;case Xe.LOST:return Oa.Lost;default:return Oa.Unknown}}(e),t!==this._connectionQuality&&this.emit(vs.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>Do(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on(ks.Muted,(()=>{this.emit(vs.TrackMuted,e)})),e.on(ks.Unmuted,(()=>{this.emit(vs.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Bs.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Bs.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class Da extends Aa{constructor(e,t,i,n,s){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=ut.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Eo)},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.handleClosing=()=>{var e,t,i,n,s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),null===(o=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===o||o.call(s,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Eo),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Ni.OK&&s.reject(new Os(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=Ur.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ci({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Jo(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Jo(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Jo(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Jo(t))),this.emit(vs.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>$i(this,void 0,void 0,(function*(){var t,i,n,s,o;if(!(null===(o=this.roomOptions)||void 0===o?void 0:o.dynacast))return;const r=this.videoTrackPublications.get(e.trackSid);if(!r)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!r.videoTrack)return;const a=yield r.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Xi(a);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;zs(e)&&(this.log.debug("publish ".concat(e," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Jo(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,e,r.options))}}catch(e){i={error:e}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>$i(this,void 0,void 0,(function*(){if(e.source===Bs.Source.ScreenShare||e.source===Bs.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Jo(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(_o(e)||xo(e))try{if(co())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Bs.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),Jo(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Jo(e))),_o(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Jo(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==ut.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(bs.RemoteMute,((e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())})),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(bs.Connected,this.handleReconnected).on(bs.SignalConnected,this.handleSignalConnected).on(bs.SignalRestarted,this.handleReconnected).on(bs.SignalResumed,this.handleReconnected).on(bs.Restarting,this.handleReconnecting).on(bs.Resuming,this.handleReconnecting).on(bs.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(bs.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(bs.Closing,this.handleClosing).on(bs.SignalRequestResponse,this.handleSignalRequestResponse).on(bs.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return $i(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return $i(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return $i(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return $i(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,o)=>$i(t,void 0,void 0,(function*(){var t,r;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(r=null!=n?n:this.name)&&void 0!==r?r:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{o(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield Zs(50)}o(new Os("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&o(e)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(Bs.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Bs.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Bs.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(vs.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return $i(this,void 0,void 0,(function*(){this.encryptionType=e?ut.GCM:ut.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(e,t,i,n){return $i(this,void 0,void 0,(function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t)if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case Bs.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case Bs.Source.Microphone:t=yield this.createTracks({audio:null===(o=i)||void 0===o||o});break;case Bs.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Es(e)}}catch(i){throw null==t||t.forEach((e=>{e.stop()})),i instanceof Error&&this.emit(vs.MediaDevicesError,i,Go(e)),this.pendingPublishing.delete(e),i}for(const n of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===Bs.Source.Microphone&&Do(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{const e=[];for(const i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Jo(i))),e.push(this.publishTrack(i,n));const i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach((e=>{e.stop()})),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e)&&(r=yield this.waitForPendingPublicationOfSource(e),r||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),r&&r.track)if(e===Bs.Source.ScreenShare){r=yield this.unpublishTrack(r.track);const e=this.getTrackPublication(Bs.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r}))}enableCameraAndMicrophone(){return $i(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Bs.Source.Camera)&&!this.pendingPublishing.has(Bs.Source.Microphone)){this.pendingPublishing.add(Bs.Source.Camera),this.pendingPublishing.add(Bs.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(Bs.Source.Camera),this.pendingPublishing.delete(Bs.Source.Microphone)}}}))}createTracks(e){return $i(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=Fo(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const e=yield Ma(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return e.map((e=>(Do(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=Bs.Source.Microphone,this.emit(vs.AudioStreamAcquired)),Lo(e)&&(this.cameraError=void 0,e.source=Bs.Source.Camera),e)))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}}))}createScreenTracks(e){return $i(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new ws("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=Ls();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&go(e.osVersion,"17")>=0}()||(e.resolution=Ys.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=oo()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new Es("no video track found");const s=new sa(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=Bs.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(vs.AudioStreamAcquired);const e=new zr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=Bs.Source.ScreenShareAudio,o.push(e)}return o}))}publishTrack(e,t){return $i(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return $i(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,o,r,a;let c,d;if(_o(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),Ao(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case Bs.Source.Microphone:t="audioinput";break;case Bs.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new zr(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new sa(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Es("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach((t=>{t.track&&t.track===e&&(d=t)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),Jo(d))),d;const l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(o=null==t?void 0:t.forceStereo)&&void 0!==o?o:l;u&&(t||(t={}),void 0===t.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),Jo(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=t.dtx)&&void 0!==r||(t.dtx=!1),null!==(a=t.red)&&void 0!==a||(t.red=!1));const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){const e=Ls(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&go(t,e.osVersion)>=0)||"Safari"===e.name&&go(t,e.version)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);const p=new Promise(((t,n)=>$i(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==sr.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Jo(e)}));const i=setTimeout((()=>{n(new Ms("publishing rejected as engine not connected within timeout",408))}),15e3);yield this.waitUntilEngineConnected(),clearTimeout(i);const s=yield this.publish(e,h,u);t(s)}else try{const i=yield this.publish(e,h,u);t(i)}catch(e){n(e)}}catch(e){n(e)}}))));i.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Eo),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Jo(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map((e=>function(e){switch(e){case $e.CAMERA:return Bs.Source.Camera;case $e.MICROPHONE:return Bs.Source.Microphone;case $e.SCREEN_SHARE:return Bs.Source.ScreenShare;case $e.SCREEN_SHARE_AUDIO:return Bs.Source.ScreenShareAudio;default:return Bs.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Jo(e))),!1)}publish(e,t,i){return $i(this,void 0,void 0,(function*(){var n,s,o,r,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new Ms("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>Ao(e)&&t.source===e.source))&&e.source!==Bs.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Jo(e))),t.stopMicTrackOnMute&&Do(e)&&(e.stopOnMute=!0),e.source===Bs.Source.ScreenShare&&so()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(oo())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(so())return!1;if(oo()){const e=Ls();if((null==e?void 0:e.version)&&go(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&go(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=Mr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===zo(e.mime)))||(t.videoCodec=zo(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(ks.Muted,this.onTrackMuted),e.on(ks.Unmuted,this.onTrackUnmuted),e.on(ks.Ended,this.handleTrackEnded),e.on(ks.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ks.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ks.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(n=t.dtx)||void 0===n||n),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(nt.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(nt.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(nt.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(nt.TF_STEREO),g&&m.push(nt.TF_NO_DTX),_o(e)&&e.hasPreConnectBuffer&&m.push(nt.TF_PRECONNECT_BUFFER);const v=new Qt({cid:e.mediaStreamTrack.id,name:t.name,type:Bs.kindToProto(e.kind),muted:e.isMuted,source:Bs.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m});let b;if(e.kind===Bs.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(t){const n=null!==(r=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==r?r:Qs.h720.resolution;i={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{dims:i}))}v.width=i.width,v.height=i.height,xo(e)&&(io(p)&&(e.source===Bs.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Jo(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),v.simulcastCodecs=[new Jt({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:Mr}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===ut.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new Jt({codec:t.backupCodec.codec,cid:""})))),b=Zr(e.source===Bs.Source.ScreenShare,v.width,v.height,t),v.layers=aa(v.width,v.height,b,io(t.videoCodec))}else e.kind===Bs.Kind.Audio&&(b=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Rs("cannot publish track when not connected");const k=()=>$i(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new Rs("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(vs.LocalSenderCreated,e.sender,e),xo(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===Bs.Source.ScreenShare||e.constraints.height&&Po(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),b)if(so()&&e.kind===Bs.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=b[0])||void 0===n?void 0:n.maxBitrate)?b[0].maxBitrate/1e3:0})}else e.codec&&io(e.codec)&&(null===(s=b[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()}));let y;const T=new Promise(((t,i)=>$i(this,void 0,void 0,(function*(){var n;try{y=yield this.engine.addTrack(v),t(y)}catch(t){e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch((t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{error:t}))}))),i(t)}}))));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([T,k()]);y=e[0]}else{let i;if(y=yield T,y.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===Bs.Kind.Video){const n=zo(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{codec:n})),t.videoCodec=n,b=Zr(e.source===Bs.Source.ScreenShare,v.width,v.height,t))}yield k()}const C=new Ia(e.kind,y,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(ks.CpuConstrained,(e=>this.onTrackCpuConstrained(e,C))),C.options=t,e.sid=y.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:y})),xo(e)?e.startMonitor(this.engine.client):_o(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit(vs.LocalTrackPublished,C),_o(e)&&y.audioFeatures.includes(nt.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();if(this.on(vs.LocalTrackSubscribed,(t=>{if(t.trackSid===y.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),Jo(e))),e.stopPreConnectBuffer()}})),t){const n=new Promise(((n,s)=>$i(this,void 0,void 0,(function*(){var o,r,a,c,d,l;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Jo(e)));const m=setTimeout((()=>{s(new Error("agent not active within 10 seconds"))}),1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Jo(e)));const v=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:C.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=Xi(t);!(o=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){r={error:e}}finally{try{h||o||!(a=p.return)||(yield a.call(p))}finally{if(r)throw r.error}}yield v.close(),n()}catch(e){s(e)}}))));n.then((()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Jo(e)))})).catch((t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{error:t}))}))}}return C}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return $i(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==ut.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new Es("track is not published");if(!xo(e))throw new Es("track is not a video track");const o=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),r=function(e,t,i){var n,s,o,r;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Gi.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(o=a.height)&&void 0!==o?o:null===(r=e.dimensions)||void 0===r?void 0:r.height;return e.source===Bs.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),Zr(e.source===Bs.Source.ScreenShare,c,d,i)}(e,t,o);if(!r)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Jo(e)));const a=e.addSimulcastTrack(t,r);if(!a)return;const c=new Qt({cid:a.mediaStreamTrack.id,type:Bs.kindToProto(e.kind),muted:e.isMuted,source:Bs.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=aa(c.width,c.height,r),!this.engine||this.engine.isClosed)throw new Rs("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>$i(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,o,r),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:r,trackInfo:d}))}))}unpublishTrack(e,t){return $i(this,void 0,void 0,(function*(){var i,n;if(Ao(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Jo(e))),yield t)}const s=this.getPublicationForTrack(e),o=s?Jo(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));(e=s.track).off(ks.Muted,this.onTrackMuted),e.off(ks.Unmuted,this.onTrackUnmuted),e.off(ks.Ended,this.handleTrackEnded),e.off(ks.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ks.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ks.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let r=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<_r.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",r=!0);if(this.engine.removeTrack(a)&&(r=!0),xo(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(r=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:e}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case Bs.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case Bs.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(vs.LocalTrackUnpublished,s),s.setTrack(void 0),r&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return $i(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise(((n,s)=>$i(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))})),yield Promise.all(t.map((e=>$i(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===Bs.Source.ScreenShare||t.source===Bs.Source.ScreenShareAudio||!_o(t)&&!xo(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),n()}catch(e){s(e)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?ft.RELIABLE:ft.LOSSY,s=i.destinationIdentities,o=i.topic,r=new gt({kind:n,value:{case:"user",value:new kt({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:o})}});yield t.engine.sendDataPacket(r,n)}()}))}publishDtmf(e,t){return $i(this,void 0,void 0,(function*(){const i=new gt({kind:ft.RELIABLE,value:{case:"sipDtmf",value:new yt({code:e,digit:t})}});yield this.engine.sendDataPacket(i,ft.RELIABLE)}))}sendChatMessage(e,t){return $i(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new gt({value:{case:"chatMessage",value:new St(Object.assign(Object.assign({},i),{timestamp:D.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,ft.RELIABLE),this.emit(vs.ChatMessage,i),i}))}editChatMessage(e,t){return $i(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new gt({value:{case:"chatMessage",value:new St(Object.assign(Object.assign({},i),{timestamp:D.parse(i.timestamp),editTimestamp:D.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,ft.RELIABLE),this.emit(vs.ChatMessage,i),i}))}sendText(e,t){return $i(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,o=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),r=new Array(o?o.length+1:1).fill(0),a=(e,i)=>{var n;r[i]=e;const s=r.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:o,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&o&&(yield Promise.all(t.attachments.map(((e,i)=>$i(this,void 0,void 0,(function*(){return this._sendFile(o[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))))),c.info}))}streamText(e){return $i(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},o=new Bt({streamId:n,mimeType:s.mimeType,topic:s.topic,timestamp:Oo(s.timestamp),totalLength:Oo(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new jt({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?Ut.UPDATE:Ut.CREATE})}}),r=null==e?void 0:e.destinationIdentities,a=new gt({destinationIdentities:r,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(a,ft.RELIABLE);let c=0;const d=this,l=new WritableStream({write(e){return $i(this,void 0,void 0,(function*(){for(const t of function(e,t){const i=[];let n=(new TextEncoder).encode(e);for(;n.length>t;){let e=t;for(;e>0;){const t=n[e];if(void 0!==t&&128!=(192&t))break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,15e3)){yield d.engine.waitForBufferStatusLow(ft.RELIABLE);const e=new Vt({content:t,streamId:n,chunkIndex:Oo(c)}),i=new gt({destinationIdentities:r,value:{case:"streamChunk",value:e}});yield d.engine.sendDataPacket(i,ft.RELIABLE),c+=1}}))},close(){return $i(this,void 0,void 0,(function*(){const e=new qt({streamId:n}),t=new gt({destinationIdentities:r,value:{case:"streamTrailer",value:e}});yield d.engine.sendDataPacket(t,ft.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let u=()=>$i(this,void 0,void 0,(function*(){yield h.close()}));d.engine.once(bs.Closing,u);const h=new ka(l,s,(()=>this.engine.off(bs.Closing,u)));return h}))}sendFile(e,t){return $i(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return $i(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:e,value:t}=yield o.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return $i(this,void 0,void 0,(function*(){var t,i,n,s,o;const r=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,c={id:r,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown"},d=new Bt({totalLength:Oo(null!==(o=c.size)&&void 0!==o?o:0),mimeType:c.mimeType,streamId:r,topic:c.topic,timestamp:Oo(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Ft({name:c.name})}}),u=new gt({destinationIdentities:a,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,ft.RELIABLE);let h=0;const p=new l,m=this.engine,g=this.log,f=new WritableStream({write(e){return $i(this,void 0,void 0,(function*(){const t=yield p.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3);yield m.waitForBufferStatusLow(ft.RELIABLE);const n=new gt({destinationIdentities:a,value:{case:"streamChunk",value:new Vt({content:t,streamId:r,chunkIndex:Oo(h)})}});yield m.sendDataPacket(n,ft.RELIABLE),h+=1,i+=t.byteLength}}finally{t()}}))},close(){return $i(this,void 0,void 0,(function*(){const e=new qt({streamId:r}),t=new gt({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,ft.RELIABLE)}))},abort(e){g.error("Sink error:",e)}});return new ya(f,c)}))}performRpc(e){return $i(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:o=1e4}=e;return function*(){return new Promise(((e,r)=>$i(t,void 0,void 0,(function*(){var t,a,c,d;if(jr(s)>15360)return void r(Ur.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&go(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void r(Ur.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(i,l,n,s,o-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),r(Ur.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:i});const h=setTimeout((()=>{this.pendingResponses.delete(l),r(Ur.builtIn("RESPONSE_TIMEOUT"))}),o);this.pendingResponses.set(l,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?r(i):e(null!=t?t:"")},participantIdentity:i})}))))}()}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return $i(this,void 0,void 0,(function*(){const o=new gt({destinationIdentities:[e],kind:ft.RELIABLE,value:{case:"rpcRequest",value:new wt({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,ft.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,Ur.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}setActiveAgent(e){var t,i,n,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(s=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Eo),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(_o(n)||xo(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return $i(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[i]=t;return i.source===e}));if(t)return t[1];yield Zs(20)}}))}}class La extends Ra{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(ks.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new si({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new It({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ks.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Ra.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ra.SubscriptionStatus.Subscribed:Ra.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ra.PermissionStatus.Allowed:Ra.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.requestedDisabled!==!e&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)===e.height||(jo(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&jo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:Fs.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(ks.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(ks.VisibilityChanged,this.handleVisibilityChange),n.off(ks.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(ks.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ks.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ks.VisibilityChanged,this.handleVisibilityChange),e.on(ks.Ended,this.handleEnded),this.emit(ks.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(ks.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?ks.Muted:ks.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(ks.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ks.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return jo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new oi({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Bs.Kind.Video){let s=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(s){$o(this.videoDimensionsAdaptiveStream,s)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(t=this.trackInfo,i=this.requestedMaxQuality,null===(n=t.layers)||void 0===n?void 0:n.find((e=>e.quality===i)));e&&$o(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream;s?(e.width=Math.ceil(s.width),e.height=Math.ceil(s.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Fs.HIGH})),e.quality=Fs.HIGH)}var t,i,n;this.emit(ks.UpdateSettings,e)}}class xa extends Aa{static fromParticipantInfo(e,t,i){return new xa(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,o,r){super(t,i||"",n,s,o,r,arguments.length>7&&void 0!==arguments[7]?arguments[7]:dt.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(ks.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)})),e.on(ks.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(ks.SubscriptionPermissionChanged,(t=>{this.emit(vs.TrackSubscriptionPermissionChanged,e,t)})),e.on(ks.SubscriptionStatusChanged,(t=>{this.emit(vs.TrackSubscriptionStatusChanged,e,t)})),e.on(ks.Subscribed,(t=>{this.emit(vs.TrackSubscribed,t,e)})),e.on(ks.Unsubscribed,(t=>{this.emit(vs.TrackUnsubscribed,t,e)})),e.on(ks.SubscriptionFailed,(t=>{this.emit(vs.TrackSubscriptionFailed,e.trackSid,t)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Bs.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Bs.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,o){let r=this.getTrackPublicationBySid(t);if(r||t.startsWith("TR")||this.trackPublications.forEach((t=>{r||e.kind!==t.kind.toString()||(r=t)})),!r)return 0===o?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(vs.TrackSubscriptionFailed,t)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,o-1)}),150));if("ended"===e.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Jo(r))),void this.emit(vs.TrackSubscriptionFailed,t);let a;return a="video"===e.kind?new Sa(e,t,n,s):new Ca(e,t,n,this.audioContext,this.audioOutput),a.source=r.source,a.isMuted=r.isMuted,a.setMediaStream(i),a.start(),r.setTrack(a),this.volumeMap.has(r.source)&&No(a)&&Do(a)&&a.setVolume(this.volumeMap.get(r.source)),r}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach((e=>{var n,s;let o=this.getTrackPublicationBySid(e.sid);if(o)o.updateInfo(e);else{const t=Bs.kindFromProto(e.type);if(!t)return;o=new La(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),o.updateInfo(e),i.set(e.sid,o);const r=Array.from(this.trackPublications.values()).find((e=>e.source===(null==o?void 0:o.source)));r&&o.source!==Bs.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Jo(r),newTrack:Jo(o)})),this.addTrackPublication(o)}t.set(e.sid,o)})),this.trackPublications.forEach((e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Jo(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(vs.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case Bs.Kind.Audio:this.audioTrackPublications.delete(e);break;case Bs.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(vs.TrackUnpublished,i)}setAudioOutput(e){return $i(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;Do(i.track)&&No(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var _a;!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(_a||(_a={}));class Na extends tn.EventEmitter{constructor(e){var t,i,n,s;if(super(),t=this,this.state=_a.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Gi,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(e,t,i)=>$i(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!eo()&&!to())throw lo()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const s=yield this.disconnectLock.lock();if(this.state===_a.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(_a.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),uo(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new ma(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const o=(n,r,a)=>$i(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{yield this.attemptConnection(null!=a?a:e,t,i,l),this.abortController=void 0,n()}catch(e){if(this.regionUrlProvider&&e instanceof Ss&&e.reason!==ps.Cancelled&&e.reason!==ps.NotAllowed){let t=null;try{t=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof Ss&&(401===e.status||e.reason===ps.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void r(e)}t&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(e.message,". Retrying with another region: ").concat(t),this.logContext),this.recreateEngine(),yield o(n,r,t)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Io(e)),r(e))}else{let t=et.UNKNOWN_REASON;e instanceof Ss&&(t=Io(e)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),r(e)}}})),r=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Eo(((e,t)=>{o(e,t,r)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,o)=>$i(this,void 0,void 0,(function*(){var r,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},o.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(r=d.room)||void 0===r?void 0:r.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Ps("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>$i(this,void 0,void 0,(function*(){var s,o;this.state===_a.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},xr),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(fs.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new Ss("could not establish signal connection",ps.ServerUnreachable);throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof Ss&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:e})),t}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Ss("Connection attempt aborted",ps.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}co()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),co()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(_a.Connected),this.emit(fs.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return $i(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s,o;const r=yield e.disconnectLock.lock();try{if(e.state===_a.Disconnected)return void e.log.debug("already disconnected",e.logContext);e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===_a.Connecting||e.state===_a.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new Ss("Client initiated disconnect",ps.Cancelled)),e.connectFuture=void 0),(null===(o=e.engine)||void 0===o?void 0:o.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,et.CLIENT_INITIATED),e.engine=void 0}finally{r()}}()}))},this.onPageLeave=()=>$i(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>$i(this,void 0,void 0,(function*(){const e=[],t=Ls();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=wo();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(fs.Disconnected,(()=>{null==i||i.remove(),i=null}))}e.push(i)}this.remoteParticipants.forEach((t=>{t.audioTrackPublications.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...e.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.startVideo=()=>$i(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(_a.Reconnecting)&&this.emit(fs.Reconnecting)},this.handleSignalRestarted=e=>$i(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(_a.Connected),this.emit(fs.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===ct.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emitWhenConnected(fs.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)})),e.forEach((e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(fs.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=Bs.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit(vs.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(fs.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(fs.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(vs.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(fs.SipDTMFReceived,t,e),null==e||e.emit(vs.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:o,endTime:r,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(r.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit(ks.TranscriptionReceived,s),null==i||i.emit(vs.TranscriptionReceived,s,n),this.emit(fs.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(fs.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(fs.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(fs.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(fs.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(fs.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(fs.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>$i(this,void 0,void 0,(function*(){var e;"iOS"!==(null===(e=Ls())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit(fs.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(fs.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(fs.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=e=>{this.emit(fs.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(fs.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(fs.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(fs.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(fs.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>$i(this,void 0,void 0,(function*(){var t,i,n,s,o,r;if(null===(t=e.track)||void 0===t||t.on(ks.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(ks.Restarted,this.onLocalTrackRestarted),null===(o=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===o||o.call(s,this),this.emit(fs.LocalTrackPublished,e,this.localParticipant),_o(e.track)){(yield e.track.checkForSilence())&&this.emit(fs.LocalAudioSilenceDetected,e)}const a=yield null===(r=e.track)||void 0===r?void 0:r.getDeviceId(!1),c=Go(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(fs.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(ks.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(ks.Restarted,this.onLocalTrackRestarted),this.emit(fs.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>$i(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=Go(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(fs.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit(fs.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(fs.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(fs.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(fs.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Lr),e),this.log=zi(null!==(i=this.options.loggerName)&&void 0!==i?i:Ki.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Ar),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Dr),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Or),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new l,this.localParticipant=new Da("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Po(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Po(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Po(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE(),co()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),Na.cleanupRegistry&&Na.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,i,n,s,o){return $i(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==o)return void(yield this.engine.publishRpcResponse(e,t,null,Ur.builtIn("UNSUPPORTED_VERSION")));const r=this.rpcHandlers.get(i);if(!r)return void(yield this.engine.publishRpcResponse(e,t,null,Ur.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const o=yield r({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});jr(o)>15360?(a=Ur.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=o}catch(e){e instanceof Ur?a=e:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),a=Ur.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)}))}setE2EEEnabled(e){return $i(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Yo(this.options.e2ee),this.e2eeManager.on(us.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(fs.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(us.EncryptionError,(e=>this.emit(fs.EncryptionError,e))),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return $i(this,void 0,void 0,(function*(){return this.state===_a.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(bs.RoomUpdate,i),e(t.sid))};this.engine.on(bs.RoomUpdate,i),this.once(fs.Disconnected,(()=>{this.engine.off(bs.RoomUpdate,i),t("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new ha(this.options),this.engine.on(bs.ParticipantUpdate,this.handleParticipantUpdates).on(bs.RoomUpdate,this.handleRoomUpdate).on(bs.SpeakersChanged,this.handleSpeakersChanged).on(bs.StreamStateChanged,this.handleStreamStateUpdate).on(bs.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(bs.SubscriptionError,this.handleSubscriptionError).on(bs.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(bs.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(bs.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(bs.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(bs.DataPacketReceived,this.handleDataPacket).on(bs.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(_a.SignalReconnecting)&&this.emit(fs.SignalReconnecting)})).on(bs.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(_a.Connected)&&this.emit(fs.Reconnected)})).on(bs.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===_a.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(bs.Restarting,this.handleRestarting).on(bs.SignalRestarted,this.handleSignalRestarted).on(bs.Offline,(()=>{this.setAndEmitConnectionState(_a.Reconnecting)&&this.emit(fs.Reconnecting)})).on(bs.DCBufferStatusChanged,((e,t)=>{this.emit(fs.DCBufferStatusChanged,e,t)})).on(bs.LocalTrackSubscribed,(e=>{const t=this.localParticipant.getTrackPublications().find((t=>{let{trackSid:i}=t;return i===e}));t?(this.localParticipant.emit(vs.LocalTrackSubscribed,t),this.emitWhenConnected(fs.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})).on(bs.RoomMoved,(e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach(((e,t)=>{this.handleParticipantDisconnected(t,e)})),this.emit(fs.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Zo.getInstance().getDevices(e,t)}prepareConnection(e,t){return $i(this,void 0,void 0,(function*(){if(this.state===_a.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(uo(new URL(e))&&t){this.regionUrlProvider=new ma(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===_a.Disconnected&&(this.regionUrl=i,yield fetch(Ro(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ro(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return $i(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Mi({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Mi({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Mi({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Mi({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>$i(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Mi({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>$i(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Mi({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new Mi({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>$i(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new ci({reason:et.CLIENT_INITIATED,action:di.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Mi({scenario:{case:"subscriberBandwidth",value:Oo(t)}});break;case"leave-full-reconnect":i=new Mi({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return $i(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,o,r,a,c,d,l;let u=!0,h=!1;const p=n?{exact:t}:t;if("audioinput"===e){h=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===Bs.Source.Microphone));try{u=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)})))).every((e=>!0===e))}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}const o=n.some((e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i}));u&&o&&(h=!0)}else if("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;const t=null!==(o=i.getActiveDevice(e))&&void 0!==o?o:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Bs.Source.Camera));try{u=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)})))).every((e=>!0===e))}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}const s=n.some((e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i}));u&&s&&(h=!0)}else if("audiooutput"===e){if(h=!0,!no()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!==(r=yield Zo.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==r?r:""),null!==(a=(l=i.options).audioOutput)&&void 0!==a||(l.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return h&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(fs.ActiveDeviceChanged,e,t)),u}()}))}setupLocalParticipantEvents(){this.localParticipant.on(vs.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(vs.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(vs.AttributesChanged,this.onLocalAttributesChanged).on(vs.TrackMuted,this.onLocalTrackMuted).on(vs.TrackUnmuted,this.onLocalTrackUnmuted).on(vs.LocalTrackPublished,this.onLocalTrackPublished).on(vs.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(vs.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(vs.MediaDevicesError,this.onMediaDevicesError).on(vs.AudioStreamAcquired,this.startAudio).on(vs.ChatMessage,this.onLocalChatMessageSent).on(vs.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===_a.Connecting||this.state===_a.Reconnecting){const n=()=>{this.onTrackAdded(e,t,i),s()},s=()=>{this.off(fs.Reconnected,n),this.off(fs.Connected,n),this.off(fs.Disconnected,s)};return this.once(fs.Reconnected,n),this.once(fs.Connected,n),void this.once(fs.Disconnected,s)}if(this.state===_a.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let o=n[1],r=e.id;if(o&&o.startsWith("TR")&&(r=o),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find((e=>e.sid===s));if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),a.addSubscribedMediaTrack(e,r,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==_a.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(vs.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(vs.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(vs.AttributesChanged,this.onLocalAttributesChanged).off(vs.TrackMuted,this.onLocalTrackMuted).off(vs.TrackUnmuted,this.onLocalTrackUnmuted).off(vs.LocalTrackPublished,this.onLocalTrackPublished).off(vs.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(vs.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(vs.MediaDevicesError,this.onMediaDevicesError).off(vs.AudioStreamAcquired,this.startAudio).off(vs.ChatMessage,this.onLocalChatMessageSent).off(vs.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),co()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(_a.Disconnected),this.emit(fs.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(fs.ParticipantDisconnected,t),t.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return $i(this,void 0,void 0,(function*(){var i;if("byteHeader"===e.contentHeader.case){const n=this.byteStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const o={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Mo(e.timestamp),attributes:e.attributes},r=new ReadableStream({start:t=>{s=t,this.byteStreamControllers.set(e.streamId,{info:o,controller:s,startTime:Date.now()})}});n(new fa(o,r,Mo(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let n;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:t=>{n=t,this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});i(new va(s,o,Mo(e.totalLength)),{identity:t})}}))}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}selectDefaultDevices(){return $i(this,void 0,void 0,(function*(){var e,t,i;const n=Zo.getInstance().previousDevices,s=yield Zo.getInstance().getDevices(void 0,!1),o=Ls();if("Chrome"===(null==o?void 0:o.name)&&"iOS"!==o.os)for(let e of s){const t=n.find((t=>t.deviceId===e.deviceId));t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(fs.ActiveDeviceChanged,e.kind,e.deviceId)}const r=["audiooutput","audioinput","videoinput"];for(let o of r){const r=Ho(o),a=this.localParticipant.getTrackPublication(r);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter((e=>e.kind===o)),d=this.getActiveDevice(o);d===(null===(t=n.filter((e=>e.kind===o))[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(o,c[0].deviceId):"audioinput"===o&&!ro()||"videoinput"===o||!(c.length>0)||c.find((e=>e.deviceId===this.getActiveDevice(o)))||"audiooutput"===o&&ro()||(yield this.switchActiveDevice(o,c[0].deviceId))}}))}acquireAudioContext(){return $i(this,void 0,void 0,(function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=Ko())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),Zs(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(fs.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?xa.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new xa(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);if(t){i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity)}return i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(fs.ParticipantConnected,i),i.on(vs.TrackPublished,(e=>{this.emitWhenConnected(fs.TrackPublished,e,i)})).on(vs.TrackSubscribed,((e,t)=>{e.kind===Bs.Kind.Audio?(e.on(ks.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(ks.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===Bs.Kind.Video&&(e.on(ks.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(ks.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(fs.TrackSubscribed,e,t,i)})).on(vs.TrackUnpublished,(e=>{this.emit(fs.TrackUnpublished,e,i)})).on(vs.TrackUnsubscribed,((e,t)=>{this.emit(fs.TrackUnsubscribed,e,t,i)})).on(vs.TrackMuted,(e=>{this.emitWhenConnected(fs.TrackMuted,e,i)})).on(vs.TrackUnmuted,(e=>{this.emitWhenConnected(fs.TrackUnmuted,e,i)})).on(vs.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(fs.ParticipantMetadataChanged,e,i)})).on(vs.ParticipantNameChanged,(e=>{this.emitWhenConnected(fs.ParticipantNameChanged,e,i)})).on(vs.AttributesChanged,(e=>{this.emitWhenConnected(fs.ParticipantAttributesChanged,e,i)})).on(vs.ConnectionQualityChanged,(e=>{this.emitWhenConnected(fs.ConnectionQualityChanged,e,i)})).on(vs.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(fs.ParticipantPermissionsChanged,e,i)})).on(vs.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(fs.TrackSubscriptionStatusChanged,e,t,i)})).on(vs.TrackSubscriptionFailed,((e,t)=>{this.emit(fs.TrackSubscriptionFailed,e,i,t)})).on(vs.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(fs.TrackSubscriptionPermissionChanged,e,t,i)})).on(vs.Active,(()=>{this.emitWhenConnected(fs.ParticipantActive,i),i.kind===dt.AGENT&&this.localParticipant.setActiveAgent(i)})),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Uo(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Us.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,et.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Us.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(fs.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,i]=e;this.emit(t,...i)})),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===_a.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===_a.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return $i(this,void 0,void 0,(function*(){var t,i;const n=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new st({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:D.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new at({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(fs.SignalConnected),this.emit(fs.Connected),this.setAndEmitConnectionState(_a.Connected),n.video){const e=new Ia(Bs.Kind.Video,new pt({source:$e.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Qe.AUDIO,name:"video-dummy"}),new sa(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Co(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(vs.LocalTrackPublished,e)}if(n.audio){const e=new Ia(Bs.Kind.Audio,new pt({source:$e.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Qe.AUDIO}),new zr(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:wo(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(vs.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new at({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:ct.ACTIVE,tracks:[],joinedAt:D.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const o=Co(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),r=new pt({source:$e.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Qe.AUDIO});n.addSubscribedMediaTrack(o,r.sid,new MediaStream([o]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}if(s.audio){const e=wo(),i=new pt({source:$e.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Qe.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==fs.ActiveSpeakersChanged&&e!==fs.TranscriptionReceived){const t=Ua(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function Ua(e){return e.map((e=>{if(e)return Array.isArray(e)?Ua(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}var ja;Na.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()})),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"}(ja||(ja={}));tn.EventEmitter;tn.EventEmitter;const Fa=(e,t)=>"error"===e||t,Ba=(e,t)=>{const i=(new Date).toISOString(),n=t?.source?`[${t.source}]`:"";return`${i} ${t?.level?`[${t.level.toUpperCase()}]`:""} ${n}`},Va=e=>({log:(t,i)=>{if(!Fa(i?.level||"debug",e))return;const n=Ba(0,{...i,level:"debug"});console.log(n,t,i?.error||"")},info:(t,i)=>{if(!Fa(i?.level||"info",e))return;const n=Ba(0,{...i,level:"info"});console.info(n,t,i?.error||"")},warn:(t,i)=>{if(!Fa(i?.level||"warn",e))return;const n=Ba(0,{...i,level:"warn"});console.warn(n,t,i?.error||"")},error:(t,i)=>{if(!Fa(i?.level||"error",e))return;const n=Ba(0,{...i,level:"error"});console.error(n,t,i?.error||"")}});var qa,Ka,Ha,Ga,za,Wa,Ja,Qa,$a,Ya,Xa,Za,ec,tc,ic,nc,sc,oc,rc,ac,cc,dc;const lc=.02,uc=.001;class hc extends s.EventEmitter{constructor(){super(),qa.add(this),this.analyticsInterval=null,this.lastAgentSpeakStart=null,this.lastUserSpeakStart=null,this.callStartTime=null,this.room=null,this.isConnected=!1,this.lastUserAudioLevel=0,this.lastAgentAudioLevel=0,this.userDropoutStartTime=null,this.agentDropoutStartTime=null,this.vadUserSpeakStart=null,this.vadAgentSpeakStart=null,this.lastUserInputTime=null,this.previousConnectionQuality="unknown",t(this,qa,"m",Ka).call(this)}setRoom(e){this.room=e}setConnectionState(e,t=null){this.isConnected=e,t&&(this.callStartTime=t)}updateConnectionStats(e,t){this.callStats.connectionAttempts=e,this.callStats.reconnectionAttempts=t,this.performanceMetrics.reconnectionCount=t}updateCounts(e,t){this.callStats.participantCount=e,this.callStats.trackCount=t}setConnectionEstablishedTime(e){this.performanceMetrics.connectionEstablishedTime=e}startAnalyticsCollection(){this.analyticsInterval&&this.stopAnalyticsCollection(),this.analyticsInterval=setInterval((()=>{t(this,qa,"m",Ha).call(this)}),5e3)}stopAnalyticsCollection(){this.analyticsInterval&&(clearInterval(this.analyticsInterval),this.analyticsInterval=null)}handleConnectionQualityChanged(e,i){const n=t(this,qa,"m",Ga).call(this,e);this.connectionMetrics.quality=n,this.callStats.connectionQuality=n,t(this,qa,"m",za).call(this),t(this,qa,"m",cc).call(this,n);const s={quality:e,participant:i.identity||"unknown",metrics:{quality:n}};this.emit("connectionQualityChanged",s)}handleAudioPlaybackChanged(e){this.emit("audioPlaybackChanged",e),t(this,qa,"m",Qa).call(this)}getConnectionStats(){return{quality:this.connectionMetrics.quality,connectionAttempts:this.callStats.connectionAttempts,reconnectionAttempts:this.callStats.reconnectionAttempts,connectionEstablishedTime:this.performanceMetrics.connectionEstablishedTime,isConnected:this.isConnected}}getAudioLevels(){return{userAudioLevel:this.audioMetrics.userAudioLevel,agentAudioLevel:this.audioMetrics.agentAudioLevel,userSpeakingTime:this.audioMetrics.userSpeakingTime,agentSpeakingTime:this.audioMetrics.agentSpeakingTime,audioDropouts:this.audioMetrics.audioDropouts,echoCancellationActive:this.audioMetrics.echoCancellationActive,currentUserLevel:this.audioMetrics.userAudioLevel,currentAgentLevel:this.audioMetrics.agentAudioLevel}}getPerformanceMetrics(){const e=this.callStartTime?Date.now()-this.callStartTime:0;return{responseTime:this.performanceMetrics.responseTime,connectionEstablishedTime:this.performanceMetrics.connectionEstablishedTime,reconnectionCount:this.performanceMetrics.reconnectionCount,callDuration:e,averageResponseTime:this.performanceMetrics.responseTime}}recordResponseTime(e){this.performanceMetrics.responseTime=e,this.emit("responseTimeRecorded",{responseTime:e,timestamp:Date.now()})}getVADSettings(){return{audioThreshold:lc,minSpeakingDuration:100,dropoutThreshold:uc,dropoutDetectionDuration:500}}getCallAnalytics(e,t,i,n){const s=this.getPerformanceMetrics(),o=this.getAudioLevels();return{connectionStats:this.getConnectionStats(),audioMetrics:{...o,isPaused:n,volume:i},performanceMetrics:s,participants:e,trackStats:t,callStats:this.callStats,metadata:{callStartTime:this.callStartTime,isConnected:this.isConnected,isPaused:n,volume:i},callDuration:s.callDuration}}getInternalConnectionStats(){return{latency:this.connectionMetrics.latency,packetLoss:this.connectionMetrics.packetLoss,bandwidth:this.connectionMetrics.bandwidth,quality:this.connectionMetrics.quality,jitter:this.connectionMetrics.jitter,connectionAttempts:this.callStats.connectionAttempts,reconnectionAttempts:this.callStats.reconnectionAttempts,connectionEstablishedTime:this.performanceMetrics.connectionEstablishedTime,isConnected:this.isConnected}}getInternalPerformanceMetrics(){const e=this.callStartTime?Date.now()-this.callStartTime:0;return{responseTime:this.performanceMetrics.responseTime,networkLatency:this.performanceMetrics.networkLatency||this.connectionMetrics.latency,connectionEstablishedTime:this.performanceMetrics.connectionEstablishedTime,reconnectionCount:this.performanceMetrics.reconnectionCount,callDuration:e,averageResponseTime:this.performanceMetrics.responseTime}}cleanup(){this.stopAnalyticsCollection(),t(this,qa,"m",Ka).call(this),this.lastAgentSpeakStart=null,this.lastUserSpeakStart=null,this.vadUserSpeakStart=null,this.vadAgentSpeakStart=null,this.userDropoutStartTime=null,this.agentDropoutStartTime=null,this.lastUserInputTime=null,this.lastUserAudioLevel=0,this.lastAgentAudioLevel=0,this.previousConnectionQuality="unknown"}}var pc,mc,gc,fc,vc,bc,kc,yc,Tc,Cc,Sc,wc,Ec,Pc,Rc,Ic,Mc,Oc,Ac,Dc;qa=new WeakSet,Ka=function(){this.callStats={connectionAttempts:0,reconnectionAttempts:0,totalBytesReceived:0,totalBytesSent:0,packetsLost:0,participantCount:0,trackCount:0,audioLevels:[],connectionQuality:"unknown"},this.connectionMetrics={latency:0,packetLoss:0,bandwidth:0,quality:"unknown",jitter:0},this.audioMetrics={userAudioLevel:0,agentAudioLevel:0,userSpeakingTime:0,agentSpeakingTime:0,audioDropouts:0,echoCancellationActive:!1},this.performanceMetrics={responseTime:0,networkLatency:0,connectionEstablishedTime:0,reconnectionCount:0}},Ha=function(){if(this.room&&this.isConnected)try{if(t(this,qa,"m",za).call(this),this.room?.localParticipant){const e=this.room.localParticipant.connectionQuality;if(e){const i=t(this,qa,"m",Ga).call(this,e);this.connectionMetrics.quality=i,this.callStats.connectionQuality=i}}t(this,qa,"m",Qa).call(this),t(this,qa,"m",Xa).call(this),t(this,qa,"m",dc).call(this);const e=this.getPerformanceMetrics();this.emit("analyticsUpdated",{connectionStats:this.getConnectionStats(),audioMetrics:this.getAudioLevels(),performanceMetrics:e,callDuration:e.callDuration})}catch(e){}},Ga=function(e){switch(e){case Oa.Excellent:return"excellent";case Oa.Good:return"good";case Oa.Poor:return"poor";default:return"lost"}},za=function(){t(this,qa,"m",Wa).call(this)},Wa=function(){const e=this.room?.localParticipant?.connectionQuality;if(!e)return;const i=t(this,qa,"m",Ja).call(this,e);0===this.connectionMetrics.latency&&(this.connectionMetrics.latency=i.latency,this.connectionMetrics.packetLoss=i.packetLoss,this.connectionMetrics.bandwidth=i.bandwidth)},Ja=function(e){switch(e){case Oa.Excellent:return{latency:10,packetLoss:0,bandwidth:1e6};case Oa.Good:return{latency:50,packetLoss:.1,bandwidth:5e5};case Oa.Poor:return{latency:200,packetLoss:1,bandwidth:1e5};default:return{latency:1e3,packetLoss:10,bandwidth:0}}},Qa=function(){if(!this.room)return;const e=Date.now(),i=this.room.activeSpeakers;let n=0,s=0;for(const o of i)o===this.room.localParticipant?n=t(this,qa,"m",$a).call(this,o,e):s=Math.max(s,t(this,qa,"m",Ya).call(this,o,e));this.audioMetrics.userAudioLevel=n,this.audioMetrics.agentAudioLevel=s},$a=function(e,i){const n=e.audioLevel||0,s=e.isSpeaking;return s&&!this.lastUserSpeakStart?(this.lastUserSpeakStart=i,this.lastUserInputTime=i):!s&&this.lastUserSpeakStart&&(this.audioMetrics.userSpeakingTime+=i-this.lastUserSpeakStart,this.lastUserSpeakStart=null),t(this,qa,"m",ec).call(this,"user",n,i),t(this,qa,"m",sc).call(this,"user",n,i),n},Ya=function(e,i){const n=e.audioLevel||0,s=e.isSpeaking;if(s&&!this.lastAgentSpeakStart){if(this.lastAgentSpeakStart=i,this.lastUserInputTime){const e=i-this.lastUserInputTime;this.performanceMetrics.responseTime=e,this.lastUserInputTime=null}}else!s&&this.lastAgentSpeakStart&&(this.audioMetrics.agentSpeakingTime+=i-this.lastAgentSpeakStart,this.lastAgentSpeakStart=null);return t(this,qa,"m",ec).call(this,"agent",n,i),t(this,qa,"m",sc).call(this,"agent",n,i),n},Xa=function(){this.room&&(this.callStats.participantCount=1+this.room.remoteParticipants.size,this.callStats.trackCount=t(this,qa,"m",Za).call(this))},Za=function(){let e=0;e+=this.room?.localParticipant.trackPublications.size||0;for(const t of this.room?.remoteParticipants.values()||[])e+=t.trackPublications.size;return e},ec=function(e,i,n){"user"===e?t(this,qa,"m",tc).call(this,i,n):t(this,qa,"m",ic).call(this,i,n)},tc=function(e,i){const n=e>lc;n&&!this.vadUserSpeakStart?this.vadUserSpeakStart=i:!n&&this.vadUserSpeakStart&&t(this,qa,"m",nc).call(this,"user",e,i)},ic=function(e,i){const n=e>lc;n&&!this.vadAgentSpeakStart?this.vadAgentSpeakStart=i:!n&&this.vadAgentSpeakStart&&t(this,qa,"m",nc).call(this,"agent",e,i)},nc=function(e,t,i){const n="user"===e?this.vadUserSpeakStart:this.vadAgentSpeakStart;if(!n)return;const s=i-n;s>=100&&this.emit("voiceActivityDetected",{participant:e,duration:s,audioLevel:t,timestamp:i}),"user"===e?this.vadUserSpeakStart=null:this.vadAgentSpeakStart=null},sc=function(e,i,n){"user"===e?t(this,qa,"m",oc).call(this,i,n):t(this,qa,"m",rc).call(this,i,n)},oc=function(e,i){this.lastUserAudioLevel>lc&&e<uc?this.userDropoutStartTime||(this.userDropoutStartTime=i):e>=uc&&this.userDropoutStartTime&&t(this,qa,"m",ac).call(this,"user",i),this.lastUserAudioLevel=e},rc=function(e,i){this.lastAgentAudioLevel>lc&&e<uc?this.agentDropoutStartTime||(this.agentDropoutStartTime=i):e>=uc&&this.agentDropoutStartTime&&t(this,qa,"m",ac).call(this,"agent",i),this.lastAgentAudioLevel=e},ac=function(e,t){const i="user"===e?this.userDropoutStartTime:this.agentDropoutStartTime;if(!i)return;const n=t-i;n>=500&&(this.audioMetrics.audioDropouts++,this.emit("audioDropoutDetected",{participant:e,duration:n,timestamp:t})),"user"===e?this.userDropoutStartTime=null:this.agentDropoutStartTime=null},cc=function(e){if(this.previousConnectionQuality!==e){let t=0;switch(e){case"excellent":t=5;break;case"good":t=15;break;case"poor":t=50;break;case"lost":t=200;break;default:t=30}this.connectionMetrics.jitter=t,this.previousConnectionQuality=e,this.emit("jitterChanged",{jitter:t,quality:e,previousQuality:this.previousConnectionQuality,timestamp:Date.now()})}},dc=function(){if(!this.room?.localParticipant?.audioTrackPublications)return;let e=!1;for(const t of this.room.localParticipant.audioTrackPublications.values())if(t.track){const i=t.track.getConstraints?.();if(!1!==i?.echoCancellation){e=!0;break}}this.audioMetrics.echoCancellationActive!==e&&(this.audioMetrics.echoCancellationActive=e,this.emit("echoCancellationChanged",{active:e,timestamp:Date.now()}))};class Lc extends s.EventEmitter{constructor(){super(...arguments),pc.add(this),this.audioElements=new Set,this.trackStats=new Map,this.volume=1,this.room=null,this.audioContext=null,this.inputAnalyser=null,this.outputAnalyser=null,this.audioCaptureEnabled=!1,this.audioCaptureOptions=null,this.recorders=new Map,this.processors=new Map,this.trackCaptureMap=new Map}setRoom(e){this.room=e}setVolume(e){try{const t=Number(e);Number.isFinite(t)?this.volume=Math.min(1,Math.max(0,t)):this.volume=0;for(const e of this.audioElements)e&&void 0!==e.volume&&(e.volume=this.volume);this.emit("volumeChanged",this.volume)}catch(e){this.emit("error",new Error(`Failed to set volume: ${e instanceof Error?e.message:String(e)}`))}}getOutputVolume(){return this.volume}getInputVolume(){try{if(this.inputAnalyser||t(this,pc,"m",Sc).call(this),!this.inputAnalyser)return 0;const e=this.inputAnalyser.frequencyBinCount,i=new Uint8Array(e);if(this.inputAnalyser.getByteFrequencyData(i),0===i.length)return 0;let n=0;for(const e of i)n+=e;const s=n/(255*i.length);return Math.max(0,Math.min(1,s))}catch{return 0}}setMicMuted(e){try{if(this.room?.localParticipant){const i=!e,n=this.room.localParticipant.setMicrophoneEnabled(i);return n&&"function"==typeof n.then?void n.then((()=>{t(this,pc,"m",mc).call(this,e?"micMuted":"micUnmuted",e)})).catch((i=>{t(this,pc,"m",gc).call(this,e,i)})):void t(this,pc,"m",mc).call(this,e?"micMuted":"micUnmuted",e)}t(this,pc,"m",mc).call(this,e?"micMuted":"micUnmuted",e)}catch(i){t(this,pc,"m",gc).call(this,e,i)}}isMicMuted(){try{let e;const t=this.room?.localParticipant?.getTrackPublication;if(t)try{e=t(Bs.Source.Microphone)}catch{e=t("microphone")}if(e&&"boolean"==typeof e.isMuted)return e.isMuted}catch{}return!1}getInputByteFrequencyData(){try{if(this.inputAnalyser||t(this,pc,"m",Sc).call(this),!this.inputAnalyser)return new Uint8Array(0);const e=this.inputAnalyser.frequencyBinCount,i=new Uint8Array(e);return this.inputAnalyser.getByteFrequencyData(i),i}catch{return new Uint8Array(0)}}getOutputByteFrequencyData(){try{if(this.outputAnalyser||t(this,pc,"m",wc).call(this),!this.outputAnalyser)return new Uint8Array(0);const e=this.outputAnalyser.frequencyBinCount,i=new Uint8Array(e);return this.outputAnalyser.getByteFrequencyData(i),i}catch{return new Uint8Array(0)}}handleTrackSubscribed(e,i,n){e.kind===Bs.Kind.Audio&&(t(this,pc,"m",fc).call(this,e,i,n),t(this,pc,"m",vc).call(this,e,i,n))}handleTrackUnsubscribed(e,t,i){if(e.kind===Bs.Kind.Audio){this.trackStats.delete(e.sid||e.mediaStreamTrack?.id||"unknown");for(const t of e.detach()){try{t?.parentNode?.removeChild&&t.parentNode.removeChild(t)}catch{}this.audioElements.delete(t)}const n={track:e,publication:t,participant:i.identity||"unknown"};this.emit("trackUnsubscribed",n)}}pauseAllAudio(){for(const e of this.audioElements)e.pause&&e.pause()}resumeAllAudio(){for(const e of this.audioElements)e.play&&e.play().catch((()=>{}))}getTrackStats(){return{totalTracks:this.trackStats.size,activeTracks:this.trackStats.size,audioElements:this.audioElements.size,trackDetails:Array.from(this.trackStats.entries())}}enableAudioCapture(e){const i=e.callback||e.onData;if(!i)throw new Error('Audio capture requires either "callback" or "onData" option');this.audioCaptureEnabled=!0,this.audioCaptureOptions={source:e.source||"agent",format:e.format||"opus-webm",chunkSize:e.chunkSize||100,bufferSize:e.bufferSize||4096,callback:i},t(this,pc,"m",Pc).call(this)}disableAudioCapture(){this.audioCaptureEnabled=!1,t(this,pc,"m",Ac).call(this),this.audioCaptureOptions=null}cleanup(){t(this,pc,"m",Ac).call(this);for(const e of this.audioElements)try{e?.parentNode?.removeChild&&e.parentNode.removeChild(e)}catch{}this.audioElements.clear(),this.trackStats.clear()}}var xc,_c,Nc,Uc,jc,Fc,Bc,Vc,qc,Kc,Hc,Gc,zc,Wc,Jc,Qc,$c,Yc,Xc,Zc,ed,td,id,nd,sd,od,rd,ad,cd,dd,ld,ud;pc=new WeakSet,mc=function(e,t){try{this.emit(e)}catch(e){this.listenerCount("error")>0&&this.emit("error",new Error(`Failed to ${t?"mute":"unmute"} microphone: ${e instanceof Error?e.message:String(e)}`))}},gc=function(e,t){this.listenerCount("error")>0&&this.emit("error",new Error(`Failed to ${e?"mute":"unmute"} microphone: ${t instanceof Error?t.message:String(t)}`))},fc=function(e,i,n){this.trackStats.set(e.sid||e.mediaStreamTrack?.id||"unknown",{trackId:e.sid||e.mediaStreamTrack?.id||"unknown",kind:e.kind,participant:n.identity||"unknown",subscriptionTime:Date.now(),publication:i,source:t(this,pc,"m",Ec).call(this,i.source),muted:i.isMuted,enabled:i.isEnabled,dimensions:i.dimensions,simulcasted:i.simulcasted})},vc=function(e,i,n){const s=e.attach();s&&(s.volume=this.volume,s.autoplay=!0,t(this,pc,"m",Tc).call(this,s),this.audioElements.add(s),t(this,pc,"m",bc).call(this,e,i,n),t(this,pc,"m",kc).call(this,s),t(this,pc,"m",yc).call(this,e,n))},bc=function(e,t,i){const n={track:e,publication:t,participant:i.identity||"unknown",trackStats:this.trackStats.get(e.sid||e.mediaStreamTrack?.id||"unknown")};this.emit("trackSubscribed",n)},kc=function(e){e.style.display="none";try{document.body.appendChild(e)}catch{}},yc=function(e,i){if(!this.audioCaptureEnabled||!this.audioCaptureOptions)return;const n=e.sid||e.mediaStreamTrack?.id||"unknown",s=(i.identity||"").toLowerCase().includes("agent")?"agent":"user",{source:o,format:r}=this.audioCaptureOptions;"both"!==o&&o!==s||!r||t(this,pc,"m",Rc).call(this,n,i.identity||"unknown",s,r)},Tc=function(e){let t=!1;e.addEventListener("play",(()=>{t||(t=!0,this.emit("speaking"))})),e.addEventListener("pause",(()=>{t=!1,this.emit("listening")})),e.addEventListener("ended",(()=>{t=!1,this.emit("listening")}))},Cc=function(){if(this.audioContext)return;const e=globalThis.AudioContext,t="function"==typeof e?e:null;if(t)try{this.audioContext=new t}catch{this.audioContext=null}},Sc=function(){try{if(t(this,pc,"m",Cc).call(this),!this.audioContext)return;let e=null;const i=this.room?.localParticipant?.getTrackPublication;if(i)try{e=i(Bs.Source.Microphone)}catch{e=i("microphone")}const n=e?.track?.mediaStreamTrack;if(!n)return;const s=new MediaStream([n]),o=this.audioContext.createMediaStreamSource(s),r=this.audioContext.createAnalyser();r.fftSize=256;{const e=o;e&&"function"==typeof e.connect&&e.connect(r)}this.inputAnalyser=r}catch{this.inputAnalyser=null}},wc=function(){try{if(t(this,pc,"m",Cc).call(this),!this.audioContext)return;const e=this.audioElements.values().next().value;if(!e)return;const i=this.audioContext.createMediaElementSource(e),n=this.audioContext.createAnalyser();n.fftSize=256;{const e=i;e&&"function"==typeof e.connect&&e.connect(n)}this.outputAnalyser=n}catch{this.outputAnalyser=null}},Ec=function(e){switch(e){case Bs.Source.Microphone:return"microphone";case Bs.Source.Camera:return"camera";case Bs.Source.ScreenShare:return"screen_share";case Bs.Source.ScreenShareAudio:return"screen_share_audio";default:return"unknown"}},Pc=function(){if(!this.audioCaptureOptions)return;const{source:e,format:i}=this.audioCaptureOptions;if(i)for(const[n,s]of this.trackStats.entries()){const o=s.participant.toLowerCase().includes("agent")?"agent":"user";"both"!==e&&e!==o||t(this,pc,"m",Rc).call(this,n,s.participant,o,i)}},Rc=function(e,i,n,s){if(!this.audioCaptureOptions)return;const o=t(this,pc,"m",Oc).call(this,e);if(!o?.mediaStreamTrack)return;this.trackCaptureMap.set(e,{participant:i,source:n});const r=new MediaStream([o.mediaStreamTrack]);"opus-webm"===s?t(this,pc,"m",Ic).call(this,r,e,i,n):t(this,pc,"m",Mc).call(this,{stream:r,trackId:e,participant:i,source:n,format:s})},Ic=function(e,i,n,s){if(!this.audioCaptureOptions?.callback)return;const{chunkSize:o,callback:r}=this.audioCaptureOptions;try{const a=t(this,pc,"m",Dc).call(this),c=new MediaRecorder(e,a?{mimeType:a}:{});c.ondataavailable=e=>{e.data.size>0&&e.data.arrayBuffer().then((e=>{const t={participant:n,source:s,timestamp:Date.now(),trackId:i,format:"opus-webm"};r(e,t)}))},c.start(o),this.recorders.set(i,c)}catch(e){this.emit("error",new Error(`Failed to setup encoded audio capture: ${e instanceof Error?e.message:String(e)}`))}},Mc=function(e){const{stream:t,trackId:i,participant:n,source:s,format:o}=e;if(!this.audioCaptureOptions?.callback)return;const{bufferSize:r,callback:a}=this.audioCaptureOptions;try{this.audioContext||(this.audioContext=new AudioContext);const e=this.audioContext;"suspended"===e.state&&e.resume().catch((()=>{}));const c=e.createMediaStreamSource(t),d=e.createScriptProcessor(r,1,1);d.onaudioprocess=e=>{const t=e.inputBuffer,r=t.getChannelData(0);let c=r;if("pcm-i16"===o){const e=new Int16Array(r.length);for(let t=0;t<r.length;t++)e[t]=Math.max(-32768,Math.min(32767,32768*r[t]));c=e}const d={participant:n,source:s,timestamp:Date.now(),trackId:i,format:o,sampleRate:t.sampleRate,channels:t.numberOfChannels};a(c,d)},c.connect(d),d.connect(e.destination),this.processors.set(i,d)}catch(e){this.emit("error",new Error(`Failed to setup PCM audio capture: ${e instanceof Error?e.message:String(e)}`))}},Oc=function(e){if(!this.room)return null;for(const t of Array.from(this.room.remoteParticipants.values()))for(const i of Array.from(t.trackPublications.values()))if(i.track?.sid===e||i.track?.mediaStreamTrack?.id===e)return i.track;if(this.room.localParticipant)for(const t of Array.from(this.room.localParticipant.trackPublications.values()))if(t.track?.sid===e||t.track?.mediaStreamTrack?.id===e)return t.track;return null},Ac=function(){for(const e of this.recorders.values())try{e.stop()}catch{}this.recorders.clear();for(const e of this.processors.values())try{e.disconnect()}catch{}if(this.processors.clear(),this.trackCaptureMap.clear(),this.audioContext){const e=this.audioContext;"closed"!==e.state&&e.close().catch((()=>{})),this.audioContext=null}},Dc=function(){const e=["audio/webm;codecs=opus","audio/mp4","audio/aac","audio/webm","audio/ogg"];for(const t of e)if(MediaRecorder.isTypeSupported(t))return t;return""};class hd extends s.EventEmitter{constructor(e,i,n=!1){super(),xc.add(this),this.room=null,this.isConnected=!1,this.isPaused=!1,this.participants=new Map,this.callStartTime=null,this.connectionAttempts=0,this.reconnectionAttempts=0,this.hasEmittedConnected=!1,this.lkUrl=e,this.accessToken=i,this.logger=Va(n),this.room=new Na({adaptiveStream:!0,dynacast:!0,videoCaptureDefaults:{resolution:Qs.h720.resolution},audioCaptureDefaults:{echoCancellation:!0,noiseSuppression:!0}}),t(this,xc,"m",_c).call(this)}getRoom(){return this.room}async connect(){try{this.logger.log("connect() called",{source:"LiveKitConnection",error:{lkUrl:this.lkUrl,attempt:this.connectionAttempts+1,stack:new Error("Connection call stack").stack}}),this.callStartTime=Date.now(),this.connectionAttempts++,this.room?.prepareConnection(this.lkUrl,this.accessToken);const e=Date.now();await(this.room?.connect(this.lkUrl,this.accessToken)),this.logger.log("room.connect() completed successfully",{source:"LiveKitConnection",error:{connectionTimeMs:Date.now()-e,roomName:this.room?.name,state:this.room?.state}});const t=Date.now()-e;this.emit("connectionEstablished",t),this.isConnected=!0,this.hasEmittedConnected||(this.emit("connected"),this.hasEmittedConnected=!0)}catch(e){this.logger.error("connect() failed",{source:"LiveKitConnection",error:{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}}),this.emit("connectionError",new Error(`LiveKit connection failed: ${e instanceof Error?e.message:String(e)}`))}}forceDisconnect(){this.isConnected=!1,this.emit("disconnected"),t(this,xc,"m",Qc).call(this)}async disconnect(){const e=Date.now();try{if(this.logger.log("LiveKitConnection.disconnect() - START",{source:"LiveKitConnection",error:{timestamp:e,isConnected:this.isConnected,roomName:this.room?.name,state:this.room?.state,participantCount:this.participants.size,hasRoom:!!this.room,stack:new Error("Disconnect call stack").stack}}),this.room){const e=Date.now();this.logger.log("Calling room.disconnect() (LiveKit SDK)",{source:"LiveKitConnection",error:{timestamp:e,roomName:this.room?.name,state:this.room?.state}}),await this.room.disconnect();const t=Date.now();this.logger.log("room.disconnect() completed (LiveKit SDK)",{source:"LiveKitConnection",error:{timestamp:t,roomDisconnectDuration:t-e,roomName:this.room?.name,state:this.room?.state}})}else this.logger.log("No room to disconnect (room is null)",{source:"LiveKitConnection",error:{timestamp:Date.now()}});const i=Date.now();t(this,xc,"m",Qc).call(this);const n=Date.now();this.logger.log("LiveKitConnection.disconnect() - COMPLETE",{source:"LiveKitConnection",error:{timestamp:n,cleanupDuration:n-i,totalDisconnectDuration:n-e}})}catch(t){const i=Date.now();this.logger.error("LiveKitConnection.disconnect() - FAILED",{source:"LiveKitConnection",error:{timestamp:i,timeSinceStart:i-e,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}}),this.emit("connectionError",new Error(`LiveKit disconnection failed: ${t instanceof Error?t.message:String(t)}`))}}pause(){try{this.isPaused=!0,this.room?.localParticipant&&this.room.localParticipant.setMicrophoneEnabled(!1),this.emit("connectionPaused")}catch(e){this.emit("connectionError",new Error(`Failed to pause call: ${e instanceof Error?e.message:String(e)}`))}}resume(){try{this.isPaused=!1,this.room?.localParticipant&&this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("connectionResumed")}catch(e){this.emit("connectionError",new Error(`Failed to resume call: ${e instanceof Error?e.message:String(e)}`))}}getConnectionStats(){return{connectionAttempts:this.connectionAttempts,reconnectionAttempts:this.reconnectionAttempts,isConnected:this.isConnected,participantCount:this.participants.size}}getConnectionAttempts(){return this.connectionAttempts}getReconnectionAttempts(){return this.reconnectionAttempts}getParticipants(){return Array.from(this.participants.values())}cleanup(){t(this,xc,"m",Qc).call(this)}}xc=new WeakSet,_c=function(){this.room&&this.room.on(fs.Connected,t(this,xc,"m",Nc).bind(this)).on(fs.Disconnected,t(this,xc,"m",Uc).bind(this)).on(fs.Reconnecting,t(this,xc,"m",jc).bind(this)).on(fs.Reconnected,t(this,xc,"m",Fc).bind(this)).on(fs.ParticipantConnected,t(this,xc,"m",Bc).bind(this)).on(fs.ParticipantDisconnected,t(this,xc,"m",Vc).bind(this)).on(fs.ParticipantAttributesChanged,t(this,xc,"m",qc).bind(this)).on(fs.ConnectionStateChanged,t(this,xc,"m",Kc).bind(this)).on(fs.SignalConnected,t(this,xc,"m",Hc).bind(this)).on(fs.SignalReconnecting,t(this,xc,"m",Gc).bind(this)).on(fs.MediaDevicesError,t(this,xc,"m",zc).bind(this)).on(fs.ConnectionQualityChanged,t(this,xc,"m",Wc).bind(this)).on(fs.DCBufferStatusChanged,t(this,xc,"m",Jc).bind(this))},Nc=async function(){try{this.isConnected=!0,this.logger.log("Room Connected event fired",{source:"LiveKitConnection",error:{roomName:this.room?.name,localParticipant:this.room?.localParticipant?.identity,state:this.room?.state}}),await(this.room?.localParticipant?.setMicrophoneEnabled(!0)),this.hasEmittedConnected||(this.emit("connected"),this.hasEmittedConnected=!0)}catch(e){this.logger.error("Error in handleConnected",{source:"LiveKitConnection",error:e}),this.emit("connectionError",new Error(`Failed to initialize after connection: ${e instanceof Error?e.message:String(e)}`))}},Uc=function(){const e=Date.now();this.logger.log("Room Disconnected event fired (from LiveKit SDK) - TIMING",{source:"LiveKitConnection",error:{timestamp:e,roomName:this.room?.name,state:this.room?.state,participantCount:this.participants.size}}),this.isConnected=!1;const i=Date.now();this.emit("disconnected");const n=Date.now();this.logger.log("disconnected event emitted to parent - TIMING",{source:"LiveKitConnection",error:{timestamp:n,emitDuration:n-i}});const s=Date.now();t(this,xc,"m",Qc).call(this);const o=Date.now();this.logger.log("Room Disconnected handler complete - TIMING",{source:"LiveKitConnection",error:{timestamp:o,cleanupDuration:o-s,totalHandlerDuration:o-e}})},jc=function(){this.reconnectionAttempts++,this.logger.log("Room Reconnecting",{source:"LiveKitConnection",error:{attempt:this.reconnectionAttempts,roomName:this.room?.name,state:this.room?.state}}),this.emit("reconnecting")},Fc=function(){this.isConnected=!0,this.logger.log("Room Reconnected successfully",{source:"LiveKitConnection",error:{roomName:this.room?.name,state:this.room?.state,participantCount:this.participants.size}}),this.emit("reconnected")},Bc=function(e){this.logger.log("Participant connected in LiveKit layer",{source:"LiveKitConnection",error:{identity:e.identity,sid:e.sid,metadata:e.metadata,totalParticipants:this.participants.size+1}}),this.participants.set(e.sid||"unknown",{identity:e.identity||"unknown",sid:e.sid||"unknown",connectionTime:Date.now(),metadata:e.metadata}),this.emit("participantConnected",e)},Vc=function(e){this.logger.log("Participant disconnected in LiveKit layer",{source:"LiveKitConnection",error:{identity:e.identity,sid:e.sid,totalParticipantsBeforeRemoval:this.participants.size}}),this.participants.delete(e.sid||"unknown"),this.emit("participantDisconnected",e)},qc=function(e,t){if("lk.agent.state"in e){const t=e["lk.agent.state"];void 0!==t&&this.emit("agentStateChanged",t)}},Kc=function(e){this.logger.log("Connection state changed",{source:"LiveKitConnection",error:{newState:e,roomName:this.room?.name,participantCount:this.participants.size}}),this.emit("connectionStateChanged",e)},Hc=function(){this.logger.log("Signal connection established",{source:"LiveKitConnection",error:{roomName:this.room?.name,state:this.room?.state}})},Gc=function(){this.logger.log("Signal reconnecting (signaling server connection lost)",{source:"LiveKitConnection",error:{roomName:this.room?.name,state:this.room?.state,participantCount:this.participants.size}})},zc=function(e){this.logger.error("Media devices error",{source:"LiveKitConnection",error:{error:e.message,stack:e.stack,roomName:this.room?.name}})},Wc=function(e,t){this.logger.log("Connection quality changed",{source:"LiveKitConnection",error:{participant:t.identity,quality:e,roomName:this.room?.name}})},Jc=function(e,t){this.logger.log("DataChannel buffer status changed",{source:"LiveKitConnection",error:{isLow:e,kind:t,roomName:this.room?.name,participantCount:this.participants.size}})},Qc=function(){this.participants.clear(),this.isConnected=!1,this.isPaused=!1,this.hasEmittedConnected=!1};class pd extends s.EventEmitter{constructor(e=[]){super(),this.room=null,this.tools=[],this.tools=e}setRoom(e){this.room=e,e&&this.tools.length>0&&this.registerTools()}setTools(e){this.tools=Array.isArray(e)?e:[],this.room&&this.registerTools()}registerTools(){if(this.room&&0!==this.tools.length){for(const e of this.tools)e.function_name&&"function"==typeof e.fn&&this.room?.registerRpcMethod(e.function_name,(async t=>{try{const i=JSON.parse(t.payload||"{}"),n=await(e.fn?.(...Object.values(i)));return JSON.stringify(n)}catch(e){return JSON.stringify({error:e instanceof Error?e.message:String(e)})}}));this.emit("toolsRegistered",this.tools.length)}}handleDataReceived(e,t){try{const i=JSON.parse((new TextDecoder).decode(e)),n=i.event,s=i.content||i.data||i;switch(n){case"answer":this.emit("answerReceived",s);break;case"transcription":this.emit("transcriptionReceived",s);break;default:this.emit("customEvent",n,s,{timestamp:Date.now(),participant:t||"unknown",rawMessage:i})}this.emit("dataReceived",i,t||"unknown")}catch(e){}}handleTranscriptionReceived(e){try{for(const t of e)t.text&&this.emit("transcriptionReceived",t.text)}catch{}}getToolCount(){return this.tools.length}getTools(){return this.tools}cleanup(){}}class md extends s.EventEmitter{constructor(e,i,n=[],s=!1){super(),$c.add(this),this.lkUrl=e,this.accessToken=i,this.logger=Va(s),this.logger.log("Initializing LiveKitManager",{source:"LiveKitManager",error:{lkUrl:e,toolsCount:n.length,debug:s}}),this.logger.log("Creating LiveKitConnection module",{source:"LiveKitManager"}),this.connection=new hd(e,i,s),this.logger.log("Creating LiveKitAnalytics module",{source:"LiveKitManager"}),this.analytics=new hc,this.logger.log("Creating LiveKitAudioManager module",{source:"LiveKitManager"}),this.audioManager=new Lc,this.logger.log("Creating LiveKitToolRegistry module",{source:"LiveKitManager",error:{toolsCount:n.length}}),this.toolRegistry=new pd(n),n.length>0&&this.logger.log("Registered client-side tools",{source:"LiveKitManager",error:{toolNames:n.map((e=>e.function_name)),totalTools:n.length}}),this.logger.log("Setting up module communication",{source:"LiveKitManager"}),t(this,$c,"m",Yc).call(this),this.logger.log("Setting up event forwarding",{source:"LiveKitManager"}),t(this,$c,"m",Xc).call(this),this.logger.log("Setting up room event handlers",{source:"LiveKitManager"}),t(this,$c,"m",Zc).call(this),this.logger.log("LiveKitManager initialization complete",{source:"LiveKitManager"})}async connect(){if(this.connection.isConnected)return void this.logger.log("Already connected, skipping duplicate connection",{source:"LiveKitManager"});this.logger.log("Starting LiveKit room connection",{source:"LiveKitManager"});const e=this.connection.getConnectionStats();this.logger.log("Updating connection analytics",{source:"LiveKitManager",error:{currentAttempts:e.connectionAttempts,reconnectionAttempts:e.reconnectionAttempts}}),this.analytics.updateConnectionStats(e.connectionAttempts+1,e.reconnectionAttempts);const t=Date.now();await this.connection.connect();const i=Date.now()-t;this.logger.log("LiveKit room connection established",{source:"LiveKitManager",error:{duration:`${i}ms`}}),this.connection.room&&this.audioManager.setRoom(this.connection.room)}async disconnect(){const e=Date.now();this.logger.log("LiveKitManager.disconnect() - START",{source:"LiveKitManager",error:{timestamp:e,isConnected:this.connection.isConnected,participantCount:this.connection.participants.size,hasRoom:!!this.connection.room}});const t=Date.now();await this.connection.disconnect();const i=Date.now();this.logger.log("LiveKitManager.disconnect() - connection.disconnect() completed",{source:"LiveKitManager",error:{timestamp:i,connectionDisconnectDuration:i-t}});const n=Date.now();this.logger.log("Performing cleanup of all modules",{source:"LiveKitManager",error:{timestamp:n}}),this.cleanup();const s=Date.now();this.logger.log("LiveKitManager.disconnect() - COMPLETE",{source:"LiveKitManager",error:{timestamp:s,cleanupDuration:s-n,totalDisconnectDuration:s-e}})}pause(){this.logger.log("Pausing voice conversation",{source:"LiveKitManager",error:{isConnected:this.connection.isConnected,wasPaused:this.connection.isPaused}}),this.connection.pause(),this.audioManager.pauseAllAudio(),this.logger.log("Voice conversation paused",{source:"LiveKitManager"})}resume(){this.logger.log("Resuming voice conversation",{source:"LiveKitManager",error:{isConnected:this.connection.isConnected,wasPaused:this.connection.isPaused}}),this.connection.resume(),this.audioManager.resumeAllAudio(),this.logger.log("Voice conversation resumed",{source:"LiveKitManager"})}setVolume(e){this.logger.log("Setting audio volume",{source:"LiveKitManager",error:{volume:e,percentage:`${Math.round(100*e)}%`}}),this.audioManager.setVolume(e)}get room(){return this.connection.room}get isConnected(){return this.connection.isConnected}get isPaused(){return this.connection.isPaused}get volume(){return this.audioManager.volume}get audioElements(){return this.audioManager.audioElements}get tools(){return this.toolRegistry.getTools()}get callStats(){return this.analytics.callStats}get connectionMetrics(){return this.analytics.connectionMetrics}get audioMetrics(){return this.analytics.audioMetrics}get performanceMetrics(){return this.analytics.performanceMetrics}get analyticsInterval(){return this.analytics.analyticsInterval}get callStartTime(){return this.analytics.callStartTime||this.connection.callStartTime}get participants(){return this.connection.participants}get trackStats(){return this.audioManager.trackStats}getConnectionStats(){return this.analytics.getConnectionStats()}getAudioLevels(){return{...this.analytics.getAudioLevels(),isPaused:this.connection.isPaused,volume:this.audioManager.volume}}getPerformanceMetrics(){return this.analytics.getPerformanceMetrics()}getParticipants(){return this.connection.getParticipants()}getTrackStats(){return this.audioManager.getTrackStats()}getCallAnalytics(){return this.analytics.getCallAnalytics(this.getParticipants(),this.getTrackStats(),this.audioManager.volume,this.connection.isPaused)}registerTools(e){this.logger.log("Registering client-side tools",{source:"LiveKitManager",error:{newToolsCount:Array.isArray(e)?e.length:0,hasRoom:!!this.room,isConnected:this.connection.isConnected}}),Array.isArray(e)&&e.length>0&&(this.logger.log("Setting new tools in registry",{source:"LiveKitManager",error:{toolNames:e.map((e=>e.function_name)),totalTools:e.length}}),this.toolRegistry.setTools(e)),this.room&&this.toolRegistry.setRoom(this.room),this.toolRegistry.registerTools(),this.logger.log("Tools registration complete",{source:"LiveKitManager",error:{registeredTools:this.toolRegistry.getTools().length}})}cleanup(){this.connection.cleanup(),this.audioManager.cleanup(),this.analytics.cleanup(),this.toolRegistry.cleanup()}}$c=new WeakSet,Yc=function(){this.connection.on("connected",(()=>{const e=this.connection.room;this.analytics.setRoom(e),this.toolRegistry.setRoom(e),this.audioManager.setRoom(e),this.analytics.setConnectionState(!0,this.connection.callStartTime),this.toolRegistry.registerTools(),this.analytics.startAnalyticsCollection(),t(this,$c,"m",Zc).call(this)})),this.connection.on("connectionEstablished",(e=>{this.analytics.setConnectionEstablishedTime(e)})),this.connection.on("connected",(()=>{const e=this.connection.getConnectionStats();this.analytics.updateConnectionStats(e.connectionAttempts,e.reconnectionAttempts)})),this.connection.on("reconnecting",(()=>{const e=this.connection.getConnectionStats();this.analytics.updateConnectionStats(e.connectionAttempts,e.reconnectionAttempts)})),this.connection.on("disconnected",(()=>{this.analytics.stopAnalyticsCollection(),this.analytics.setConnectionState(!1),this.audioManager.cleanup(),this.toolRegistry.cleanup(),this.analytics.cleanup()})),this.connection.on("participantConnected",(()=>{t(this,$c,"m",ed).call(this)})),this.connection.on("participantDisconnected",(()=>{t(this,$c,"m",ed).call(this)})),this.audioManager.on("trackSubscribed",(()=>{t(this,$c,"m",ed).call(this)})),this.audioManager.on("trackUnsubscribed",(()=>{t(this,$c,"m",ed).call(this)}))},Xc=function(){this.connection.on("connected",(()=>this.emit("connected"))),this.connection.on("disconnected",(()=>this.emit("disconnected"))),this.connection.on("reconnecting",(()=>this.emit("reconnecting"))),this.connection.on("reconnected",(()=>this.emit("reconnected"))),this.connection.on("participantConnected",(e=>this.emit("participantConnected",e))),this.connection.on("participantDisconnected",(e=>this.emit("participantDisconnected",e))),this.connection.on("agentStateChanged",(e=>this.emit("agentStateChanged",e))),this.connection.on("connectionStateChanged",(e=>this.emit("connectionStateChanged",e))),this.connection.on("connectionError",(e=>{this.listenerCount("error")>0&&this.emit("error",e)})),this.audioManager.on("trackSubscribed",(e=>this.emit("trackSubscribed",e))),this.audioManager.on("trackUnsubscribed",(e=>this.emit("trackUnsubscribed",e))),this.audioManager.on("speaking",(()=>this.emit("speaking"))),this.audioManager.on("listening",(()=>this.emit("listening"))),this.audioManager.on("volumeChanged",(e=>this.emit("volumeChanged",e))),this.audioManager.on("error",(e=>{this.listenerCount("error")>0&&this.emit("error",e)})),this.audioManager.on("micMuted",(()=>this.emit("micMuted"))),this.audioManager.on("micUnmuted",(()=>this.emit("micUnmuted"))),this.analytics.on("connectionQualityChanged",(e=>this.emit("connectionQualityChanged",e))),this.analytics.on("audioPlaybackChanged",(e=>this.emit("audioPlaybackChanged",e))),this.analytics.on("analyticsUpdated",(e=>this.emit("analyticsUpdated",e))),this.toolRegistry.on("answerReceived",(e=>this.emit("answerReceived",e))),this.toolRegistry.on("transcriptionReceived",(e=>this.emit("transcriptionReceived",e))),this.toolRegistry.on("customEvent",((e,t,i)=>this.emit("customEvent",e,t,i))),this.toolRegistry.on("dataReceived",((e,t)=>this.emit("dataReceived",e,t))),this.toolRegistry.on("toolsRegistered",(e=>this.emit("toolsRegistered",e)))},Zc=function(){const e=this.connection.room;if(!e)return;const t=[[fs.TrackSubscribed,(e,t,i)=>{this.logger.log("Track subscribed",{source:"LiveKitManager",error:{trackSid:e.sid,trackKind:e.kind,participantIdentity:i.identity,isMuted:t.isMuted}}),this.audioManager.handleTrackSubscribed(e,t,i)}],[fs.TrackUnsubscribed,(e,t,i)=>{this.logger.log("Track unsubscribed",{source:"LiveKitManager",error:{trackSid:e.sid,trackKind:e.kind,participantIdentity:i.identity}}),this.audioManager.handleTrackUnsubscribed(e,t,i)}],[fs.DataReceived,(e,t)=>{this.logger.log("Data received from participant",{source:"LiveKitManager",error:{payloadSize:e.length,participantIdentity:t?.identity||"unknown"}}),this.toolRegistry.handleDataReceived(e,t?.identity)}],[fs.TranscriptionReceived,e=>{this.toolRegistry.handleTranscriptionReceived(e)}],[fs.ConnectionQualityChanged,(e,t)=>{this.logger.log("Connection quality changed",{source:"LiveKitManager",error:{quality:e,participantIdentity:t.identity,isLocal:t.isLocal}}),this.analytics.handleConnectionQualityChanged(e,t)}],[fs.AudioPlaybackStatusChanged,e=>{this.logger.log("Audio playback status changed",{source:"LiveKitManager",error:{playing:e,state:e?"started":"stopped"}}),this.analytics.handleAudioPlaybackChanged(e)}],[fs.MediaDevicesError,e=>{this.logger.error("Media devices error",{source:"LiveKitManager",error:{message:e.message,name:e.name}}),this.emit("mediaDevicesError",e)}],[fs.LocalTrackPublished,e=>{this.logger.log("Local track published",{source:"LiveKitManager",error:{trackSid:e.trackSid,trackKind:e.kind,isMuted:e.isMuted}}),this.emit("localTrackPublished",{publication:e,track:e.track})}]];for(const[i,n]of t)e.on(i,n)},ed=function(){const e=this.connection.participants.size,t=this.audioManager.trackStats.size;this.logger.log("Updating analytics counts",{source:"LiveKitManager",error:{participants:e,tracks:t}}),this.analytics.updateCounts(e,t)};class gd{constructor(){this._wakeLock=null,this._wakeLock=null}async acquire(){if("wakeLock"in(e=navigator)&&"object"==typeof e.wakeLock)try{this._wakeLock=await navigator.wakeLock.request("screen"),this._wakeLock.addEventListener("release",(()=>{this._wakeLock=null}))}catch{}var e}async release(){if(null!==this._wakeLock)try{await this._wakeLock.release(),this._wakeLock=null}catch{}}isActive(){return null!==this._wakeLock}}class fd extends Error{constructor(e,t){super(e),this.name="HamsaApiError",this.messageKey=t}}class vd extends s.EventEmitter{constructor(e,{API_URL:t="https://api.tryhamsa.com",LIVEKIT_URL:i="wss://rtc.eu.tryhamsa.com",debug:n=!1}={}){super(),td.add(this),this.liveKitManager=null,this.jobId=null,this.userInitiatedEnd=!1,this.liveKitManager=null,this.apiKey=e,this.API_URL=t,this.LIVEKIT_URL=i,this.debug=n,this.logger=Va(n),this.jobId=null,this.wakeLockManager=new gd}setVolume(e){this.liveKitManager&&this.liveKitManager.setVolume(e)}getOutputVolume(){return this.liveKitManager?.audioManager.getOutputVolume()??vd.DEFAULT_OUTPUT_VOLUME}getJobId(){return this.jobId}getInputVolume(){return this.liveKitManager?.audioManager.getInputVolume()??vd.DEFAULT_INPUT_VOLUME}setMicMuted(e){this.liveKitManager&&this.liveKitManager.audioManager.setMicMuted(e)}isMicMuted(){return this.liveKitManager?.audioManager.isMicMuted()??!1}sendUserActivity(){this.liveKitManager?.isConnected&&this.logger.log("User activity detected - preventing agent interruption",{source:"HamsaVoiceAgent"})}sendContextualUpdate(e){this.liveKitManager?.isConnected&&this.logger.log("Sending contextual update",{source:"HamsaVoiceAgent",error:{context:e}})}getInputByteFrequencyData(){return this.liveKitManager?.audioManager.getInputByteFrequencyData()??new Uint8Array(0)}getOutputByteFrequencyData(){return this.liveKitManager?.audioManager.getOutputByteFrequencyData()??new Uint8Array(0)}enableAudioCapture(e){if(!this.liveKitManager)throw new Error("Cannot enable audio capture: not connected to agent");this.liveKitManager.audioManager.enableAudioCapture(e)}disableAudioCapture(){this.liveKitManager?.audioManager.disableAudioCapture()}async start({agentId:e,params:i={},voiceEnablement:n=!1,tools:s=[],userId:o,preferHeadphonesForIosDevices:r=!1,connectionDelay:a,disableWakeLock:c=!1,onAudioData:d,captureAudio:l}){try{this.logger.log("SDK initialized - disconnect debugging enabled",{source:"HamsaVoiceAgent"}),this.userInitiatedEnd=!1,this.logger.log("Starting conversation initialization",{source:"HamsaVoiceAgent",error:{agentId:e,voiceEnablement:n,toolsCount:s?.length??0,hasParams:Object.keys(i).length>0}});const o=await t(this,td,"m",od).call(this,e,i,n,s);this.logger.log("Creating LiveKitManager instance",{source:"HamsaVoiceAgent",error:{livekitUrl:this.LIVEKIT_URL,tokenLength:o.length,debug:this.debug}}),this.liveKitManager=new md(this.LIVEKIT_URL,o,s,this.debug),this.logger.log("LiveKitManager created, setting up event listeners",{source:"HamsaVoiceAgent"}),this.liveKitManager.on("error",(e=>{this.logger.error("LiveKitManager error event",{source:"HamsaVoiceAgent",error:e}),this.emit("error",e)})).on("connected",(()=>{this.logger.log("LiveKit connection established",{source:"HamsaVoiceAgent"}),l?(this.logger.log("Enabling audio capture via captureAudio options",{source:"HamsaVoiceAgent",error:{source:l.source,format:l.format}}),this.liveKitManager?.audioManager.enableAudioCapture(l)):d&&(this.logger.log("Enabling audio capture via onAudioData",{source:"HamsaVoiceAgent"}),this.liveKitManager?.audioManager.enableAudioCapture({source:"agent",format:"opus-webm",chunkSize:100,callback:d})),this.emit("start")})).on("transcriptionReceived",(e=>{this.logger.log("Transcription received from user",{source:"HamsaVoiceAgent",error:{length:e.length,preview:e.substring(0,50)}}),this.emit("transcriptionReceived",e)})).on("answerReceived",(e=>{this.logger.log("Answer received from agent",{source:"HamsaVoiceAgent",error:{length:e.length,preview:e.substring(0,50)}}),this.emit("answerReceived",e)})).on("speaking",(()=>{this.logger.log("Agent started speaking",{source:"HamsaVoiceAgent"}),this.emit("speaking")})).on("listening",(()=>{this.logger.log("Agent started listening",{source:"HamsaVoiceAgent"}),this.emit("listening")})).on("disconnected",(()=>{const e=Date.now();this.logger.log("disconnected event fired - room connection closed - TIMING",{source:"HamsaVoiceAgent",error:{timestamp:e,userInitiatedEnd:this.userInitiatedEnd}}),this.emit("callEnded");const t=Date.now();this.emit("closed"),this.logger.log("closed event emitted - TIMING",{source:"HamsaVoiceAgent",error:{timestamp:t,timeSinceDisconnected:t-e}}),this.userInitiatedEnd=!1})).on("trackSubscribed",(e=>{this.logger.log("Track subscribed",{source:"HamsaVoiceAgent",error:{kind:e.track?.kind,trackSid:e.track?.sid,participant:e.participant}}),this.emit("trackSubscribed",e)})).on("trackUnsubscribed",(e=>{this.logger.log("Track unsubscribed",{source:"HamsaVoiceAgent",error:{kind:e.track?.kind,trackSid:e.track?.sid,participant:e.participant}}),this.emit("trackUnsubscribed",e)})).on("localTrackPublished",(e=>{this.logger.log("Local track published",{source:"HamsaVoiceAgent",error:{kind:e.publication?.kind,trackSid:e.publication?.trackSid}}),this.emit("localTrackPublished",e)})).on("info",(e=>{this.logger.log("Info message received",{source:"HamsaVoiceAgent",error:{info:e}}),this.emit("info",e)})).on("reconnecting",(()=>{this.logger.warn("Connection reconnecting",{source:"HamsaVoiceAgent"}),this.emit("reconnecting")})).on("reconnected",(()=>{this.logger.log("Connection reconnected successfully",{source:"HamsaVoiceAgent"}),this.emit("reconnected")})).on("participantConnected",(e=>{this.logger.log("Participant connected",{source:"HamsaVoiceAgent",error:{identity:e.identity,sid:e.sid}}),this.emit("participantConnected",e)})).on("participantDisconnected",(e=>{this.logger.log("Participant disconnected",{source:"HamsaVoiceAgent",error:{identity:e.identity,sid:e.sid,hasAgentInIdentity:e.identity?.includes("agent"),remainingCount:this.liveKitManager?.connection.participants.size??0}}),this.emit("participantDisconnected",e)})).on("agentStateChanged",(e=>{this.logger.log("Agent state changed",{source:"HamsaVoiceAgent",error:{state:e}}),this.emit("agentStateChanged",e)})).on("connectionQualityChanged",(e=>{this.logger.log("Connection quality changed",{source:"HamsaVoiceAgent",error:{quality:e.quality,participant:e.participant}}),this.emit("connectionQualityChanged",e)})).on("connectionStateChanged",(e=>{this.logger.log("Connection state changed",{source:"HamsaVoiceAgent",error:{state:e}}),this.emit("connectionStateChanged",e)})).on("audioPlaybackChanged",(e=>{this.logger.log("Audio playback state changed",{source:"HamsaVoiceAgent",error:{playing:e}}),this.emit("audioPlaybackChanged",e)})).on("micMuted",(()=>{this.logger.log("Microphone muted",{source:"HamsaVoiceAgent"}),this.emit("micMuted")})).on("micUnmuted",(()=>{this.logger.log("Microphone unmuted",{source:"HamsaVoiceAgent"}),this.emit("micUnmuted")})).on("analyticsUpdated",(e=>this.emit("analyticsUpdated",e))).on("customEvent",((e,t,i)=>this.emit("customEvent",e,t,i))).on("dataReceived",((e,t)=>this.emit("dataReceived",e,t))),this.logger.log("Connecting to LiveKit room",{source:"HamsaVoiceAgent",error:{livekitUrl:this.LIVEKIT_URL}});const r=Date.now();await this.liveKitManager.connect();const a=Date.now()-r;this.logger.log("Connected to LiveKit room",{source:"HamsaVoiceAgent",error:{duration:`${a}ms`}}),this.logger.log("Acquiring screen wake lock",{source:"HamsaVoiceAgent"});try{await this.wakeLockManager.acquire(),this.logger.log("Screen wake lock acquired successfully",{source:"HamsaVoiceAgent"})}catch(e){this.logger.warn("Failed to acquire screen wake lock",{source:"HamsaVoiceAgent",error:{error:e instanceof Error?e.message:String(e)}})}this.logger.log("Call started successfully",{source:"HamsaVoiceAgent",error:{totalStartupTime:Date.now()-r+"ms",jobId:this.jobId}}),this.emit("callStarted",{jobId:this.jobId??""})}catch(e){if(this.logger.error("Failed to start call",{source:"HamsaVoiceAgent",error:{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,isHamsaApiError:e instanceof fd}}),this.listenerCount("error")>0)if(e instanceof fd)this.emit("error",e);else{const t=e instanceof Error?e.message:String(e);this.emit("error",new Error(`Failed to start call: ${t}`))}}}end(){const e=Date.now();this.logger.log("end() called - START DISCONNECT TIMING",{source:"HamsaVoiceAgent",error:{timestamp:e,userInitiatedEnd:this.userInitiatedEnd,isConnected:this.liveKitManager?.isConnected??!1,stack:new Error("Stack trace").stack}}),t(this,td,"m",id).call(this,e).then((()=>{const t=Date.now();this.logger.log("end() completed - END DISCONNECT TIMING",{source:"HamsaVoiceAgent",error:{timestamp:t,totalDuration:t-e}})})).catch((i=>{t(this,td,"m",sd).call(this,i,e)})),t(this,td,"m",nd).call(this)}pause(){this.liveKitManager&&(this.liveKitManager.pause(),this.wakeLockManager?.isActive()&&this.wakeLockManager.release().catch((e=>{})),this.emit("callPaused"))}resume(){this.liveKitManager&&(this.liveKitManager.resume(),this.wakeLockManager.acquire().catch((e=>{})),this.emit("callResumed"))}async getJobDetails(e=5,i=1e3,n=2){if(!this.jobId)throw new Error("Cannot fetch job details: jobId is not set. Start a conversation first.");const s=`${this.API_URL}/v1/voice-agents/conversation/${this.jobId}`,o={Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},r=new URLSearchParams({jobId:this.jobId});let a=i;const c=async(i=1)=>{try{const e=await fetch(`${s}?${r.toString()}`,{method:"GET",headers:o});if(!e.ok){const t=await e.text();throw new Error(`API Error: ${e.status} ${e.statusText} - ${t}`)}const t=await e.json();if("COMPLETED"===t.data.status)return t.data;throw new Error(`Job status is not COMPLETED: ${t.data.status}`)}catch(s){if(i<e)return await t(this,td,"m",ud).call(this,a),a*=n,c(i+1);throw new Error(`Failed to fetch job details after ${e} attempts: ${s instanceof Error?s.message:String(s)}`)}};return await c()}getConnectionStats(){return this.liveKitManager?this.liveKitManager.getConnectionStats():null}getAudioLevels(){return this.liveKitManager?this.liveKitManager.getAudioLevels():null}getPerformanceMetrics(){return this.liveKitManager?this.liveKitManager.getPerformanceMetrics():null}getParticipants(){return this.liveKitManager?this.liveKitManager.getParticipants():[]}getTrackStats(){return this.liveKitManager?this.liveKitManager.getTrackStats():null}getCallAnalytics(){return this.liveKitManager?this.liveKitManager.getCallAnalytics():null}getRoom(){return this.liveKitManager?.connection.getRoom()??null}getRemoteAudioTrack(){const e=this.liveKitManager?.connection.getRoom();if(e?.remoteParticipants)for(const t of e.remoteParticipants.values()){const e=Array.from(t.audioTrackPublications.values())[0];if(e?.track)return e.track}}}td=new WeakSet,id=async function(e){if(!this.liveKitManager)return;this.userInitiatedEnd=!0;const t=this.liveKitManager.connection.room?.name;if(t){const e=Date.now();this.logger.log("Calling room destroy API",{source:"HamsaVoiceAgent",error:{timestamp:e,roomName:t}});try{const i=await fetch(`${this.API_URL}/v1/voice-agents/room/destroy`,{method:"DELETE",headers:{Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({roomName:t})}),n=Date.now();if(i.ok){const t=await i.json();this.logger.log("Room destroy API succeeded",{source:"HamsaVoiceAgent",error:{timestamp:n,duration:n-e,success:t.success,message:t.message}})}else{const t=await i.text();this.logger.error("Room destroy API failed",{source:"HamsaVoiceAgent",error:{timestamp:n,duration:n-e,status:i.status,statusText:i.statusText,errorText:t}})}}catch(t){const i=Date.now();this.logger.error("Room destroy API threw error",{source:"HamsaVoiceAgent",error:{timestamp:i,duration:i-e,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}})}}else this.logger.warn("Skipping room destroy API - missing roomName",{source:"HamsaVoiceAgent",error:{hasRoomName:!!t}});const i=Date.now();this.logger.log("Calling liveKitManager.disconnect()",{source:"HamsaVoiceAgent",error:{timestamp:i,timeSinceEndCalled:i-e}}),await this.liveKitManager.disconnect();const n=Date.now();this.logger.log("liveKitManager.disconnect() completed",{source:"HamsaVoiceAgent",error:{timestamp:n,disconnectCallDuration:n-i}}),this.emit("callEnded");const s=Date.now();this.logger.log("callEnded event emitted",{source:"HamsaVoiceAgent",error:{timestamp:s,totalTimeInEndMethod:s-e}})},nd=function(){this.wakeLockManager?.isActive()&&this.wakeLockManager.release().catch((e=>{}))},sd=function(e,t){if(this.logger.error("end() threw error",{source:"HamsaVoiceAgent",error:{error:e instanceof Error?e.message:String(e),timeSinceStart:Date.now()-t}}),this.listenerCount("error")>0)if(e instanceof fd)this.emit("error",e);else{const t=e instanceof Error?e.message:String(e);this.emit("error",new Error(`Failed to end call: ${t}`))}},od=async function(e,i,n,s){const o={Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},r=await t(this,td,"m",ad).call(this,e,i,o),a=r.liveKitAccessToken,c=t(this,td,"m",dd).call(this,a,r.jobId,e);return await t(this,td,"m",cd).call(this,{voiceAgentId:e,params:i,voiceEnablement:n,tools:s,headers:o,jobIdFromToken:c,tokenData:r}),this.jobId=c,a},rd=function(e,t,i=!1){try{const e=JSON.parse(t);if(e.message)throw new fd(e.message,e.messageKey)}catch(e){if(e instanceof fd)throw e}const n=i?`${e.status} ${e.statusText} - ${t}`:t;throw new fd(n)},ad=async function(e,i,n){this.logger.log("Fetching participant token from API",{source:"HamsaVoiceAgent",error:{voiceAgentId:e,apiUrl:this.API_URL,paramsCount:Object.keys(i).length}});const s=Date.now(),o=await fetch(`${this.API_URL}/v1/voice-agents/room/participant-token`,{method:"POST",headers:n,body:JSON.stringify({voiceAgentId:e,params:i})}),r=Date.now()-s;if(this.logger.log("Received API response for participant token",{source:"HamsaVoiceAgent",error:{status:o.status,ok:o.ok,duration:`${r}ms`}}),!o.ok){const e=await o.text();this.logger.error("API request failed for participant token",{source:"HamsaVoiceAgent",error:{status:o.status,statusText:o.statusText,errorText:e}}),t(this,td,"m",rd).call(this,o,e,!0)}const a=await o.json();if(!a?.success||!a?.data?.liveKitAccessToken)throw this.logger.error("Invalid token response structure",{source:"HamsaVoiceAgent",error:{success:a?.success,hasToken:!!a?.data?.liveKitAccessToken}}),new Error("Failed to get LiveKit access token");return this.logger.log("Successfully received LiveKit access token",{source:"HamsaVoiceAgent",error:{tokenLength:a.data.liveKitAccessToken.length,hasJobId:!!a.data.jobId,jobId:a.data.jobId}}),a.data},cd=async function(e){const{voiceAgentId:i,params:n,voiceEnablement:s,tools:o,headers:r,jobIdFromToken:a,tokenData:c}=e,d=o?.length>0?t(this,td,"m",ld).call(this,o):[],l={tools:d,voiceEnablement:s,voiceAgentId:i,params:n,jobId:a??c.jobId??i,channelType:"Web"};this.logger.log("Initializing conversation with API",{source:"HamsaVoiceAgent",error:{voiceAgentId:i,toolsCount:d.length,voiceEnablement:s,jobId:l.jobId,channelType:l.channelType}});const u=Date.now(),h=await fetch(`${this.API_URL}/v1/voice-agents/room/conversation-init`,{method:"POST",headers:r,body:JSON.stringify(l),redirect:"follow"}),p=Date.now()-u;if(this.logger.log("Received conversation init response",{source:"HamsaVoiceAgent",error:{status:h.status,ok:h.ok,duration:`${p}ms`}}),!h.ok){const e=await h.text();this.logger.error("Conversation initialization failed",{source:"HamsaVoiceAgent",error:{status:h.status,statusText:h.statusText,errorText:e}}),t(this,td,"m",rd).call(this,h,e,!1)}this.logger.log("Conversation initialized successfully",{source:"HamsaVoiceAgent"})},dd=function(e,t,i){this.logger.log("Parsing JWT token for jobId",{source:"HamsaVoiceAgent",error:{tokenPreview:e.substring(0,20),endpointJobId:t,voiceAgentId:i}});try{const t=function(e,t){if("string"!=typeof e)throw new o("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,n=e.split(".")[i];if("string"!=typeof n)throw new o(`Invalid token specified: missing part #${i+1}`);let s;try{s=r(n)}catch(e){throw new o(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new o(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e);this.logger.log("JWT token parsed successfully",{source:"HamsaVoiceAgent",error:{hasRoomConfig:!!t.roomConfig,hasAgents:!!t.roomConfig?.agents,agentsCount:t.roomConfig?.agents?.length??0}});const i=t?.roomConfig?.agents?.[0]?.metadata;if("string"==typeof i){const e=JSON.parse(i);if("string"==typeof e.jobId&&e.jobId.length>0)return this.logger.log("Extracted jobId from token metadata",{source:"HamsaVoiceAgent",error:{jobId:e.jobId}}),e.jobId}}catch(e){this.logger.warn("Failed to parse jobId from token, using fallback",{source:"HamsaVoiceAgent",error:{error:e instanceof Error?e.message:String(e)}})}const n=t??i;return this.logger.log("Using fallback jobId",{source:"HamsaVoiceAgent",error:{jobId:n,source:t?"endpoint":"voiceAgentId"}}),n},ld=function(e){return e.map((e=>({type:"function",function:{name:e.function_name,description:e.description,parameters:{type:"object",properties:e.parameters?.reduce(((e,t)=>(e[t.name]={type:t.type,description:t.description},e)),{})||{},required:e.required||[]},func_map:e.func_map}})))},ud=function(e){return new Promise((t=>setTimeout(t,e)))},vd.DEFAULT_OUTPUT_VOLUME=0,vd.DEFAULT_INPUT_VOLUME=0,e.HamsaApiError=fd,e.HamsaVoiceAgent=vd,e.default=vd,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
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).HamsaVoiceAgent={})}(this,(function(e){"use strict";function t(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)}"function"==typeof SuppressedError&&SuppressedError;var i,n={exports:{}};var s=function(){if(i)return n.exports;i=1;var e,t="object"==typeof Reflect?Reflect:null,s=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var o=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}n.exports=r,n.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}f(e,t,o,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&f(e,"error",t,i)}(e,s,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function d(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function l(e,t,i,n){var s,o,r,a;if(c(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),r=o[t]),void 0===r)r=o[t]=i,++e._eventsCount;else if("function"==typeof r?r=o[t]=n?[i,r]:[r,i]:n?r.unshift(i):r.push(i),(s=d(e))>0&&r.length>s&&!r.warned){r.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=r.length,a=l,console&&console.warn&&console.warn(a)}return e}function u(){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 h(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=u.bind(n);return s.listener=i,n.wrapFn=s,s}function p(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):g(s,s.length)}function m(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 g(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function f(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(o){n.once&&e.removeEventListener(t,s),i(o)}))}}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||o(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),r.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},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||o(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},r.prototype.getMaxListeners=function(){return d(this)},r.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,o=this._events;if(void 0!==o)n=n&&void 0===o.error;else if(!n)return!1;if(n){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)s(c,this,t);else{var d=c.length,l=g(c,d);for(i=0;i<d;++i)s(l[i],this,t)}return!0},r.prototype.addListener=function(e,t){return l(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return l(this,e,t,!0)},r.prototype.once=function(e,t){return c(t),this.on(e,h(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,h(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,s,o,r;if(c(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,o=i.length-1;o>=0;o--)if(i[o]===t||i[o].listener===t){r=i[o].listener,s=o;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,r||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,o=Object.keys(i);for(n=0;n<o.length;++n)"removeListener"!==(s=o[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},r.prototype.listeners=function(e){return p(this,e,!0)},r.prototype.rawListeners=function(e){return p(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},r.prototype.listenerCount=m,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},n.exports}();class o extends Error{}function r(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i})))}(t)}catch(e){return atob(t)}}function a(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)}o.prototype.name="InvalidTokenError";var c=Object.defineProperty,d=(e,t,i)=>((e,t,i)=>t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class l{constructor(){d(this,"_locking"),d(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function u(e,t){if(!e)throw new Error(t)}function h(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function p(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function m(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const g=Symbol("@bufbuild/protobuf/enum-type");function f(e){const t=e[g];return u(t,"missing enum type on enum object"),t}function v(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),s=Object.create(null),o=[];for(const e of t){const t=y(e);o.push(t),n[e.name]=t,s[e.no]=t}return{typeName:e,values:o,findName:e=>n[e],findNumber:e=>s[e]}}function k(e,t,i){const n={};for(const e of t){const t=y(e);n[t.localName]=t.no,n[t.no]=t.localName}return v(n,e,t),n}function y(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class T{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(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}}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,!(128&n))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function S(e,t,i){for(let n=0;n<28;n+=7){const s=e>>>n,o=!(s>>>7==0&&0==t),r=255&(o?128|s:s);if(i.push(r),!o)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),o=255&(s?128|n:n);if(i.push(o),!s)return}i.push(t>>>31&1)}}const w=4294967296;function E(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function o(t,o){const r=Number(e.slice(t,o));s*=i,n=n*i+r,n>=w&&(s+=n/w|0,n%=w)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?I(n,s):R(n,s)}function P(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(w*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,o=i+8147497*n,r=2*n;const a=1e7;return s>=a&&(o+=Math.floor(s/a),s%=a),o>=a&&(r+=Math.floor(o/a),o%=a),r.toString()+M(o)+M(s)}function R(e,t){return{lo:0|e,hi:0|t}}function I(e,t){return t=~t,e?e=1+~e:t+=1,R(e,t)}const M=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 A(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const D=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>u(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>u(/^[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),E(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),E(e)),dec:(e,t)=>function(e,t){let i=R(e,t);const n=2147483648&i.hi;n&&(i=I(i.lo,i.hi));const s=P(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>P(e,t)}}();var L,x,_;function N(e,t,i){if(t===i)return!0;if(e==L.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 L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return t==i}return!1}function U(e,t){switch(e){case L.BOOL:return!1;case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return 0==t?D.zero:"0";case L.DOUBLE:case L.FLOAT:return 0;case L.BYTES:return new Uint8Array(0);case L.STRING:return"";default:return 0}}function j(e,t){switch(e){case L.BOOL:return!1===t;case L.STRING:return""===t;case L.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!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"}(L||(L={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(x||(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"}(_||(_={}));class F{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(p(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return h(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){m(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){p(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){h(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return h(e),O(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=D.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=D.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=D.enc(e);return S(t.lo,t.hi,this.buf),this}sint64(e){let t=D.enc(e),i=t.hi>>31;return S(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=D.uEnc(e);return S(t.lo,t.hi,this.buf),this}}class B{constructor(e,t){this.varint64=C,this.uint32=A,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case _.Varint:for(;128&this.buf[this.pos++];);break;case _.Bit64:this.pos+=4;case _.Bit32:this.pos+=4;break;case _.LengthDelimited:let i=this.uint32();this.pos+=i;break;case _.StartGroup:for(;;){const[e,i]=this.tag();if(i===_.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return D.dec(...this.varint64())}uint64(){return D.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,D.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 D.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return D.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 V(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return U(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),K=[];for(let e=0;e<q.length;e++)K[q[e].charCodeAt(0)]=e;K["-".charCodeAt(0)]=q.indexOf("+"),K["_".charCodeAt(0)]=q.indexOf("/");const H={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,o=0,r=0;for(let t=0;t<e.length;t++){if(i=K[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":o=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(o){case 0:r=i,o=1;break;case 1:n[s++]=r<<2|(48&i)>>4,r=i,o=2;break;case 2:n[s++]=(15&r)<<4|(60&i)>>2,r=i,o=3;break;case 3:n[s++]=(3&r)<<6|i,o=0}}if(1==o)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let o=0;o<e.length;o++)switch(t=e[o],n){case 0:i+=q[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=q[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=q[s|t>>6],i+=q[63&t],n=0}return n&&(i+=q[s],i+="=",1==n&&(i+="=")),i}};function G(e,t,i){J(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[o,r]=V(t);for(const e of s)t.runtime.bin.readField(o,n.readerFactory(e.data),t.field,e.wireType,n);return r()}function z(e,t,i,n){J(t,e);const s=t.runtime.bin.makeReadOptions(n),o=t.runtime.bin.makeWriteOptions(n);if(W(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const r=o.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,r,o);const c=s.readerFactory(r.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function W(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function J(e,t){u(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function Q(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!j(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function $(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?U(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function X(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(T.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function Y(e,t){return X(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}L.DOUBLE,L.FLOAT,L.INT64,L.UINT64,L.INT32,L.UINT32,L.BOOL,L.STRING,L.BYTES;const Z={ignoreUnknownFields:!1},ee={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function te(e){return e?Object.assign(Object.assign({},Z),e):Z}function ie(e){return e?Object.assign(Object.assign({},ee),e):ee}const ne=Symbol(),se=Symbol();function oe(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 re(e,t,i,n,s){let o=i.localName;if(i.repeated){if(u("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const r=e[o];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(e)));switch(i.kind){case"message":r.push(i.T.fromJson(e,n));break;case"enum":const t=de(i.T,e,n.ignoreUnknownFields,!0);t!==se&&r.push(t);break;case"scalar":try{r.push(ce(i.T,e,i.L,!0))}catch(t){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),new Error(n)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const r=e[o];for(const[e,o]of Object.entries(t)){if(null===o)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let a;try{a=ae(i.K,e)}catch(e){let n="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}switch(i.V.kind){case"message":r[a]=i.V.T.fromJson(o,n);break;case"enum":const e=de(i.V.T,o,n.ignoreUnknownFields,!0);e!==se&&(r[a]=e);break;case"scalar":try{r[a]=ce(i.V.T,o,x.BIGINT,!0)}catch(e){let n="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:o},o="value"),i.kind){case"message":const r=i.T;if(null===t&&"google.protobuf.Value"!=r.typeName)return;let a=e[o];X(a)?a.fromJson(t,n):(e[o]=a=r.fromJson(t,n),r.fieldWrapper&&!i.oneof&&(e[o]=r.fieldWrapper.unwrapField(a)));break;case"enum":const c=de(i.T,t,n.ignoreUnknownFields,!1);switch(c){case ne:$(i,e);break;case se:break;default:e[o]=c}break;case"scalar":try{const n=ce(i.T,t,i.L,!1);if(n===ne)$(i,e);else e[o]=n}catch(e){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}}}function ae(e,t){if(e===L.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return ce(e,t,x.BIGINT,!0).toString()}function ce(e,t,i,n){if(null===t)return n?U(e,i):ne;switch(e){case L.DOUBLE:case L.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==L.FLOAT&&m(n),n;case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==L.UINT32||e==L.FIXED32?p(s):h(s),s;case L.INT64:case L.SFIXED64:case L.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=D.parse(t);return i?o.toString():o;case L.FIXED64:case L.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const r=D.uParse(t);return i?r.toString():r;case L.BOOL:if("boolean"!=typeof t)break;return t;case L.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case L.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return H.dec(t)}throw new Error}function de(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:ne;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return se}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(oe(t)))}function le(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function ue(e,t,i){if("map"==e.kind){u("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,i]of s)n[t.toString()]=pe(e.V.T,i);break;case"message":for(const[e,t]of s)n[e.toString()]=t.toJson(i);break;case"enum":const t=e.V.T;for(const[e,o]of s)n[e.toString()]=he(t,o,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){u(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(pe(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(he(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return pe(e.T,t);case"enum":return he(e.T,t,i.enumAsInteger);case"message":return Y(e.T,t).toJson(i)}}function he(e,t,i){var n;if(u("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function pe(e,t){switch(e){case L.INT32:case L.SFIXED32:case L.SINT32:case L.FIXED32:case L.UINT32:return u("number"==typeof t),t;case L.FLOAT:case L.DOUBLE:return u("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case L.STRING:return u("string"==typeof t),t;case L.BOOL:return u("boolean"==typeof t),t;case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return u("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case L.BYTES:return u(t instanceof Uint8Array),H.enc(t)}}const me=Symbol("@bufbuild/protobuf/unknown-fields"),ge={readUnknownFields:!0,readerFactory:e=>new B(e)},fe={writeUnknownFields:!0,writerFactory:()=>new F};function ve(e){return e?Object.assign(Object.assign({},ge),e):ge}function be(e){return e?Object.assign(Object.assign({},fe),e):fe}function ke(e,t,i,n,s){let{repeated:o,localName:r}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=r&&delete e.value,e.case=r,r="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?L.INT32:i.T;let c=Ce;if("scalar"==i.kind&&i.L>0&&(c=Te),o){let i=e[r];if(n==_.LengthDelimited&&a!=L.STRING&&a!=L.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[r]=c(t,a);break;case"message":const d=i.T;o?e[r].push(ye(t,new d,s,i)):X(e[r])?ye(t,e[r],s,i):(e[r]=ye(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[r]=d.fieldWrapper.unwrapField(e[r])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let o,r;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:o=Ce(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=Ce(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=ye(t,new e.V.T,i,void 0)}}}void 0===o&&(o=U(e.K,x.BIGINT));"string"!=typeof o&&"number"!=typeof o&&(o=o.toString());if(void 0===r)switch(e.V.kind){case"scalar":r=U(e.V.T,x.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[o,r]}(i,t,s);e[r][l]=u}}function ye(e,t,i,n){const s=t.getType().runtime.bin,o=null==n?void 0:n.delimited;return s.readMessage(t,e,o?n.no:e.uint32(),i,o),t}function Te(e,t){const i=Ce(e,t);return"bigint"==typeof i?i.toString():i}function Ce(e,t){switch(t){case L.STRING:return e.string();case L.BOOL:return e.bool();case L.DOUBLE:return e.double();case L.FLOAT:return e.float();case L.INT32:return e.int32();case L.INT64:return e.int64();case L.UINT64:return e.uint64();case L.FIXED64:return e.fixed64();case L.BYTES:return e.bytes();case L.FIXED32:return e.fixed32();case L.SFIXED32:return e.sfixed32();case L.SFIXED64:return e.sfixed64();case L.SINT64:return e.sint64();case L.UINT32:return e.uint32();case L.SINT32:return e.sint32()}}function Se(e,t,i,n){u(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?L.INT32:e.T;if(s)if(u(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,_.LengthDelimited).fork();let[,s]=Re(t);for(let t=0;t<n.length;t++)e[s](n[t]);e.join()}(i,o,e.no,t);else for(const n of t)Pe(i,o,e.no,n);else Pe(i,o,e.no,t);break;case"message":if(s){u(Array.isArray(t));for(const s of t)Ee(i,n,e,s)}else Ee(i,n,e,t);break;case"map":u("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))we(i,n,e,s,o)}}function we(e,t,i,n,s){e.tag(i.no,_.LengthDelimited),e.fork();let o=n;switch(i.K){case L.INT32:case L.FIXED32:case L.UINT32:case L.SFIXED32:case L.SINT32:o=Number.parseInt(n);break;case L.BOOL:u("true"==n||"false"==n),o="true"==n}switch(Pe(e,i.K,1,o),i.V.kind){case"scalar":Pe(e,i.V.T,2,s);break;case"enum":Pe(e,L.INT32,2,s);break;case"message":u(void 0!==s),e.tag(2,_.LengthDelimited).bytes(s.toBinary(t))}e.join()}function Ee(e,t,i,n){const s=Y(i.T,n);i.delimited?e.tag(i.no,_.StartGroup).raw(s.toBinary(t)).tag(i.no,_.EndGroup):e.tag(i.no,_.LengthDelimited).bytes(s.toBinary(t))}function Pe(e,t,i,n){u(void 0!==n);let[s,o]=Re(t);e.tag(i,s)[o](n)}function Re(e){let t=_.Varint;switch(e){case L.BYTES:case L.STRING:t=_.LengthDelimited;break;case L.DOUBLE:case L.FIXED64:case L.SFIXED64:t=_.Bit64;break;case L.FIXED32:case L.SFIXED32:case L.FLOAT:t=_.Bit32}return[t,L[e].toLowerCase()]}function Ie(e){if(void 0===e)return e;if(X(e))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 Oe{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 Ae(e,t){const i=Le(e);return t?i:je(Ue(i))}const De=Le;function Le(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const xe=new Set(["constructor","toString","toJSON","valueOf"]),_e=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ne=e=>"".concat(e,"$"),Ue=e=>_e.has(e)?Ne(e):e,je=e=>xe.has(e)?Ne(e):e;class Fe{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Ae(e,!1)}addField(e){u(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 Be=(Ve=e=>new Oe(e,(e=>function(e){var t,i,n,s,o,r;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Ae(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:De(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:x.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(o=d.req)&&void 0!==o&&o,e.opt=null!==(r=d.opt)&&void 0!==r&&r,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=L.BYTES&&d.T!=L.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Fe(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e))),qe=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]=U(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:te,makeWriteOptions:ie,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(oe(t)));n=null!=n?n:new e;const s=new Map,o=i.typeRegistry;for(const[r,a]of Object.entries(t)){const t=e.fields.findJsonName(r);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(r,'"'));s.set(t.oneof,r)}re(n,a,t,i,e)}else{let t=!1;if((null==o?void 0:o.findExtension)&&r.startsWith("[")&&r.endsWith("]")){const s=o.findExtension(r.substring(1,r.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,o]=V(s);re(e,a,s.field,i,s),z(n,s,o(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(r,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!Q(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!le(s))continue}const i=ue(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const o=t.typeRegistry;if(null==o?void 0:o.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const r=o.findExtensionFor(i.typeName,s.no);if(r&&W(e,r)){const i=G(e,r,t),s=ue(r.field,i,t);void 0!==s&&(n[r.field.jsonName]=s)}}}catch(e){const t=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),n=e instanceof Error?e.message:String(e);throw new Error(t+(n.length>0?": ".concat(n):""))}return n},readScalar:(e,t,i)=>ce(e,t,null!=i?i:x.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||j(e,t)?pe(e,t):void 0},debug:oe},bin:{makeReadOptions:ve,makeWriteOptions:be,listUnknownFields(e){var t;return null!==(t=e[me])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[me]},writeUnknownFields(e,t){const i=e[me];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[me])||(s[me]=[]),s[me].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const o=e.getType(),r=s?t.len:t.pos+i;let a,c;for(;t.pos<r&&([a,c]=t.tag(),!0!==s||c!=_.EndGroup);){const i=o.fields.find(a);if(i)ke(e,t,i,c,n);else{const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i)}}if(s&&(c!=_.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:ke,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(Q(s,e))Se(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Se(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:v,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,o=e;if(null!=o[i])switch(n.kind){case"oneof":const e=o[i].case;if(void 0===e)continue;const t=n.findField(e);let r=o[i].value;t&&"message"==t.kind&&!X(r,t.T)?r=new t.T(r):t&&"scalar"===t.kind&&t.T===L.BYTES&&(r=Me(r)),s[i]={case:e,value:r};break;case"scalar":case"enum":let a=o[i];n.T===L.BYTES&&(a=n.repeated?a.map(Me):Me(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===L.BYTES)for(const[e,t]of Object.entries(o[i]))s[i][e]=Me(t);else Object.assign(s[i],o[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(o[i])){let n=o[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=o[i].map((e=>X(e,c)?e:new c(e)));else{const e=o[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=Me(e):s[i]=e:s[i]=X(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>N(e.T,t,s[i])));case"enum":return n.every(((e,t)=>N(L.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=n,i=s;return e.T.fieldWrapper&&(void 0===t||X(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===i||X(i)||(i=e.T.fieldWrapper.wrapField(i))),e.T.equals(t,i);case"enum":return N(L.INT32,n,s);case"scalar":return N(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const o=e.findField(n.case);if(void 0===o)return!0;switch(o.kind){case"message":return o.T.equals(n.value,s.value);case"enum":return N(L.INT32,n.value,s.value);case"scalar":return N(o.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const r=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return r.every((e=>t.equals(n[e],s[e])));case"enum":return r.every((e=>N(L.INT32,n[e],s[e])));case"scalar":const i=e.V.T;return r.every((e=>N(i,n[e],s[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 s;if(i.repeated)s=t.map(Ie);else if("map"==i.kind){s=n[i.localName];for(const[e,i]of Object.entries(t))s[e]=Ie(i)}else s="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:Ie(t.value)}:{case:void 0}:Ie(t);n[i.localName]=s}for(const i of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,i.no,i.wireType,i.data);return i}}),{newFieldList:Ve,initFields:qe}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const o=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),r={[o]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[o];return Object.setPrototypeOf(r.prototype,new T),Object.assign(r,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new r).fromBinary(e,t),fromJson:(e,t)=>(new r).fromJson(e,t),fromJsonString:(e,t)=>(new r).fromJsonString(e,t),equals:(t,i)=>e.util.equals(r,t,i)}),r}(this,e,t,i)},makeEnum:k,makeEnumType:b,getEnumType:f,makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Ve,qe;class Ke extends T{constructor(e){super(),this.seconds=D.zero,this.nanos=0,Be.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Be.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=D.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:D.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 Be.util.equals(Ke,e,t)}}Ke.runtime=Be,Ke.typeName="google.protobuf.Timestamp",Ke.fields=Be.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const He=Be.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ge,repeated:!0},{no:5,name:"events",kind:"message",T:We,repeated:!0}])),Ge=Be.makeMessageType("livekit.TimeSeriesMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:ze,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),ze=Be.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"value",kind:"scalar",T:2}])),We=Be.makeMessageType("livekit.EventMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Ke},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ke,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Je=Be.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Qe=Be.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),$e=Be.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Xe=Be.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Ye=Be.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ze=Be.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),et=Be.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),tt=Be.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),it=Be.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),nt=Be.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),st=Be.makeMessageType("livekit.Room",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:ot,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:Nt}])),ot=Be.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),rt=Be.makeMessageType("livekit.ParticipantPermission",(()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:Be.getEnumType($e),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}])),at=Be.makeMessageType("livekit.ParticipantInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Be.getEnumType(ct)},{no:4,name:"tracks",kind:"message",T:pt,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:rt},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Be.getEnumType(dt)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Be.getEnumType(et)},{no:18,name:"kind_details",kind:"enum",T:Be.getEnumType(lt),repeated:!0}])),ct=Be.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),dt=Be.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),lt=Be.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),ut=Be.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ht=Be.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:mt,repeated:!0}])),pt=Be.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Be.getEnumType(Qe)},{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:Be.getEnumType($e)},{no:10,name:"layers",kind:"message",T:mt,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:ht,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:Be.getEnumType(ut)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Nt},{no:19,name:"audio_features",kind:"enum",T:Be.getEnumType(nt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Be.getEnumType(Je)}])),mt=Be.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Be.getEnumType(Xe)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}])),gt=Be.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Be.getEnumType(ft)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:kt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:vt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:yt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Tt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:He,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:St,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:wt,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Et,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Pt,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Bt,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Vt,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:qt,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),ft=Be.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),vt=Be.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:bt,repeated:!0}])),bt=Be.makeMessageType("livekit.SpeakerInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}])),kt=Be.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}])),yt=Be.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Tt=Be.makeMessageType("livekit.Transcription",(()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Ct,repeated:!0}])),Ct=Be.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),St=Be.makeMessageType("livekit.ChatMessage",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}])),wt=Be.makeMessageType("livekit.RpcRequest",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}])),Et=Be.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Pt=Be.makeMessageType("livekit.RpcResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Rt,oneof:"value"}])),Rt=Be.makeMessageType("livekit.RpcError",(()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}])),It=Be.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Mt=Be.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Be.getEnumType(Ot)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}])),Ot=Be.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),At=Be.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Be.getEnumType(Dt)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}])),Dt=Be.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),Lt=Be.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:xt},{no:2,name:"screen",kind:"message",T:xt},{no:3,name:"resume_connection",kind:"enum",T:Be.getEnumType(Ze)},{no:4,name:"disabled_codecs",kind:"message",T:_t},{no:5,name:"force_relay",kind:"enum",T:Be.getEnumType(Ze)}])),xt=Be.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Be.getEnumType(Ze)}])),_t=Be.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ot,repeated:!0},{no:2,name:"publish",kind:"message",T:ot,repeated:!0}])),Nt=Be.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Ut=Be.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),jt=Be.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Be.getEnumType(Ut)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}]),{localName:"DataStream_TextHeader"}),Ft=Be.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Bt=Be.makeMessageType("livekit.DataStream.Header",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:Be.getEnumType(ut)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:jt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Ft,oneof:"content_header"}]),{localName:"DataStream_Header"}),Vt=Be.makeMessageType("livekit.DataStream.Chunk",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}]),{localName:"DataStream_Chunk"}),qt=Be.makeMessageType("livekit.DataStream.Trailer",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]),{localName:"DataStream_Trailer"}),Kt=Be.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Ht=Be.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Gt=Be.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),zt=Be.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:ii,oneof:"message"},{no:2,name:"answer",kind:"message",T:ii,oneof:"message"},{no:3,name:"trickle",kind:"message",T:$t,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Qt,oneof:"message"},{no:5,name:"mute",kind:"message",T:Xt,oneof:"message"},{no:6,name:"subscription",kind:"message",T:si,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:oi,oneof:"message"},{no:8,name:"leave",kind:"message",T:ci,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:li,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Si,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Pi,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Mi,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:ui,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Oi,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ri,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ai,oneof:"message"}])),Wt=Be.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Yt,oneof:"message"},{no:2,name:"answer",kind:"message",T:ii,oneof:"message"},{no:3,name:"offer",kind:"message",T:ii,oneof:"message"},{no:4,name:"trickle",kind:"message",T:$t,oneof:"message"},{no:5,name:"update",kind:"message",T:ni,oneof:"message"},{no:6,name:"track_published",kind:"message",T:ei,oneof:"message"},{no:8,name:"leave",kind:"message",T:ci,oneof:"message"},{no:9,name:"mute",kind:"message",T:Xt,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:pi,oneof:"message"},{no:11,name:"room_update",kind:"message",T:mi,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:fi,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:bi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Ti,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:wi,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ti,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Zt,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Ai,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:xi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:_i,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Ui,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Ei,oneof:"message"}])),Jt=Be.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),Qt=Be.makeMessageType("livekit.AddTrackRequest",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:Be.getEnumType(Qe)},{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:Be.getEnumType($e)},{no:9,name:"layers",kind:"message",T:mt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Jt,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:Be.getEnumType(ut)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Be.getEnumType(Je)},{no:17,name:"audio_features",kind:"enum",T:Be.getEnumType(nt),repeated:!0}])),$t=Be.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Be.getEnumType(Kt)},{no:3,name:"final",kind:"scalar",T:8}])),Xt=Be.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Yt=Be.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:st},{no:2,name:"participant",kind:"message",T:at},{no:3,name:"other_participants",kind:"message",T:at,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:hi,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:Lt},{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:Mt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ot,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),Zt=Be.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:hi,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Lt},{no:3,name:"server_info",kind:"message",T:Mt},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),ei=Be.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:pt}])),ti=Be.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),ii=Be.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}])),ni=Be.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:at,repeated:!0}])),si=Be.makeMessageType("livekit.UpdateSubscription",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:It,repeated:!0}])),oi=Be.makeMessageType("livekit.UpdateTrackSettings",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:Be.getEnumType(Xe)},{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}])),ri=Be.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Be.getEnumType(nt),repeated:!0}])),ai=Be.makeMessageType("livekit.UpdateLocalVideoTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}])),ci=Be.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Be.getEnumType(et)},{no:3,name:"action",kind:"enum",T:Be.getEnumType(di)},{no:4,name:"regions",kind:"message",T:Di}])),di=Be.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),li=Be.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:mt,repeated:!0}])),ui=Be.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}])),hi=Be.makeMessageType("livekit.ICEServer",(()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}])),pi=Be.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:bt,repeated:!0}])),mi=Be.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:st}])),gi=Be.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Be.getEnumType(Ye)},{no:3,name:"score",kind:"scalar",T:2}])),fi=Be.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:gi,repeated:!0}])),vi=Be.makeMessageType("livekit.StreamStateInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Be.getEnumType(Ht)}])),bi=Be.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:vi,repeated:!0}])),ki=Be.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Be.getEnumType(Xe)},{no:2,name:"enabled",kind:"scalar",T:8}])),yi=Be.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ki,repeated:!0}])),Ti=Be.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ki,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:yi,repeated:!0}])),Ci=Be.makeMessageType("livekit.TrackPermission",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}])),Si=Be.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Ci,repeated:!0}])),wi=Be.makeMessageType("livekit.SubscriptionPermissionUpdate",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}])),Ei=Be.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:st},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:at},{no:4,name:"other_participants",kind:"message",T:at,repeated:!0}])),Pi=Be.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:ii},{no:2,name:"subscription",kind:"message",T:si},{no:3,name:"publish_tracks",kind:"message",T:ei,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ii,repeated:!0},{no:5,name:"offer",kind:"message",T:ii},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Ri,repeated:!0}])),Ri=Be.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Ii=Be.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:Be.getEnumType(Kt)}])),Mi=Be.makeMessageType("livekit.SimulateScenario",(()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:Be.getEnumType(Gt),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}])),Oi=Be.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Ai=Be.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Di=Be.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Li,repeated:!0}])),Li=Be.makeMessageType("livekit.RegionInfo",(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}])),xi=Be.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Be.getEnumType(it)}])),_i=Be.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Be.getEnumType(Ni)},{no:3,name:"message",kind:"scalar",T:9}])),Ni=Be.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Ui=Be.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));function ji(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Fi,Bi={exports:{}},Vi=Bi.exports;var qi,Ki,Hi=(Fi||(Fi=1,function(e){var t,i;t=Vi,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},o=null;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 a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var o=n[s];this[o]=s<i?e:this.methodFactory(o,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,o){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?r(console,n):void 0!==console.log?r(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var r,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:r},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(o!==u&&(r=m(o.getLevel())),c.call(u),o===u)for(var e in s)s[e].rebuild()},r=m(o?o.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(o=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,o.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=h),o},o.getLoggers=function(){return s},o.default=o,o},e.exports?e.exports=i():t.log=i()}(Bi)),Bi.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(qi||(qi={})),function(e){e.Default="livekit",e.Room="livekit-room",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(Ki||(Ki={}));let Gi=Hi.getLogger("livekit");function zi(e){const t=Hi.getLogger(e);return t.setDefaultLevel(Gi.getLevel()),t}Object.values(Ki).map((e=>Hi.getLogger(e))),Gi.setDefaultLevel(qi.info);const Wi=Hi.getLogger("lk-e2ee"),Ji=7e3,Qi=[0,300,1200,2700,4800,Ji,Ji,Ji,Ji,Ji];function $i(e,t,i,n){return new(i||(i=Promise))((function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}function Xi(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 Yi(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Xi(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,s){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var Zi,en={exports:{}};var tn=function(){if(Zi)return en.exports;Zi=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}en.exports=s,en.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,s,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,o,c,d;if(r(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),c=o[t]),void 0===c)c=o[t]=i,++e._eventsCount;else if("function"==typeof c?c=o[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(o){n.once&&e.removeEventListener(t,s),i(o)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,o=this._events;if(void 0!==o)s=s&&void 0===o.error;else if(!s)return!1;if(s){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return r(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,o,a;if(r(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,o=i.length-1;o>=0;o--)if(i[o]===t||i[o].listener===t){a=i[o].listener,s=o;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,o=Object.keys(i);for(n=0;n<o.length;++n)"removeListener"!==(s=o[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},en.exports}();let nn=!0,sn=!0;function on(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function rn(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const o=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,o),s.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.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,o.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 an(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(nn=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function cn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(sn=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function dn(){if("object"==typeof window){if(nn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function ln(e,t){sn&&console.warn(e+" is deprecated, please use "+t+" instead.")}function un(e){return"[object Object]"===Object.prototype.toString.call(e)}function hn(e){return un(e)?Object.keys(e).reduce((function(t,i){const n=un(e[i]),s=n?hn(e[i]):e[i],o=n&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[i]:s})}),{}):e}function pn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?pn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{pn(e,e.get(t),i)}))})))}function mn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&pn(e,i,s)}))})),s}const gn=dn;function fn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const r=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||r)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let r=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!r&&i.length&&t.includes("back")&&(r=i[i.length-1]),r&&(e.video.deviceId=o.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=n(e.video),gn("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return gn("chrome: "+JSON.stringify(e)),s(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function vn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function bn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else rn(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function kn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function yn(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=>mn(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}),rn(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>mn(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 Tn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Cn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Tn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const r=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),r.apply(this,arguments)):r.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:o(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 Sn(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 wn(e,t){rn(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var En=Object.freeze({__proto__:null,fixNegotiationNeeded:wn,shimAddTrackRemoveTrack:Cn,shimAddTrackRemoveTrackWithNative:Tn,shimGetSendersWithDtmf:kn,shimGetUserMedia:fn,shimMediaStream:vn,shimOnTrack:bn,shimPeerConnection:Sn,shimSenderReceiverGetStats:yn});function Pn(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){ln("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 Rn(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 In(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,o]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(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(s,o)}}function Mn(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 On(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}),rn(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function An(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){ln("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Dn(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ln(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 xn(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 _n(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 Nn(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 Un=Object.freeze({__proto__:null,shimAddTransceiver:Ln,shimCreateAnswer:Nn,shimCreateOffer:_n,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:xn,shimGetUserMedia:Pn,shimOnTrack:Rn,shimPeerConnection:In,shimRTCDataChannel:Dn,shimReceiverGetStats:On,shimRemoveStream:An,shimSenderGetStats:Mn});function jn(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function Fn(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 Bn(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,o=t.setRemoteDescription,r=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Vn(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(qn(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function qn(e){return e&&void 0!==e.video?Object.assign({},e,{video:hn(e.video)}):e}function Kn(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?(ln("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 Hn(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 Gn(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 zn(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Wn,Jn=Object.freeze({__proto__:null,shimAudioContext:zn,shimCallbacksAPI:Bn,shimConstraints:qn,shimCreateOfferLegacy:Gn,shimGetUserMedia:Vn,shimLocalStreamsAPI:jn,shimRTCIceServerUrls:Kn,shimRemoteStreamsAPI:Fn,shimTrackEventTransceiver:Hn}),Qn={exports:{}};var $n=(Wn||(Wn=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let 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],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let s=3;s<n.length;s++){const o=n[s],r=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(r){const n=t.parseRtpMap(r),s=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(n.parameters=s.length?t.parseFmtp(s[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=r.length>0&&r[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),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const r=t.matchPrefix(e,"a=sctpmap:");if(r.length>0){const e=r[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const o=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+o+" 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}(Qn)),Qn.exports),Xn=ji($n),Yn=a({__proto__:null,default:Xn},[$n]);function Zn(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=Xn.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,rn(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function es(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||rn(e,"icecandidate",(e=>{if(e.candidate){const t=Xn.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function ts(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=Xn.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Xn.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=Xn.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>s}),this._sctp=o}return i.apply(this,arguments)}}function is(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},rn(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function ns(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 ss(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)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 os(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 rs(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 as=Object.freeze({__proto__:null,removeExtmapAllowMixed:ss,shimAddIceCandidateNullOrEmpty:os,shimConnectionState:ns,shimMaxMessageSize:ts,shimParameterlessSetLocalDescription:rs,shimRTCIceCandidate:Zn,shimRTCIceCandidateRelayProtocol:es,shimSendThrowTypeError:is});!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=dn,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=parseInt(on(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(on(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=parseInt(on(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=on(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),s={browserDetails:n,commonShim:as,extractVersion:on,disableLog:an,disableWarnings:cn,sdp:Yn};switch(n.browser){case"chrome":if(!En||!Sn||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=En,os(e,n),rs(e),fn(e,n),vn(e),Sn(e,n),bn(e),Cn(e,n),kn(e),yn(e),wn(e,n),Zn(e),es(e),ns(e),ts(e,n),is(e),ss(e,n);break;case"firefox":if(!Un||!In||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Un,os(e,n),rs(e),Pn(e,n),In(e,n),Rn(e),An(e),Mn(e),On(e),Dn(e),Ln(e),xn(e),_n(e),Nn(e),Zn(e),ns(e),ts(e,n),is(e);break;case"safari":if(!Jn||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=Jn,os(e,n),rs(e),Kn(e),Gn(e),Bn(e),jn(e),Fn(e),Hn(e),Vn(e),zn(e),Zn(e),es(e),ts(e,n),is(e),ss(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const cs="lk_e2ee";var ds,ls,us,hs,ps,ms,gs,fs,vs,bs,ks;function ys(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||Ts()}function Ts(){return void 0!==window.RTCRtpScriptTransform}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(ds||(ds={})),function(e){e.KeyRatcheted="keyRatcheted"}(ls||(ls={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(us||(us={})),function(e){e.Error="cryptorError"}(hs||(hs={}));tn.EventEmitter;class Cs extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"}(ps||(ps={}));class Ss extends Cs{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=ps[t]}}class ws extends Cs{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Es extends Cs{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Ps extends Cs{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Rs extends Cs{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Is extends Cs{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Ms extends Cs{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Os extends Cs{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:Ni[t]}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(ms||(ms={})),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}}(ms||(ms={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(gs||(gs={})),function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"}(fs||(fs={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(vs||(vs={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"}(bs||(bs={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(ks||(ks={}));const As=/version\/(\d+(\.?_?\d+)+)/i;let Ds;function Ls(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const i=navigator.userAgent.toLowerCase();if(void 0===Ds||t){const e=xs.find((e=>{let{test:t}=e;return t.test(i)}));Ds=null==e?void 0:e.describe(i)}return Ds}const xs=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:_s(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Ns(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:_s(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Ns(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:_s(As,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Ns(e)})}];function _s(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function Ns(e){return e.includes("mac os")?_s(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class Us{}Us.setTimeout=function(){return setTimeout(...arguments)},Us.setInterval=function(){return setInterval(...arguments)},Us.clearTimeout=function(){return clearTimeout(...arguments)},Us.clearInterval=function(){return clearInterval(...arguments)};const js=[];var Fs;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(Fs||(Fs={}));class Bs extends tn.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=Bs.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Gi,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=zi(null!==(n=i.loggerName)&&void 0!==n?n:Ki.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Bs.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Jo(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Bs.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===Bs.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(js.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&js.splice(js.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Vs(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?ks.AudioPlaybackStarted:ks.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?ks.AudioPlaybackFailed:ks.VideoPlaybackFailed,t):"AbortError"===t.name?Gi.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Gi.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(ks.ElementAttached,e),e}detach(e){try{if(e){qs(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(ks.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{qs(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(ks.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=zi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),js.forEach((e=>{e.parentElement||(t=!1)})),t&&js.push(e)}}handleAppVisibilityChanged(){return $i(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Bs.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){co()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){co()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Vs(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)),oo()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(oo()||so())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function qs(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t,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 Qe.AUDIO;case t.Video:return Qe.VIDEO;default:return Qe.DATA}},e.kindFromProto=function(e){switch(e){case Qe.AUDIO:return t.Audio;case Qe.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return $e.CAMERA;case i.Microphone:return $e.MICROPHONE;case i.ScreenShare:return $e.SCREEN_SHARE;case i.ScreenShareAudio:return $e.SCREEN_SHARE_AUDIO;default:return $e.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case $e.CAMERA:return i.Camera;case $e.MICROPHONE:return i.Microphone;case $e.SCREEN_SHARE:return i.ScreenShare;case $e.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Ht.ACTIVE:return n.Active;case Ht.PAUSED:return n.Paused;default:return n.Unknown}}}(Bs||(Bs={}));class Ks{constructor(e,t,i,n,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Hs=["vp8","h264"],Gs=["vp8","h264","vp9","av1","h265"];function zs(e){return!!Hs.find((t=>t===e))}var Ws,Js;!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(Ws||(Ws={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(Js||(Js={}));const Qs={h90:new Ks(160,90,9e4,20),h180:new Ks(320,180,16e4,20),h216:new Ks(384,216,18e4,20),h360:new Ks(640,360,45e4,20),h540:new Ks(960,540,8e5,25),h720:new Ks(1280,720,17e5,30),h1080:new Ks(1920,1080,3e6,30),h1440:new Ks(2560,1440,5e6,30),h2160:new Ks(3840,2160,8e6,30)},$s={h120:new Ks(160,120,7e4,20),h180:new Ks(240,180,125e3,20),h240:new Ks(320,240,14e4,20),h360:new Ks(480,360,33e4,20),h480:new Ks(640,480,5e5,20),h540:new Ks(720,540,6e5,25),h720:new Ks(960,720,13e5,30),h1080:new Ks(1440,1080,23e5,30),h1440:new Ks(1920,1440,38e5,30)},Xs={h360fps3:new Ks(640,360,2e5,3,"medium"),h360fps15:new Ks(640,360,4e5,15,"medium"),h720fps5:new Ks(1280,720,8e5,5,"medium"),h720fps15:new Ks(1280,720,15e5,15,"medium"),h720fps30:new Ks(1280,720,2e6,30,"medium"),h1080fps15:new Ks(1920,1080,25e5,15,"medium"),h1080fps30:new Ks(1920,1080,5e6,30,"medium"),original:new Ks(0,0,7e6,30,"medium")},Ys="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Zs(e){return $i(this,void 0,void 0,(function*(){return new Promise((t=>Us.setTimeout(t,e)))}))}function eo(){return"addTransceiver"in RTCPeerConnection.prototype}function to(){return"addTrack"in RTCPeerConnection.prototype}function io(e){return"av1"===e||"vp9"===e}function no(e){return!(!document||ro())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function so(){var e;return"Firefox"===(null===(e=Ls())||void 0===e?void 0:e.name)}function oo(){var e;return"Safari"===(null===(e=Ls())||void 0===e?void 0:e.name)}function ro(){const e=Ls();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function ao(){var e,t;return!!co()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function co(){return"undefined"!=typeof document}function lo(){return"ReactNative"==navigator.product}function uo(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function ho(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function po(){if(!lo())return;let e=ho();return e?e.platform:void 0}function mo(){if(co())return window.devicePixelRatio;if(lo()){let e=ho();if(e)return e.devicePixelRatio}return 1}function go(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let e=0;e<s;++e){const t=parseInt(i[e],10),o=parseInt(n[e],10);if(t>o)return 1;if(t<o)return-1;if(e===s-1&&t===o)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function fo(e){for(const t of e)t.target.handleResize(t)}function vo(e){for(const t of e)t.target.handleVisibilityChanged(t)}let bo=null;const ko=()=>(bo||(bo=new ResizeObserver(fo)),bo);let yo=null;const To=()=>(yo||(yo=new IntersectionObserver(vo,{root:null,rootMargin:"0px"})),yo);function Co(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const o=s.getContext("2d");null==o||o.fillRect(0,0,s.width,s.height),n&&o&&(o.beginPath(),o.arc(e/2,t/2,50,0,2*Math.PI,!0),o.closePath(),o.fillStyle="grey",o.fill());const r=s.captureStream(),[a]=r.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let So;function wo(){if(!So){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(),[So]=n.stream.getAudioTracks(),!So)throw Error("Could not get empty media stream audio track");So.enabled=!1}return So.clone()}class Eo{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,i)=>$i(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)}))}}function Po(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Ro(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Io(e){switch(e.reason){case ps.LeaveRequest:return e.context;case ps.Cancelled:return et.CLIENT_INITIATED;case ps.NotAllowed:return et.USER_REJECTED;case ps.ServerUnreachable:return et.JOIN_FAILURE;default:return et.UNKNOWN_REASON}}function Mo(e){return void 0!==e?Number(e):void 0}function Oo(e){return void 0!==e?BigInt(e):void 0}function Ao(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Do(e){return!!e&&e.kind==Bs.Kind.Audio}function Lo(e){return!!e&&e.kind==Bs.Kind.Video}function xo(e){return Ao(e)&&Lo(e)}function _o(e){return Ao(e)&&Do(e)}function No(e){return!!e&&!e.isLocal}function Uo(e){return!!e&&!e.isLocal}function jo(e){return No(e)&&Lo(e)}function Fo(e,t,i){var n,s,o,r;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=Qo(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(Bo(h.audio,t),null!==(n=(o=h.audio).deviceId)&&void 0!==n||(o.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(Bo(h.video,i),null!==(s=(r=h.video).deviceId)&&void 0!==s||(r.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function Bo(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function Vo(e){var t,i,n,s;const o={};if(e.video)if("object"==typeof e.video){const i={},s=i,r=e.video;Object.keys(r).forEach((e=>{if("resolution"===e)Bo(s,r.resolution);else s[e]=r[e]})),o.video=i,null!==(t=(n=o.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else o.video=!!e.video&&{deviceId:{ideal:"default"}};else o.video=!1;return e.audio?"object"==typeof e.audio?(o.audio=e.audio,null!==(i=(s=o.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):o.audio={deviceId:{ideal:"default"}}:o.audio=!1,o}function qo(e){return $i(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Ko();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield Zs(t),n.getByteTimeDomainData(o);const r=o.some((e=>128!==e&&0!==e));return i.close(),!r}return!1}()}))}function Ko(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>$i(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}));window.document.body.addEventListener("click",e)}return i}}function Ho(e){return"audioinput"===e?Bs.Source.Microphone:"videoinput"===e?Bs.Source.Camera:Bs.Source.Unknown}function Go(e){return e===Bs.Source.Microphone?"audioinput":e===Bs.Source.Camera?"videoinput":void 0}function zo(e){return e.split("/")[1].toLowerCase()}function Wo(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new ei({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function Jo(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?Jo(e.track):{})}}function Qo(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function $o(e,t){return e.width*e.height<t.width*t.height}class Xo extends tn.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":Gi.error(s.error.message),this.emit(us.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(us.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(us.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(ds.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex)}},this.onWorkerError=e=>{Gi.error("e2ee worker encountered an error:",{error:e.error}),this.emit(us.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!ys())throw new ws("tried to setup end-to-end encryption on an unsupported browser");if(Gi.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Wi.getLevel()}};this.worker&&(Gi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Gi.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Gi.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(bs.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on(fs.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ut.NONE,t.identity))),e.on(fs.ConnectionStateChanged,(t=>{t===_a.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==ut.NONE,e.identity)}))}))})).on(fs.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(fs.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(fs.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach((e=>{this.postKey(e)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),e.localParticipant.on(vs.LocalSenderCreated,((e,t)=>$i(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.on(ds.SetKey,(e=>this.postKey(e))).on(ds.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(o)}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?zo(i.mimeType):void 0)}}setupE2EESender(e,t){Ao(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Gi.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return $i(this,void 0,void 0,(function*(){if(this.worker){if(Ts()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(cs in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,o=e.readableStream;if(!s||!o){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,o=t.readable}const r={kind:"decode",data:{readableStream:o,writableStream:s,trackId:t,codec:n,participantIdentity:i,isReuse:cs in e}};this.worker.postMessage(r,[o,s])}e[cs]=!0}}))}handleSender(e,t,i){var n;if(!(cs 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(Ts()){Gi.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{Gi.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(s,[n.readable,n.writable])}e[cs]=!0}}}const Yo="default";class Zo{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Zo),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=Zo.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Gi.debug("awaiting getUserMedia promise");try{e?yield Zo.userMediaPromiseMap.get(e):yield Promise.all(Zo.userMediaPromiseMap.values())}catch(e){Gi.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!oo()||!t.hasDeviceInUse(e))){if(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return $i(this,void 0,void 0,(function*(){if(t!==Yo)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===Yo));if(!s)return void Gi.warn("could not reliably determine default device");const o=n.find((e=>e.deviceId!==Yo&&e.groupId===(null!=i?i:s.groupId)));if(o)return null==o?void 0:o.deviceId;Gi.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Zo.userMediaPromiseMap.has(e):Zo.userMediaPromiseMap.size>0}}var er;Zo.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Zo.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(er||(er={}));class tr{constructor(){this.pendingTasks=new Map,this.taskMutex=new l,this.nextTaskIndex=0}run(e){return $i(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:er.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=er.RUNNING,yield e()}finally{t.status=er.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return $i(this,void 0,void 0,(function*(){return this.run((()=>$i(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function ir(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const nr=["syncState","trickle","offer","answer","simulate","leave"];var sr;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(sr||(sr={}));class or{get currentState(){return this.state}get isDisconnected(){return this.state===sr.DISCONNECTING||this.state===sr.DISCONNECTED}get isEstablishingConnection(){return this.state===sr.CONNECTING||this.state===sr.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=sr.DISCONNECTED,this.log=Gi,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=zi(null!==(i=t.loggerName)&&void 0!==i?i:Ki.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new tr,this.queuedRequests=[],this.closingLock=new l,this.connectionLock=new l,this.state=sr.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return $i(this,void 0,void 0,(function*(){this.state=sr.CONNECTING,this.options=i;return yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return $i(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=sr.RECONNECTING,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;const s=function(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",lo()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return s}(t,function(){var e;const t=new At({sdk:Dt.JS,protocol:16,version:"2.15.4"});return lo()&&(t.os=null!==(e=po())&&void 0!==e?e:""),t}(),i),o=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{i.searchParams.set(t,e)})),ir(i,"rtc")}(e,s),r=ir(new URL(Ro(o)),"validate");return new Promise(((e,t)=>$i(this,void 0,void 0,(function*(){const s=yield this.connectionLock.lock();try{const s=()=>$i(this,void 0,void 0,(function*(){this.close(),clearTimeout(a),t(new Ss("room connection has been cancelled (signal)",ps.Cancelled))})),a=setTimeout((()=>{this.close(),t(new Ss("room connection has timed out (signal)",ps.ServerUnreachable))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&s(),null==n||n.addEventListener("abort",s);const c=new URL(o);c.searchParams.has("access_token")&&c.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(c),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(a)},this.ws.onerror=e=>$i(this,void 0,void 0,(function*(){if(this.state===sr.CONNECTED)this.handleWSError(e);else{this.state=sr.DISCONNECTED,clearTimeout(a);try{const i=yield fetch(r);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();t(new Ss(e,ps.NotAllowed,i.status))}else t(new Ss("Encountered unknown websocket error during connection: ".concat(e.toString()),ps.InternalError,i.status))}catch(e){t(new Ss(e instanceof Error?e.message:"server was not reachable",ps.ServerUnreachable))}}})),this.ws.onmessage=o=>$i(this,void 0,void 0,(function*(){var r,a,c;let d;if("string"==typeof o.data){const e=JSON.parse(o.data);d=Wt.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(o.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof o.data),this.logContext);d=Wt.fromBinary(new Uint8Array(o.data))}if(this.state!==sr.CONNECTED){let o=!1;if("join"===(null===(r=d.message)||void 0===r?void 0:r.case)?(this.state=sr.CONNECTED,null==n||n.removeEventListener("abort",s),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),e(d.message.value)):this.state===sr.RECONNECTING&&"leave"!==d.message.case?(this.state=sr.CONNECTED,null==n||n.removeEventListener("abort",s),this.startPingInterval(),"reconnect"===(null===(a=d.message)||void 0===a?void 0:a.case)?e(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),o=!0)):this.isEstablishingConnection&&"leave"===d.message.case?t(new Ss("Received leave request while trying to (re)connect",ps.LeaveRequest,void 0,d.message.value.reason)):i.reconnect||t(new Ss("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"),ps.InternalError)),!o)return}this.signalLatency&&(yield Zs(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new Ss("Websocket got closed during a (re)connection attempt",ps.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{s()}}))))}close(){return $i(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=sr.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,Zs(250)])),e.ws=void 0}}finally{t&&(e.state=sr.DISCONNECTED),i()}}()}))}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:ar(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:ar(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new $t({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Xt({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return $i(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new ui({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new li({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Si({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:D.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Oi({timestamp:D.parse(Date.now()),rtt:D.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new ri({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ci({reason:et.CLIENT_INITIATED,action:di.DISCONNECT})})}sendRequest(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=nr.indexOf(e.case)>=0;return Gi.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===sr.RECONNECTING)return void t.queuedRequests.push((()=>$i(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield Zs(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new zt({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=rr(n.value);this.onAnswer&&this.onAnswer(e,n.value.id)}else if("offer"===n.case){const e=rr(n.value);this.onOffer&&this.onOffer(e,n.value.id)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return $i(this,void 0,void 0,(function*(){if(this.state===sr.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Us.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&Us.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Us.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Us.clearInterval(this.pingInterval)}}function rr(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 ar(e,t){return new ii({sdp:e.sdp,type:e.type,id:t})}class cr{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class dr{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[n,s]of i.entries())t.push(e(s,n,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var lr,ur,hr,pr,mr,gr={},fr={},vr={exports:{}};function br(){if(lr)return vr.exports;lr=1;var e=vr.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"]}]};return Object.keys(e).forEach((function(t){e[t].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),vr.exports}function kr(){return ur||(ur=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(i[n[o]]=t(e[o+1]))}(n.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},n=br(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],r=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),r=o[o.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,r,s)}})),t.media=o,t};var o=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(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},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}}))}))}}(fr)),fr}function yr(){if(pr)return hr;pr=1;var e=br(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,(function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var r=t.names[o];t.name?s.push(n[t.name][r]):s.push(n[t.names[o]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return hr=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=i.outerOrder||s,a=i.innerOrder||o,c=[];return r.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))})),t.media.forEach((function(t){c.push(n("m",e.m[0],t)),a.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))}))})),c.join("\r\n")+"\r\n"},hr}var Tr=function(){if(mr)return gr;mr=1;var e=kr(),t=yr(),i=br();return gr.grammar=i,gr.write=t,gr.parse=e.parse,gr.parseParams=e.parseParams,gr.parseFmtpConfig=e.parseFmtpConfig,gr.parsePayloads=e.parsePayloads,gr.parseRemoteCandidates=e.parseRemoteCandidates,gr.parseImageAttributes=e.parseImageAttributes,gr.parseSimulcastStreamList=e.parseSimulcastStreamList,gr}();function Cr(e,t,i){var n,s,o;void 0===t&&(t=50),void 0===i&&(i={});var r=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[];function u(){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,s){var c=r&&void 0===o;if(void 0!==o&&clearTimeout(o),o=setTimeout((function(){if(o=void 0,d=Date.now(),!r){var n=e.apply(i,t);a&&a(n),l.forEach((function(e){return(0,e.resolve)(n)})),l=[]}}),u()),c){var h=e.apply(i,t);return a&&a(h),n(h)}l.push({resolve:n,reject:s})}))};return h.cancel=function(e){void 0!==o&&clearTimeout(o),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},h}const Sr="negotiationStarted",wr="negotiationComplete",Er="rtpVideoPayloadTypes";class Pr extends tn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Gi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Cr((e=>$i(this,void 0,void 0,(function*(){this.emit(Sr);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=zi(null!==(i=t.loggerName)&&void 0!==i?i:Ki.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new l}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return $i(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e,t){return $i(this,void 0,void 0,(function*(){var i;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Tr.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let o=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(o=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===o&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===o&&(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 t=Tr.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),n=Tr.write(t)}if(yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(wr),e.sdp)){Tr.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Er,e.rtp)}))}return!0}))}createAndSendOffer(e){return $i(this,void 0,void 0,(function*(){var t;const i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=this.latestOfferId+1;this.latestOfferId=i;const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=Tr.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(s.media.forEach((e=>{Ir(e),"audio"===e.type?Rr(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(io(t.codec)&&!oo()&&this.ensureVideoDDExtensionForSVC(e,s),"av1"!==t.codec)return!0;const n=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0}))})),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,Tr.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}}))}createAndSetAnswer(){return $i(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=Tr.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Ir(e),"audio"===e.type&&Rr(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Tr.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Rs("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Rs("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return $i(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return $i(this,void 0,void 0,(function*(){if(t){const n=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let n="unknown error";t instanceof Error?n=t.message:"string"==typeof t&&(n=t);const s={error:n,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Is(n)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Ys)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:Ys})}}}function Rr(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Ir(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}const Mr="vp8",Or={audioPreset:Js.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Xs.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Mr,backupCodec:!0,preConnectBuffer:!1},Ar={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Dr={deviceId:{ideal:"default"},resolution:Qs.h720.resolution},Lr={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Qi}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1},xr={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var _r;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(_r||(_r={}));class Nr{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=xr.peerConnectionTimeout,this.log=Gi,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=_r.CONNECTED:i.some((e=>"failed"===e))?this.state=_r.FAILED:i.some((e=>"connecting"===e))?this.state=_r.CONNECTING:i.every((e=>"closed"===e))?this.state=_r.CLOSED:i.some((e=>"closed"===e))?this.state=_r.CLOSING:i.every((e=>"new"===e))&&(this.state=_r.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(_r[t]," to ").concat(_r[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=zi(null!==(n=i.loggerName)&&void 0!==n?n:Ki.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Pr(e,i),this.subscriber=new Pr(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Kt.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Kt.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=_r.NEW,this.connectionLock=new l,this.remoteOfferLock=new l}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return $i(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return $i(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return $i(this,void 0,void 0,(function*(){t===Kt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return $i(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{if(!(yield this.subscriber.setRemoteDescription(e,t)))return;return yield this.subscriber.createAndSetAnswer()}finally{i()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return $i(this,void 0,void 0,(function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return $i(this,void 0,void 0,(function*(){return new Promise(((t,i)=>$i(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(Sr,(()=>{e.signal.aborted||this.publisher.once(wr,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Kt.PUBLISHER||e===Kt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return $i(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,s)=>$i(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Us.clearTimeout(o),s(new Ss("room connection has been cancelled",ps.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const o=Us.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new Ss("could not establish pc connection",ps.InternalError))}),n);for(;this.state!==_r.CONNECTED;)if(yield Zs(50),null==t?void 0:t.signal.aborted)return void s(new Ss("room connection has been cancelled",ps.Cancelled));Us.clearTimeout(o),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}class Ur extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Fr(t,Ur.MAX_MESSAGE_BYTES),this.data=i?Fr(i,Ur.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ur(e.code,e.message,e.data)}toProto(){return new Rt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Ur(Ur.ErrorCode[e],Ur.ErrorMessage[e],t)}}Ur.MAX_MESSAGE_BYTES=256,Ur.MAX_DATA_BYTES=15360,Ur.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Ur.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};function jr(e){return(new TextEncoder).encode(e).length}function Fr(e,t){if(jr(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const o=Math.floor((i+n+1)/2);s.encode(e.slice(0,o)).length<=t?i=o:n=o-1}return e.slice(0,i)}const Br=2e3;function Vr(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)}const qr="undefined"!=typeof MediaRecorder;const Kr=qr?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class Hr extends Kr{constructor(e,t){if(!qr)throw new Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([e.mediaStreamTrack]),t);const s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),null==n||n.close(),n=void 0},o=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>$i(this,void 0,void 0,(function*(){let i;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();i=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");i=t.data.byteArray}void 0!==n&&e.enqueue(i)})),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",o)}}class Gr extends Bs{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Cr((()=>$i(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>$i(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(ks.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new l,this.pauseUpstreamLock=new l,this.processorLock=new l,this.restartLock=new l,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Bs.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return $i(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{qs(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Vs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Vs(null!=n?n:e,t)})))}))}waitForDimensions(){return $i(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===Bs.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=Ls())||void 0===i?void 0:i.os)&&(yield Zs(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield Zs(50)}throw new Es("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return $i(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Po(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Po(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return $i(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===Bs.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===Bs.Kind.Audio?"audioinput":"videoinput";return t?Zo.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return $i(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return $i(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return $i(this,void 0,void 0,(function*(){if(!this.sender)throw new Es("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this}))}restart(e){return $i(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===Bs.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||{deviceId:t},this.attachedElements.forEach((e=>{qs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield o.applyConstraints(n),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o),this._constraints=e,this.emit(ks.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}}))}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ks.Muted:ks.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 $i(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ao()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return $i(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(ks.UpstreamPaused,this);const t=Ls();if("Safari"===(null==t?void 0:t.name)&&go(t.version,"12.0")<0)throw new ws("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}}))}resumeUpstream(){return $i(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(ks.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}}))}getRTCStatsReport(){return $i(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),o={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(o),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(Vs(t._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout((()=>{s.play().catch((e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))}))}),100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))})),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(qs(t._mediaStreamTrack,e),Vs(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(ks.TrackProcessorUpdate,t.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return $i(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(ks.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(qr)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new Hr(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout((()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()}),1e4)}else this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class zr extends Gr{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,Bs.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>$i(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 this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=Vr(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ks.AudioTrackFeatureUpdate,this,nt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ks.AudioTrackFeatureUpdate,this,nt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return $i(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Bs.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return $i(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Po(this._constraints.deviceId);return this.source!==Bs.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return $i(this,void 0,void 0,(function*(){let t;if(e){const i=Vo({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 $i(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){co()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Br)))}setProcessor(e){return $i(this,void 0,void 0,(function*(){var t;const i=yield this.processorLock.lock();try{if(!lo()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(ks.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return $i(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return $i(this,void 0,void 0,(function*(){const e=yield qo(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(ks.AudioSilenceDetected)),e}))}}const Wr=Object.values(Qs),Jr=Object.values($s),Qr=Object.values(Xs),$r=[Qs.h180,Qs.h360],Xr=[$s.h180,$s.h360],Yr=["q","h","f"];function Zr(e,t,i,n){var s,o;let r=null==n?void 0:n.videoEncoding;e&&(r=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!r&&!a&&!c||!t||!i)return[{}];r||(r=function(e,t,i,n){const s=function(e,t,i){if(e)return Qr;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return Wr;return Jr}(e,t,i);let{encoding:o}=s[0];const r=Math.max(t,i);for(let e=0;e<s.length;e+=1){const t=s[e];if(o=t.encoding,t.width>=r)break}if(n)switch(n){case"av1":case"h265":o=Object.assign({},o),o.maxBitrate=.7*o.maxBitrate;break;case"vp9":o=Object.assign({},o),o.maxBitrate=.85*o.maxBitrate}return o}(e,t,i,d),Gi.debug("using video encoding",r));const l=r.maxFramerate,u=new Ks(t,i,r.maxBitrate,r.maxFramerate,r.priority);if(c&&io(d)){const e=new na(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=Ls();if(ro()||lo()||"Chrome"===(null==i?void 0:i.name)&&go(null==i?void 0:i.version,"113")<0){const n="h"==e.suffix?2:3,s=function(e){return e||(e=Ls()),"Safari"===(null==e?void 0:e.name)&&go(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&go(e.osVersion,"18.3")>0}(i);for(let i=0;i<e.spatial;i+=1)t.push({rid:Yr[2-i],maxBitrate:r.maxBitrate/Math.pow(n,i),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,i):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:r.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),Gi.debug("using svc encoding",{encodings:t}),t}if(!a)return[r];let h,p=[];if(p=e?null!==(s=ia(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:ea(e,u):null!==(o=ia(null==n?void 0:n.videoSimulcastLayers))&&void 0!==o?o:ea(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return ta(t,i,[e,h,u],l);if(n>=480)return ta(t,i,[e,u],l)}return ta(t,i,[u])}function ea(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new Ks(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)}));var i;const{width:n,height:s}=t,o=n>s?n/s:s/n;return Math.abs(o-16/9)<Math.abs(o-4/3)?$r:Xr}function ta(e,t,i,n){const s=[];if(i.forEach(((i,o)=>{if(o>=Yr.length)return;const r=Math.min(e,t),a={rid:Yr[o],scaleResolutionDownBy:Math.max(1,r/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=so()||0===o;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)})),lo()&&"ios"===po()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,Gi.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Gi.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function ia(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 na{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 sa extends Gr{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,Bs.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>$i(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 this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const t=new Map(e.map((e=>[e.rid,e]))),i=e.some((e=>"cpu"===e.qualityLimitationReason));if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(ks.CpuConstrained)),this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=Vr(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new l}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!co())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()}),Br))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return $i(this,void 0,void 0,(function*(){var t,i,n,s,o;yield e.pauseUpstream.call(this);try{for(var r,a=!0,c=Yi(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.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}});return $i(this,void 0,void 0,(function*(){var t,i,n,s,o;yield e.resumeUpstream.call(this);try{for(var r,a=!0,c=Yi(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.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 $i(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==Bs.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return $i(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Bs.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return $i(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},o=i.get(e.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(e){const t=[];for(let i=Fs.LOW;i<=Fs.HIGH;i+=1)t.push(new ki({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(io(this.codec),t)}restartTrack(e){return $i(this,void 0,void 0,(function*(){var t,i,n,s,o;let r;if(e){const t=Vo({video:e});"boolean"!=typeof t.video&&(r=t.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var a,c=!0,d=Yi(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(o=e.sender.transport)||void 0===o?void 0:o.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){i={error:e}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return $i(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,o,r,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Yi(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(e){o={error:e}}finally{try{u||s||!(r=h.return)||(yield r.call(h))}finally{if(o)throw o.error}}}()}))}setDegradationPreference(e){return $i(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return $i(this,void 0,void 0,(function*(){var t,i,n,s,o,r,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(io(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Yi(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield oa(t.sender,t.encodings,e.qualities,this.senderLock,io(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(io(e.codec),e.qualities)}}catch(e){o={error:e}}finally{try{t||s||!(r=i.return)||(yield r.call(i))}finally{if(o)throw o.error}}return c}))}setPublishingLayers(e,t){return $i(this,void 0,void 0,(function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield oa(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return $i(this,void 0,void 0,(function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const e=this.sender.getParameters();e.encodings=e.encodings.map(((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&io(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})})),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return $i(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),ao()&&this.isInBackground&&this.source===Bs.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function oa(e,t,i,n,s,o,r){return $i(this,void 0,void 0,(function*(){const a=yield n.lock();o.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void o.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(s){i.some((e=>e.enabled))&&i.forEach((e=>e.enabled=!0))}a.forEach(((e,n)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=ra(a),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,o.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),so()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}))}c&&(n.encodings=a,o.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}}))}function ra(e){switch(e){case"f":default:return Fs.HIGH;case"h":return Fs.MEDIUM;case"q":return Fs.LOW}}function aa(e,t,i,n){if(!i)return[new mt({quality:Fs.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new na(n),o=[],r="h"==s.suffix?1.5:2,a="h"==s.suffix?2:3;for(let n=0;n<s.spatial;n+=1)o.push(new mt({quality:Math.min(Fs.HIGH,s.spatial-1)-n,width:Math.ceil(e/Math.pow(r,n)),height:Math.ceil(t/Math.pow(r,n)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,n)):0,ssrc:0}));return o}return i.map((i=>{var n,s,o;const r=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=ra(null!==(s=i.rid)&&void 0!==s?s:"");return new mt({quality:a,width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:null!==(o=i.maxBitrate)&&void 0!==o?o:0,ssrc:0})}))}const ca="_lossy",da="_reliable",la="leave-reconnect";var ua;!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"}(ua||(ua={}));class ha extends tn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=xr.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=ua.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Gi,this.reliableDataSequence=1,this.reliableMessageBuffer=new cr,this.reliableReceivedState=new dr(3e4),this.handleDataChannel=e=>$i(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===da)t.reliableDCSub=i;else{if(i.label!==ca)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=e=>$i(this,void 0,void 0,(function*(){var t,i;const n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));n=yield e.data.arrayBuffer()}const s=gt.fromBinary(new Uint8Array(n));if(s.sequence>0&&""!==s.participantSid){const e=this.reliableReceivedState.get(s.participantSid);if(e&&s.sequence<=e)return;this.reliableReceivedState.set(s.participantSid,s.sequence)}"speaker"===(null===(t=s.value)||void 0===t?void 0:t.case)?this.emit(bs.ActiveSpeakersUpdate,s.value.value.speakers):("user"===(null===(i=s.value)||void 0===i?void 0:i.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(s,s.value.value),this.emit(bs.DataPacketReceived,s))}finally{n()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?ft.LOSSY:ft.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(bs.Disconnected),this.close()},n=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==s?(e===la&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Us.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),s)):i(n)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===ua.Connected&&e();const i=()=>{this.off(bs.Disconnected,n),e()},n=()=>{this.off(bs.Restarted,i),t()};this.once(bs.Restarted,i),this.once(bs.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(bs.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return e===ft.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount),t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===sr.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(tt.RR_SIGNAL_DISCONNECTED))},this.log=zi(null!==(t=e.loggerName)&&void 0!==t?t:Ki.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new or(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new l,this.dataProcessLock=new l,this.dcBufferStatus=new Map([[ft.LOSSY,!0],[ft.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(bs.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(bs.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(bs.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(bs.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(bs.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(bs.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(bs.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(bs.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,o;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(o=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===o?void 0:o.identity,pID:this.participantSid}}join(e,t,i,n){return $i(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,this.emit(bs.SignalConnected,s),s}catch(s){if(s instanceof Ss&&s.reason===ps.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}}))}close(){return $i(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(bs.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return $i(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new cr,this.reliableDataSequence=1,this.reliableReceivedState.clear()}))}cleanupClient(){return $i(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Es("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 Ss("publication of local track timed out, no response from server",ps.Timeout))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return $i(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return $i(this,void 0,void 0,(function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==_r.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new Nr(n,e.subscriberPrimary,this.loggerOptions),this.emit(bs.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>$i(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===_r.CONNECTED){const t=this.pcState===ua.New;this.pcState=ua.Connected,t&&this.emit(bs.Connected,e)}else t===_r.FAILED&&this.pcState===ua.Connected&&(this.pcState=ua.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?tt.RR_SUBSCRIBER_FAILED:tt.RR_PUBLISHER_FAILED));const s=this.client.isDisconnected||this.client.currentState===sr.RECONNECTING,o=[_r.FAILED,_r.CLOSING,_r.CLOSED].includes(t);s&&o&&!this._isClosed&&this.emit(bs.Offline)})),this.pcManager.onTrack=e=>{this.emit(bs.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=(e,t)=>$i(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,t))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t)=>$i(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);i&&this.client.sendAnswer(i,t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(bs.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(bs.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(bs.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(bs.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(bs.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",tt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case di.DISCONNECT:this.emit(bs.Disconnected,null==e?void 0:e.reason),this.close();break;case di.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(la);break;case di.RESUME:this.handleDisconnect(la)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ze.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(ca,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(da,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,i){return $i(this,void 0,void 0,(function*(){if(eo()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(to()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new Rs("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return $i(this,void 0,void 0,(function*(){if(eo())return this.createSimulcastTransceiverSender(e,t,i,n);if(to())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Rs("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return $i(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Rs("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Lo(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};i&&(s.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return $i(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Rs("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender}))}createRTCRtpSender(e){return $i(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Rs("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return $i(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)Gi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Ze.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:_r.NEW)!==_r.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof Rs?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof pa||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",tt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(bs.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return $i(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new Rs("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(bs.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new pa;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof Ss&&e.reason===ps.NotAllowed)throw new Rs("could not reconnect, token might be expired");throw new pa}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(bs.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==sr.CONNECTED)throw new pa("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(bs.Restarted)}catch(e){const t=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),e}}))}resumeConnection(e){return $i(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new Rs("could not reconnect, url or token not saved");if(!this.pcManager)throw new Rs("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(bs.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t="";if(e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof Ss&&e.reason===ps.NotAllowed)throw new Rs("could not reconnect, token might be expired");if(e instanceof Ss&&e.reason===ps.LeaveRequest)throw e;throw new pa(t)}if(this.emit(bs.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==sr.CONNECTED)throw new pa("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(bs.Resumed)}))}waitForPCInitialConnection(e,t){return $i(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Rs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return $i(this,void 0,void 0,(function*(){this.pcState=ua.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Zs(2e3),!this.pcManager)throw new Rs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ua.Connected}catch(e){throw this.pcState=ua.Disconnected,new Ss("could not establish PC connection, ".concat(e.message),ps.InternalError)}}))}publishRpcResponse(e,t,i,n){return $i(this,void 0,void 0,(function*(){const s=new gt({destinationIdentities:[e],kind:ft.RELIABLE,value:{case:"rpcResponse",value:new Pt({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,ft.RELIABLE)}))}publishRpcAck(e,t){return $i(this,void 0,void 0,(function*(){const i=new gt({destinationIdentities:[e],kind:ft.RELIABLE,value:{case:"rpcAck",value:new Et({requestId:t})}});yield this.sendDataPacket(i,ft.RELIABLE)}))}sendDataPacket(e,t){return $i(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(t),t===ft.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===ft.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)}))}resendReliableMessagesForResume(e){return $i(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(ft.RELIABLE);const t=this.dataChannelForKind(ft.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach((e=>{t.send(e.data)}))),this.updateAndEmitDCBufferStatus(ft.RELIABLE)}))}waitForBufferStatusLow(e){return new Promise(((t,i)=>$i(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(bs.Closing,n);!this.dcBufferStatus.get(e);)yield Zs(10);this.off(bs.Closing,n),t()}}))))}ensureDataTransportConnected(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new Rs("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new Ss("".concat(o," connection not set"),ps.InternalError);let r=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),r=!0),r||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(r=!0),r&&t.negotiate();const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield Zs(50)}throw new Ss("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),ps.InternalError)}()}))}ensurePublisherConnected(e){return $i(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===_r.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return $i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>$i(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new Is("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(bs.Closing,n),this.pcManager.publisher.once(Er,(e=>{const t=new Map;e.forEach((e=>{const i=e.codec.toLowerCase();var n;n=i,Gs.includes(n)&&t.set(e.payload,i)})),this.emit(bs.RTPVideoMapUpdate,t)}));try{yield this.pcManager.negotiate(i),e()}catch(e){e instanceof Is&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",tt.RR_UNKNOWN),t(e)}finally{this.off(bs.Closing,n)}}))))}))}dataChannelForKind(e,t){if(t){if(e===ft.LOSSY)return this.lossyDCSub;if(e===ft.RELIABLE)return this.reliableDCSub}else{if(e===ft.LOSSY)return this.lossyDC;if(e===ft.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),r=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array,c=new Array;e.forEach((e=>{e.isDesired!==r&&a.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new Pi({answer:s?ar({sdp:s.sdp,type:s.type}):void 0,offer:o?ar({sdp:o.sdp,type:o.type}):void 0,subscription:new si({trackSids:a,subscribe:!r,participantTracks:[]}),publishTracks:Wo(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new Ri({publisherSid:t,lastSeq:e})))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Ii({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(ft.LOSSY),Kt.PUBLISHER),t(this.dataChannelForKind(ft.RELIABLE),Kt.PUBLISHER),t(this.dataChannelForKind(ft.LOSSY,!0),Kt.SUBSCRIBER),t(this.dataChannelForKind(ft.RELIABLE,!0),Kt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Us.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){co()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){co()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class pa extends Error{}class ma{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 uo(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return $i(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),Gi.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return $i(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 Ss("Could not fetch region settings: ".concat(t.statusText),401===t.status?ps.NotAllowed:ps.InternalError,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class ga{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class fa extends ga{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>$i(this,void 0,void 0,(function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch(e){return{done:!0,value:void 0}}})),return(){return $i(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return $i(this,void 0,void 0,(function*(){var e,t,i,n;let s=new Set;try{for(var o,r=!0,a=Yi(this);!(e=(o=yield a.next()).done);r=!0){n=o.value,r=!1;const e=n;s.add(e)}}catch(e){t={error:e}}finally{try{r||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return Array.from(s)}))}}class va extends ga{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Mo(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>$i(this,void 0,void 0,(function*(){try{const{done:i,value:n}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)})}catch(e){return{done:!0,value:void 0}}})),return(){return $i(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return $i(this,void 0,void 0,(function*(){var e,t,i,n;let s="";try{for(var o,r=!0,a=Yi(this);!(e=(o=yield a.next()).done);r=!0){n=o.value,r=!1;s+=n}}catch(e){t={error:e}}finally{try{r||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return s}))}}class ba{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return $i(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class ka extends ba{}class ya extends ba{}class Ta extends Bs{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ks.Muted:ks.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(ks.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return $i(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),Br)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame((()=>e()));const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(ks.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Ca extends Ta{constructor(e,t,i,n,s,o){super(e,t,Bs.Kind.Audio,i,o),this.monitorReceiver=()=>$i(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=Vr(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;lo()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(lo())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return $i(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(no(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&no(e)&&e.setSinkId(this.sinkId).catch((e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)})),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then((()=>{"running"!==e.state&&this.emit(ks.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(ks.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return $i(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Sa extends Ta{constructor(e,t,i,n,s){super(e,t,Bs.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>$i(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=Vr(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Cr((()=>{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?qs(this._mediaStreamTrack,t):Vs(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 wa(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const 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 $i(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return $i(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!n||s;this.lastVisible!==o&&(!o&&Date.now()-i<100?Us.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(ks.VisibilityChanged,o,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,o=e.height()*s;t+o>i+n&&(i=t,n=o)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(ks.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return mo();if(!t){return mo()>2?2:1}return t}}class wa{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=Ea(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ea(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=Ea(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Pa(e),this.isPiP=co()&&Ea(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Pa(this.element),this.isPiP=Ea(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,To().observe(this.element),ko().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=To())||void 0===e||e.unobserve(this.element),null===(t=ko())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function Ea(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Pa(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Pa(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const o=e.offsetWidth,r=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+r>i.pageYOffset&&s+o>i.pageXOffset&&!a&&"none"!==c}class Ra extends tn.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=ut.NONE,this.log=Gi,this.handleMuted=()=>{this.emit(ks.Muted)},this.handleUnmuted=()=>{this.emit(ks.Unmuted)},this.log=zi(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:Ki.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=Bs.Source.Unknown}setTrack(e){this.track&&(this.track.off(ks.Muted,this.handleMuted),this.track.off(ks.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ks.Muted,this.handleMuted),e.on(ks.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Jo(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ut.NONE}get audioTrack(){if(Do(this.track))return this.track}get videoTrack(){if(Lo(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Bs.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Bs.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}!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"}(Ra||(Ra={}));class Ia extends Ra{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(ks.Ended)},this.handleCpuConstrained=()=>{this.track&&Lo(this.track)&&this.emit(ks.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(ks.Ended,this.handleTrackEnded),this.track.off(ks.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ks.Ended,this.handleTrackEnded),e.on(ks.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return $i(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return $i(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return $i(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return $i(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(Do(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(nt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(nt.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(nt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(nt.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(nt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(nt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function Ma(e,t){return $i(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:o}=Qo(e);let r=o.audio,a=o.video;if(n&&"object"==typeof o.audio&&(o.audio.processor=n),s&&"object"==typeof o.video&&(o.video.processor=s),e.audio&&"object"==typeof o.audio&&"string"==typeof o.audio.deviceId){const e=o.audio.deviceId;o.audio.deviceId={exact:e},i=!0,r=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&"object"==typeof o.video&&"string"==typeof o.video.deviceId){const e=o.video.deviceId;o.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}(!0===o.audio||"object"==typeof o.audio&&!o.audio.deviceId)&&(o.audio={deviceId:"default"}),!0===o.video?o.video={deviceId:"default"}:"object"!=typeof o.video||o.video.deviceId||(o.video.deviceId="default");const c=Fo(o,Ar,Dr),d=Vo(c),l=navigator.mediaDevices.getUserMedia(d);o.audio&&(Zo.userMediaPromiseMap.set("audioinput",l),l.catch((()=>Zo.userMediaPromiseMap.delete("audioinput")))),o.video&&(Zo.userMediaPromiseMap.set("videoinput",l),l.catch((()=>Zo.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>$i(this,void 0,void 0,(function*(){const o="audio"===i.kind;let r,a=o?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=o?d.audio:d.video;"boolean"!=typeof l&&(r=l);const u=i.getSettings().deviceId;(null==r?void 0:r.deviceId)&&Po(r.deviceId)!==u?r.deviceId=u:r||(r={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new zr(e,t,!1,void 0,i);case"video":return new sa(e,t,!1,i);default:throw new Es("unsupported track type: ".concat(e.kind))}}(i,r,t);return h.kind===Bs.Kind.Video?h.source=Bs.Source.Camera:h.kind===Bs.Kind.Audio&&(h.source=Bs.Source.Microphone),h.mediaStream=e,Do(h)&&n?yield h.setProcessor(n):Lo(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(n){if(!i)throw n;return Ma(Object.assign(Object.assign({},e),{audio:r,video:a}),t)}}))}var Oa;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(Oa||(Oa={}));class Aa extends tn.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===dt.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===ct.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,o){let r=arguments.length>6&&void 0!==arguments[6]?arguments[6]:dt.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Oa.Unknown,this.log=Gi,this.log=zi(null!==(a=null==o?void 0:o.loggerName)&&void 0!==a?a:Ki.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=r,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Eo,this.once(vs.Active,(()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0}))),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(Bs.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Bs.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Bs.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===ct.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==ct.ACTIVE&&this.emit(vs.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(vs.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(vs.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const o of n)e[o]!==t[o]&&(s[o]=null!==(i=t[o])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(vs.AttributesChanged,t)}setPermissions(e){var t,i,n,s,o,r;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(r=this.permissions)||void 0===r?void 0:r.canSubscribeMetrics);return this.permissions=e,c&&this.emit(vs.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(vs.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case Ye.EXCELLENT:return Oa.Excellent;case Ye.GOOD:return Oa.Good;case Ye.POOR:return Oa.Poor;case Ye.LOST:return Oa.Lost;default:return Oa.Unknown}}(e),t!==this._connectionQuality&&this.emit(vs.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>Do(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on(ks.Muted,(()=>{this.emit(vs.TrackMuted,e)})),e.on(ks.Unmuted,(()=>{this.emit(vs.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Bs.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Bs.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class Da extends Aa{constructor(e,t,i,n,s){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=ut.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Eo)},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.handleClosing=()=>{var e,t,i,n,s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),null===(o=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===o||o.call(s,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Eo),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Ni.OK&&s.reject(new Os(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=Ur.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ci({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Jo(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Jo(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Jo(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Jo(t))),this.emit(vs.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>$i(this,void 0,void 0,(function*(){var t,i,n,s,o;if(!(null===(o=this.roomOptions)||void 0===o?void 0:o.dynacast))return;const r=this.videoTrackPublications.get(e.trackSid);if(!r)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!r.videoTrack)return;const a=yield r.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Yi(a);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;zs(e)&&(this.log.debug("publish ".concat(e," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Jo(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,e,r.options))}}catch(e){i={error:e}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>$i(this,void 0,void 0,(function*(){if(e.source===Bs.Source.ScreenShare||e.source===Bs.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Jo(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(_o(e)||xo(e))try{if(co())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Bs.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),Jo(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Jo(e))),_o(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Jo(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==ut.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(bs.RemoteMute,((e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())})),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(bs.Connected,this.handleReconnected).on(bs.SignalConnected,this.handleSignalConnected).on(bs.SignalRestarted,this.handleReconnected).on(bs.SignalResumed,this.handleReconnected).on(bs.Restarting,this.handleReconnecting).on(bs.Resuming,this.handleReconnecting).on(bs.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(bs.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(bs.Closing,this.handleClosing).on(bs.SignalRequestResponse,this.handleSignalRequestResponse).on(bs.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return $i(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return $i(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return $i(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return $i(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,o)=>$i(t,void 0,void 0,(function*(){var t,r;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(r=null!=n?n:this.name)&&void 0!==r?r:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{o(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield Zs(50)}o(new Os("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&o(e)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(Bs.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Bs.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Bs.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(vs.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return $i(this,void 0,void 0,(function*(){this.encryptionType=e?ut.GCM:ut.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(e,t,i,n){return $i(this,void 0,void 0,(function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t)if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case Bs.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case Bs.Source.Microphone:t=yield this.createTracks({audio:null===(o=i)||void 0===o||o});break;case Bs.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Es(e)}}catch(i){throw null==t||t.forEach((e=>{e.stop()})),i instanceof Error&&this.emit(vs.MediaDevicesError,i,Go(e)),this.pendingPublishing.delete(e),i}for(const n of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===Bs.Source.Microphone&&Do(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{const e=[];for(const i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Jo(i))),e.push(this.publishTrack(i,n));const i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach((e=>{e.stop()})),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e)&&(r=yield this.waitForPendingPublicationOfSource(e),r||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),r&&r.track)if(e===Bs.Source.ScreenShare){r=yield this.unpublishTrack(r.track);const e=this.getTrackPublication(Bs.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r}))}enableCameraAndMicrophone(){return $i(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Bs.Source.Camera)&&!this.pendingPublishing.has(Bs.Source.Microphone)){this.pendingPublishing.add(Bs.Source.Camera),this.pendingPublishing.add(Bs.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(Bs.Source.Camera),this.pendingPublishing.delete(Bs.Source.Microphone)}}}))}createTracks(e){return $i(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=Fo(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const e=yield Ma(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return e.map((e=>(Do(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=Bs.Source.Microphone,this.emit(vs.AudioStreamAcquired)),Lo(e)&&(this.cameraError=void 0,e.source=Bs.Source.Camera),e)))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}}))}createScreenTracks(e){return $i(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new ws("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=Ls();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&go(e.osVersion,"17")>=0}()||(e.resolution=Xs.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=oo()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new Es("no video track found");const s=new sa(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=Bs.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(vs.AudioStreamAcquired);const e=new zr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=Bs.Source.ScreenShareAudio,o.push(e)}return o}))}publishTrack(e,t){return $i(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return $i(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,o,r,a;let c,d;if(_o(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),Ao(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case Bs.Source.Microphone:t="audioinput";break;case Bs.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new zr(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new sa(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Es("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach((t=>{t.track&&t.track===e&&(d=t)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),Jo(d))),d;const l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(o=null==t?void 0:t.forceStereo)&&void 0!==o?o:l;u&&(t||(t={}),void 0===t.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),Jo(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=t.dtx)&&void 0!==r||(t.dtx=!1),null!==(a=t.red)&&void 0!==a||(t.red=!1));const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){const e=Ls(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&go(t,e.osVersion)>=0)||"Safari"===e.name&&go(t,e.version)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);const p=new Promise(((t,n)=>$i(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==sr.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Jo(e)}));const i=setTimeout((()=>{n(new Ms("publishing rejected as engine not connected within timeout",408))}),15e3);yield this.waitUntilEngineConnected(),clearTimeout(i);const s=yield this.publish(e,h,u);t(s)}else try{const i=yield this.publish(e,h,u);t(i)}catch(e){n(e)}}catch(e){n(e)}}))));i.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Eo),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Jo(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map((e=>function(e){switch(e){case $e.CAMERA:return Bs.Source.Camera;case $e.MICROPHONE:return Bs.Source.Microphone;case $e.SCREEN_SHARE:return Bs.Source.ScreenShare;case $e.SCREEN_SHARE_AUDIO:return Bs.Source.ScreenShareAudio;default:return Bs.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Jo(e))),!1)}publish(e,t,i){return $i(this,void 0,void 0,(function*(){var n,s,o,r,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new Ms("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>Ao(e)&&t.source===e.source))&&e.source!==Bs.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Jo(e))),t.stopMicTrackOnMute&&Do(e)&&(e.stopOnMute=!0),e.source===Bs.Source.ScreenShare&&so()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(oo())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(so())return!1;if(oo()){const e=Ls();if((null==e?void 0:e.version)&&go(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&go(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=Mr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===zo(e.mime)))||(t.videoCodec=zo(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(ks.Muted,this.onTrackMuted),e.on(ks.Unmuted,this.onTrackUnmuted),e.on(ks.Ended,this.handleTrackEnded),e.on(ks.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ks.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ks.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(n=t.dtx)||void 0===n||n),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(nt.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(nt.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(nt.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(nt.TF_STEREO),g&&m.push(nt.TF_NO_DTX),_o(e)&&e.hasPreConnectBuffer&&m.push(nt.TF_PRECONNECT_BUFFER);const v=new Qt({cid:e.mediaStreamTrack.id,name:t.name,type:Bs.kindToProto(e.kind),muted:e.isMuted,source:Bs.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m});let b;if(e.kind===Bs.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(t){const n=null!==(r=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==r?r:Qs.h720.resolution;i={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{dims:i}))}v.width=i.width,v.height=i.height,xo(e)&&(io(p)&&(e.source===Bs.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Jo(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),v.simulcastCodecs=[new Jt({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:Mr}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===ut.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new Jt({codec:t.backupCodec.codec,cid:""})))),b=Zr(e.source===Bs.Source.ScreenShare,v.width,v.height,t),v.layers=aa(v.width,v.height,b,io(t.videoCodec))}else e.kind===Bs.Kind.Audio&&(b=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Rs("cannot publish track when not connected");const k=()=>$i(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new Rs("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(vs.LocalSenderCreated,e.sender,e),xo(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===Bs.Source.ScreenShare||e.constraints.height&&Po(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),b)if(so()&&e.kind===Bs.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=b[0])||void 0===n?void 0:n.maxBitrate)?b[0].maxBitrate/1e3:0})}else e.codec&&io(e.codec)&&(null===(s=b[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()}));let y;const T=new Promise(((t,i)=>$i(this,void 0,void 0,(function*(){var n;try{y=yield this.engine.addTrack(v),t(y)}catch(t){e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch((t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{error:t}))}))),i(t)}}))));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([T,k()]);y=e[0]}else{let i;if(y=yield T,y.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===Bs.Kind.Video){const n=zo(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{codec:n})),t.videoCodec=n,b=Zr(e.source===Bs.Source.ScreenShare,v.width,v.height,t))}yield k()}const C=new Ia(e.kind,y,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(ks.CpuConstrained,(e=>this.onTrackCpuConstrained(e,C))),C.options=t,e.sid=y.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:y})),xo(e)?e.startMonitor(this.engine.client):_o(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit(vs.LocalTrackPublished,C),_o(e)&&y.audioFeatures.includes(nt.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();if(this.on(vs.LocalTrackSubscribed,(t=>{if(t.trackSid===y.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),Jo(e))),e.stopPreConnectBuffer()}})),t){const n=new Promise(((n,s)=>$i(this,void 0,void 0,(function*(){var o,r,a,c,d,l;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Jo(e)));const m=setTimeout((()=>{s(new Error("agent not active within 10 seconds"))}),1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Jo(e)));const v=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:C.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=Yi(t);!(o=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){r={error:e}}finally{try{h||o||!(a=p.return)||(yield a.call(p))}finally{if(r)throw r.error}}yield v.close(),n()}catch(e){s(e)}}))));n.then((()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Jo(e)))})).catch((t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{error:t}))}))}}return C}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return $i(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==ut.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new Es("track is not published");if(!xo(e))throw new Es("track is not a video track");const o=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),r=function(e,t,i){var n,s,o,r;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Gi.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(o=a.height)&&void 0!==o?o:null===(r=e.dimensions)||void 0===r?void 0:r.height;return e.source===Bs.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),Zr(e.source===Bs.Source.ScreenShare,c,d,i)}(e,t,o);if(!r)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Jo(e)));const a=e.addSimulcastTrack(t,r);if(!a)return;const c=new Qt({cid:a.mediaStreamTrack.id,type:Bs.kindToProto(e.kind),muted:e.isMuted,source:Bs.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=aa(c.width,c.height,r),!this.engine||this.engine.isClosed)throw new Rs("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>$i(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,o,r),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:r,trackInfo:d}))}))}unpublishTrack(e,t){return $i(this,void 0,void 0,(function*(){var i,n;if(Ao(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Jo(e))),yield t)}const s=this.getPublicationForTrack(e),o=s?Jo(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));(e=s.track).off(ks.Muted,this.onTrackMuted),e.off(ks.Unmuted,this.onTrackUnmuted),e.off(ks.Ended,this.handleTrackEnded),e.off(ks.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ks.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ks.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let r=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<_r.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",r=!0);if(this.engine.removeTrack(a)&&(r=!0),xo(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(r=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:e}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case Bs.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case Bs.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(vs.LocalTrackUnpublished,s),s.setTrack(void 0),r&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return $i(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise(((n,s)=>$i(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))})),yield Promise.all(t.map((e=>$i(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===Bs.Source.ScreenShare||t.source===Bs.Source.ScreenShareAudio||!_o(t)&&!xo(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),n()}catch(e){s(e)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return $i(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?ft.RELIABLE:ft.LOSSY,s=i.destinationIdentities,o=i.topic,r=new gt({kind:n,value:{case:"user",value:new kt({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:o})}});yield t.engine.sendDataPacket(r,n)}()}))}publishDtmf(e,t){return $i(this,void 0,void 0,(function*(){const i=new gt({kind:ft.RELIABLE,value:{case:"sipDtmf",value:new yt({code:e,digit:t})}});yield this.engine.sendDataPacket(i,ft.RELIABLE)}))}sendChatMessage(e,t){return $i(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new gt({value:{case:"chatMessage",value:new St(Object.assign(Object.assign({},i),{timestamp:D.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,ft.RELIABLE),this.emit(vs.ChatMessage,i),i}))}editChatMessage(e,t){return $i(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new gt({value:{case:"chatMessage",value:new St(Object.assign(Object.assign({},i),{timestamp:D.parse(i.timestamp),editTimestamp:D.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,ft.RELIABLE),this.emit(vs.ChatMessage,i),i}))}sendText(e,t){return $i(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,o=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),r=new Array(o?o.length+1:1).fill(0),a=(e,i)=>{var n;r[i]=e;const s=r.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:o,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&o&&(yield Promise.all(t.attachments.map(((e,i)=>$i(this,void 0,void 0,(function*(){return this._sendFile(o[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))))),c.info}))}streamText(e){return $i(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},o=new Bt({streamId:n,mimeType:s.mimeType,topic:s.topic,timestamp:Oo(s.timestamp),totalLength:Oo(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new jt({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?Ut.UPDATE:Ut.CREATE})}}),r=null==e?void 0:e.destinationIdentities,a=new gt({destinationIdentities:r,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(a,ft.RELIABLE);let c=0;const d=this,l=new WritableStream({write(e){return $i(this,void 0,void 0,(function*(){for(const t of function(e,t){const i=[];let n=(new TextEncoder).encode(e);for(;n.length>t;){let e=t;for(;e>0;){const t=n[e];if(void 0!==t&&128!=(192&t))break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,15e3)){yield d.engine.waitForBufferStatusLow(ft.RELIABLE);const e=new Vt({content:t,streamId:n,chunkIndex:Oo(c)}),i=new gt({destinationIdentities:r,value:{case:"streamChunk",value:e}});yield d.engine.sendDataPacket(i,ft.RELIABLE),c+=1}}))},close(){return $i(this,void 0,void 0,(function*(){const e=new qt({streamId:n}),t=new gt({destinationIdentities:r,value:{case:"streamTrailer",value:e}});yield d.engine.sendDataPacket(t,ft.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let u=()=>$i(this,void 0,void 0,(function*(){yield h.close()}));d.engine.once(bs.Closing,u);const h=new ka(l,s,(()=>this.engine.off(bs.Closing,u)));return h}))}sendFile(e,t){return $i(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return $i(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:e,value:t}=yield o.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return $i(this,void 0,void 0,(function*(){var t,i,n,s,o;const r=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,c={id:r,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown"},d=new Bt({totalLength:Oo(null!==(o=c.size)&&void 0!==o?o:0),mimeType:c.mimeType,streamId:r,topic:c.topic,timestamp:Oo(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Ft({name:c.name})}}),u=new gt({destinationIdentities:a,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,ft.RELIABLE);let h=0;const p=new l,m=this.engine,g=this.log,f=new WritableStream({write(e){return $i(this,void 0,void 0,(function*(){const t=yield p.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3);yield m.waitForBufferStatusLow(ft.RELIABLE);const n=new gt({destinationIdentities:a,value:{case:"streamChunk",value:new Vt({content:t,streamId:r,chunkIndex:Oo(h)})}});yield m.sendDataPacket(n,ft.RELIABLE),h+=1,i+=t.byteLength}}finally{t()}}))},close(){return $i(this,void 0,void 0,(function*(){const e=new qt({streamId:r}),t=new gt({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,ft.RELIABLE)}))},abort(e){g.error("Sink error:",e)}});return new ya(f,c)}))}performRpc(e){return $i(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:o=1e4}=e;return function*(){return new Promise(((e,r)=>$i(t,void 0,void 0,(function*(){var t,a,c,d;if(jr(s)>15360)return void r(Ur.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&go(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void r(Ur.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(i,l,n,s,o-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),r(Ur.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:i});const h=setTimeout((()=>{this.pendingResponses.delete(l),r(Ur.builtIn("RESPONSE_TIMEOUT"))}),o);this.pendingResponses.set(l,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?r(i):e(null!=t?t:"")},participantIdentity:i})}))))}()}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return $i(this,void 0,void 0,(function*(){const o=new gt({destinationIdentities:[e],kind:ft.RELIABLE,value:{case:"rpcRequest",value:new wt({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,ft.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,Ur.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}setActiveAgent(e){var t,i,n,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(s=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Eo),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(_o(n)||xo(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return $i(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[i]=t;return i.source===e}));if(t)return t[1];yield Zs(20)}}))}}class La extends Ra{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(ks.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new si({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new It({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ks.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Ra.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ra.SubscriptionStatus.Subscribed:Ra.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ra.PermissionStatus.Allowed:Ra.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.requestedDisabled!==!e&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)===e.height||(jo(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&jo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:Fs.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(ks.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(ks.VisibilityChanged,this.handleVisibilityChange),n.off(ks.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(ks.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ks.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ks.VisibilityChanged,this.handleVisibilityChange),e.on(ks.Ended,this.handleEnded),this.emit(ks.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(ks.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?ks.Muted:ks.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(ks.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ks.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return jo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new oi({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Bs.Kind.Video){let s=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(s){$o(this.videoDimensionsAdaptiveStream,s)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(t=this.trackInfo,i=this.requestedMaxQuality,null===(n=t.layers)||void 0===n?void 0:n.find((e=>e.quality===i)));e&&$o(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream;s?(e.width=Math.ceil(s.width),e.height=Math.ceil(s.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Fs.HIGH})),e.quality=Fs.HIGH)}var t,i,n;this.emit(ks.UpdateSettings,e)}}class xa extends Aa{static fromParticipantInfo(e,t,i){return new xa(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,o,r){super(t,i||"",n,s,o,r,arguments.length>7&&void 0!==arguments[7]?arguments[7]:dt.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(ks.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Jo(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)})),e.on(ks.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(ks.SubscriptionPermissionChanged,(t=>{this.emit(vs.TrackSubscriptionPermissionChanged,e,t)})),e.on(ks.SubscriptionStatusChanged,(t=>{this.emit(vs.TrackSubscriptionStatusChanged,e,t)})),e.on(ks.Subscribed,(t=>{this.emit(vs.TrackSubscribed,t,e)})),e.on(ks.Unsubscribed,(t=>{this.emit(vs.TrackUnsubscribed,t,e)})),e.on(ks.SubscriptionFailed,(t=>{this.emit(vs.TrackSubscriptionFailed,e.trackSid,t)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Bs.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Bs.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,o){let r=this.getTrackPublicationBySid(t);if(r||t.startsWith("TR")||this.trackPublications.forEach((t=>{r||e.kind!==t.kind.toString()||(r=t)})),!r)return 0===o?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(vs.TrackSubscriptionFailed,t)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,o-1)}),150));if("ended"===e.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Jo(r))),void this.emit(vs.TrackSubscriptionFailed,t);let a;return a="video"===e.kind?new Sa(e,t,n,s):new Ca(e,t,n,this.audioContext,this.audioOutput),a.source=r.source,a.isMuted=r.isMuted,a.setMediaStream(i),a.start(),r.setTrack(a),this.volumeMap.has(r.source)&&No(a)&&Do(a)&&a.setVolume(this.volumeMap.get(r.source)),r}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach((e=>{var n,s;let o=this.getTrackPublicationBySid(e.sid);if(o)o.updateInfo(e);else{const t=Bs.kindFromProto(e.type);if(!t)return;o=new La(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),o.updateInfo(e),i.set(e.sid,o);const r=Array.from(this.trackPublications.values()).find((e=>e.source===(null==o?void 0:o.source)));r&&o.source!==Bs.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Jo(r),newTrack:Jo(o)})),this.addTrackPublication(o)}t.set(e.sid,o)})),this.trackPublications.forEach((e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Jo(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(vs.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case Bs.Kind.Audio:this.audioTrackPublications.delete(e);break;case Bs.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(vs.TrackUnpublished,i)}setAudioOutput(e){return $i(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;Do(i.track)&&No(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var _a;!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(_a||(_a={}));class Na extends tn.EventEmitter{constructor(e){var t,i,n,s;if(super(),t=this,this.state=_a.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Gi,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(e,t,i)=>$i(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!eo()&&!to())throw lo()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const s=yield this.disconnectLock.lock();if(this.state===_a.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(_a.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),uo(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new ma(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const o=(n,r,a)=>$i(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{yield this.attemptConnection(null!=a?a:e,t,i,l),this.abortController=void 0,n()}catch(e){if(this.regionUrlProvider&&e instanceof Ss&&e.reason!==ps.Cancelled&&e.reason!==ps.NotAllowed){let t=null;try{t=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof Ss&&(401===e.status||e.reason===ps.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void r(e)}t&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(e.message,". Retrying with another region: ").concat(t),this.logContext),this.recreateEngine(),yield o(n,r,t)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Io(e)),r(e))}else{let t=et.UNKNOWN_REASON;e instanceof Ss&&(t=Io(e)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),r(e)}}})),r=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Eo(((e,t)=>{o(e,t,r)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,o)=>$i(this,void 0,void 0,(function*(){var r,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},o.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(r=d.room)||void 0===r?void 0:r.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Ps("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>$i(this,void 0,void 0,(function*(){var s,o;this.state===_a.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},xr),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(fs.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new Ss("could not establish signal connection",ps.ServerUnreachable);throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof Ss&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:e})),t}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Ss("Connection attempt aborted",ps.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}co()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),co()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(_a.Connected),this.emit(fs.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return $i(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s,o;const r=yield e.disconnectLock.lock();try{if(e.state===_a.Disconnected)return void e.log.debug("already disconnected",e.logContext);e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===_a.Connecting||e.state===_a.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new Ss("Client initiated disconnect",ps.Cancelled)),e.connectFuture=void 0),(null===(o=e.engine)||void 0===o?void 0:o.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,et.CLIENT_INITIATED),e.engine=void 0}finally{r()}}()}))},this.onPageLeave=()=>$i(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>$i(this,void 0,void 0,(function*(){const e=[],t=Ls();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=wo();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(fs.Disconnected,(()=>{null==i||i.remove(),i=null}))}e.push(i)}this.remoteParticipants.forEach((t=>{t.audioTrackPublications.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...e.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.startVideo=()=>$i(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(_a.Reconnecting)&&this.emit(fs.Reconnecting)},this.handleSignalRestarted=e=>$i(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(_a.Connected),this.emit(fs.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===ct.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emitWhenConnected(fs.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)})),e.forEach((e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(fs.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=Bs.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit(vs.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(fs.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(fs.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(vs.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(fs.SipDTMFReceived,t,e),null==e||e.emit(vs.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:o,endTime:r,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(r.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit(ks.TranscriptionReceived,s),null==i||i.emit(vs.TranscriptionReceived,s,n),this.emit(fs.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(fs.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(fs.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(fs.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(fs.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(fs.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(fs.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>$i(this,void 0,void 0,(function*(){var e;"iOS"!==(null===(e=Ls())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit(fs.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(fs.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(fs.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=e=>{this.emit(fs.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(fs.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(fs.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(fs.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(fs.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>$i(this,void 0,void 0,(function*(){var t,i,n,s,o,r;if(null===(t=e.track)||void 0===t||t.on(ks.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(ks.Restarted,this.onLocalTrackRestarted),null===(o=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===o||o.call(s,this),this.emit(fs.LocalTrackPublished,e,this.localParticipant),_o(e.track)){(yield e.track.checkForSilence())&&this.emit(fs.LocalAudioSilenceDetected,e)}const a=yield null===(r=e.track)||void 0===r?void 0:r.getDeviceId(!1),c=Go(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(fs.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(ks.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(ks.Restarted,this.onLocalTrackRestarted),this.emit(fs.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>$i(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=Go(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(fs.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit(fs.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(fs.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(fs.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(fs.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Lr),e),this.log=zi(null!==(i=this.options.loggerName)&&void 0!==i?i:Ki.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Ar),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Dr),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Or),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new l,this.localParticipant=new Da("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Po(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Po(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Po(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE(),co()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),Na.cleanupRegistry&&Na.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,i,n,s,o){return $i(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==o)return void(yield this.engine.publishRpcResponse(e,t,null,Ur.builtIn("UNSUPPORTED_VERSION")));const r=this.rpcHandlers.get(i);if(!r)return void(yield this.engine.publishRpcResponse(e,t,null,Ur.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const o=yield r({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});jr(o)>15360?(a=Ur.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=o}catch(e){e instanceof Ur?a=e:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),a=Ur.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)}))}setE2EEEnabled(e){return $i(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Xo(this.options.e2ee),this.e2eeManager.on(us.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(fs.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(us.EncryptionError,(e=>this.emit(fs.EncryptionError,e))),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return $i(this,void 0,void 0,(function*(){return this.state===_a.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(bs.RoomUpdate,i),e(t.sid))};this.engine.on(bs.RoomUpdate,i),this.once(fs.Disconnected,(()=>{this.engine.off(bs.RoomUpdate,i),t("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new ha(this.options),this.engine.on(bs.ParticipantUpdate,this.handleParticipantUpdates).on(bs.RoomUpdate,this.handleRoomUpdate).on(bs.SpeakersChanged,this.handleSpeakersChanged).on(bs.StreamStateChanged,this.handleStreamStateUpdate).on(bs.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(bs.SubscriptionError,this.handleSubscriptionError).on(bs.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(bs.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(bs.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(bs.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(bs.DataPacketReceived,this.handleDataPacket).on(bs.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(_a.SignalReconnecting)&&this.emit(fs.SignalReconnecting)})).on(bs.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(_a.Connected)&&this.emit(fs.Reconnected)})).on(bs.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===_a.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(bs.Restarting,this.handleRestarting).on(bs.SignalRestarted,this.handleSignalRestarted).on(bs.Offline,(()=>{this.setAndEmitConnectionState(_a.Reconnecting)&&this.emit(fs.Reconnecting)})).on(bs.DCBufferStatusChanged,((e,t)=>{this.emit(fs.DCBufferStatusChanged,e,t)})).on(bs.LocalTrackSubscribed,(e=>{const t=this.localParticipant.getTrackPublications().find((t=>{let{trackSid:i}=t;return i===e}));t?(this.localParticipant.emit(vs.LocalTrackSubscribed,t),this.emitWhenConnected(fs.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})).on(bs.RoomMoved,(e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach(((e,t)=>{this.handleParticipantDisconnected(t,e)})),this.emit(fs.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Zo.getInstance().getDevices(e,t)}prepareConnection(e,t){return $i(this,void 0,void 0,(function*(){if(this.state===_a.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(uo(new URL(e))&&t){this.regionUrlProvider=new ma(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===_a.Disconnected&&(this.regionUrl=i,yield fetch(Ro(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ro(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return $i(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Mi({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Mi({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Mi({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Mi({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>$i(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Mi({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>$i(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Mi({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new Mi({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>$i(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new ci({reason:et.CLIENT_INITIATED,action:di.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Mi({scenario:{case:"subscriberBandwidth",value:Oo(t)}});break;case"leave-full-reconnect":i=new Mi({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return $i(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,o,r,a,c,d,l;let u=!0,h=!1;const p=n?{exact:t}:t;if("audioinput"===e){h=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===Bs.Source.Microphone));try{u=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)})))).every((e=>!0===e))}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}const o=n.some((e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i}));u&&o&&(h=!0)}else if("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;const t=null!==(o=i.getActiveDevice(e))&&void 0!==o?o:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Bs.Source.Camera));try{u=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)})))).every((e=>!0===e))}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}const s=n.some((e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i}));u&&s&&(h=!0)}else if("audiooutput"===e){if(h=!0,!no()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!==(r=yield Zo.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==r?r:""),null!==(a=(l=i.options).audioOutput)&&void 0!==a||(l.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return h&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(fs.ActiveDeviceChanged,e,t)),u}()}))}setupLocalParticipantEvents(){this.localParticipant.on(vs.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(vs.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(vs.AttributesChanged,this.onLocalAttributesChanged).on(vs.TrackMuted,this.onLocalTrackMuted).on(vs.TrackUnmuted,this.onLocalTrackUnmuted).on(vs.LocalTrackPublished,this.onLocalTrackPublished).on(vs.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(vs.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(vs.MediaDevicesError,this.onMediaDevicesError).on(vs.AudioStreamAcquired,this.startAudio).on(vs.ChatMessage,this.onLocalChatMessageSent).on(vs.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===_a.Connecting||this.state===_a.Reconnecting){const n=()=>{this.onTrackAdded(e,t,i),s()},s=()=>{this.off(fs.Reconnected,n),this.off(fs.Connected,n),this.off(fs.Disconnected,s)};return this.once(fs.Reconnected,n),this.once(fs.Connected,n),void this.once(fs.Disconnected,s)}if(this.state===_a.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let o=n[1],r=e.id;if(o&&o.startsWith("TR")&&(r=o),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find((e=>e.sid===s));if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),a.addSubscribedMediaTrack(e,r,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==_a.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(vs.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(vs.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(vs.AttributesChanged,this.onLocalAttributesChanged).off(vs.TrackMuted,this.onLocalTrackMuted).off(vs.TrackUnmuted,this.onLocalTrackUnmuted).off(vs.LocalTrackPublished,this.onLocalTrackPublished).off(vs.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(vs.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(vs.MediaDevicesError,this.onMediaDevicesError).off(vs.AudioStreamAcquired,this.startAudio).off(vs.ChatMessage,this.onLocalChatMessageSent).off(vs.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),co()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(_a.Disconnected),this.emit(fs.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(fs.ParticipantDisconnected,t),t.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return $i(this,void 0,void 0,(function*(){var i;if("byteHeader"===e.contentHeader.case){const n=this.byteStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const o={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Mo(e.timestamp),attributes:e.attributes},r=new ReadableStream({start:t=>{s=t,this.byteStreamControllers.set(e.streamId,{info:o,controller:s,startTime:Date.now()})}});n(new fa(o,r,Mo(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let n;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:t=>{n=t,this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});i(new va(s,o,Mo(e.totalLength)),{identity:t})}}))}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}selectDefaultDevices(){return $i(this,void 0,void 0,(function*(){var e,t,i;const n=Zo.getInstance().previousDevices,s=yield Zo.getInstance().getDevices(void 0,!1),o=Ls();if("Chrome"===(null==o?void 0:o.name)&&"iOS"!==o.os)for(let e of s){const t=n.find((t=>t.deviceId===e.deviceId));t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(fs.ActiveDeviceChanged,e.kind,e.deviceId)}const r=["audiooutput","audioinput","videoinput"];for(let o of r){const r=Ho(o),a=this.localParticipant.getTrackPublication(r);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter((e=>e.kind===o)),d=this.getActiveDevice(o);d===(null===(t=n.filter((e=>e.kind===o))[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(o,c[0].deviceId):"audioinput"===o&&!ro()||"videoinput"===o||!(c.length>0)||c.find((e=>e.deviceId===this.getActiveDevice(o)))||"audiooutput"===o&&ro()||(yield this.switchActiveDevice(o,c[0].deviceId))}}))}acquireAudioContext(){return $i(this,void 0,void 0,(function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=Ko())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),Zs(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(fs.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?xa.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new xa(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);if(t){i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity)}return i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(fs.ParticipantConnected,i),i.on(vs.TrackPublished,(e=>{this.emitWhenConnected(fs.TrackPublished,e,i)})).on(vs.TrackSubscribed,((e,t)=>{e.kind===Bs.Kind.Audio?(e.on(ks.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(ks.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===Bs.Kind.Video&&(e.on(ks.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(ks.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(fs.TrackSubscribed,e,t,i)})).on(vs.TrackUnpublished,(e=>{this.emit(fs.TrackUnpublished,e,i)})).on(vs.TrackUnsubscribed,((e,t)=>{this.emit(fs.TrackUnsubscribed,e,t,i)})).on(vs.TrackMuted,(e=>{this.emitWhenConnected(fs.TrackMuted,e,i)})).on(vs.TrackUnmuted,(e=>{this.emitWhenConnected(fs.TrackUnmuted,e,i)})).on(vs.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(fs.ParticipantMetadataChanged,e,i)})).on(vs.ParticipantNameChanged,(e=>{this.emitWhenConnected(fs.ParticipantNameChanged,e,i)})).on(vs.AttributesChanged,(e=>{this.emitWhenConnected(fs.ParticipantAttributesChanged,e,i)})).on(vs.ConnectionQualityChanged,(e=>{this.emitWhenConnected(fs.ConnectionQualityChanged,e,i)})).on(vs.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(fs.ParticipantPermissionsChanged,e,i)})).on(vs.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(fs.TrackSubscriptionStatusChanged,e,t,i)})).on(vs.TrackSubscriptionFailed,((e,t)=>{this.emit(fs.TrackSubscriptionFailed,e,i,t)})).on(vs.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(fs.TrackSubscriptionPermissionChanged,e,t,i)})).on(vs.Active,(()=>{this.emitWhenConnected(fs.ParticipantActive,i),i.kind===dt.AGENT&&this.localParticipant.setActiveAgent(i)})),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Uo(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Us.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,et.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Us.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(fs.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,i]=e;this.emit(t,...i)})),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===_a.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===_a.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return $i(this,void 0,void 0,(function*(){var t,i;const n=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new st({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:D.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new at({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(fs.SignalConnected),this.emit(fs.Connected),this.setAndEmitConnectionState(_a.Connected),n.video){const e=new Ia(Bs.Kind.Video,new pt({source:$e.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Qe.AUDIO,name:"video-dummy"}),new sa(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Co(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(vs.LocalTrackPublished,e)}if(n.audio){const e=new Ia(Bs.Kind.Audio,new pt({source:$e.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Qe.AUDIO}),new zr(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:wo(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(vs.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new at({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:ct.ACTIVE,tracks:[],joinedAt:D.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const o=Co(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),r=new pt({source:$e.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Qe.AUDIO});n.addSubscribedMediaTrack(o,r.sid,new MediaStream([o]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}if(s.audio){const e=wo(),i=new pt({source:$e.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Qe.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==fs.ActiveSpeakersChanged&&e!==fs.TranscriptionReceived){const t=Ua(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function Ua(e){return e.map((e=>{if(e)return Array.isArray(e)?Ua(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}var ja;Na.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()})),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"}(ja||(ja={}));tn.EventEmitter;tn.EventEmitter;const Fa=(e,t)=>"error"===e||t,Ba=(e,t)=>{const i=(new Date).toISOString(),n=t?.source?`[${t.source}]`:"";return`${i} ${t?.level?`[${t.level.toUpperCase()}]`:""} ${n}`},Va=e=>({log:(t,i)=>{if(!Fa(i?.level||"debug",e))return;const n=Ba(0,{...i,level:"debug"});console.log(n,t,i?.error||"")},info:(t,i)=>{if(!Fa(i?.level||"info",e))return;const n=Ba(0,{...i,level:"info"});console.info(n,t,i?.error||"")},warn:(t,i)=>{if(!Fa(i?.level||"warn",e))return;const n=Ba(0,{...i,level:"warn"});console.warn(n,t,i?.error||"")},error:(t,i)=>{if(!Fa(i?.level||"error",e))return;const n=Ba(0,{...i,level:"error"});console.error(n,t,i?.error||"")}});var qa,Ka,Ha,Ga,za,Wa,Ja,Qa,$a,Xa,Ya,Za,ec,tc,ic,nc,sc,oc,rc,ac,cc,dc;const lc=.02,uc=.001;class hc extends s.EventEmitter{constructor(){super(),qa.add(this),this.analyticsInterval=null,this.lastAgentSpeakStart=null,this.lastUserSpeakStart=null,this.callStartTime=null,this.room=null,this.isConnected=!1,this.lastUserAudioLevel=0,this.lastAgentAudioLevel=0,this.userDropoutStartTime=null,this.agentDropoutStartTime=null,this.vadUserSpeakStart=null,this.vadAgentSpeakStart=null,this.lastUserInputTime=null,this.previousConnectionQuality="unknown",t(this,qa,"m",Ka).call(this)}setRoom(e){this.room=e}setConnectionState(e,t=null){this.isConnected=e,t&&(this.callStartTime=t)}updateConnectionStats(e,t){this.callStats.connectionAttempts=e,this.callStats.reconnectionAttempts=t,this.performanceMetrics.reconnectionCount=t}updateCounts(e,t){this.callStats.participantCount=e,this.callStats.trackCount=t}setConnectionEstablishedTime(e){this.performanceMetrics.connectionEstablishedTime=e}startAnalyticsCollection(){this.analyticsInterval&&this.stopAnalyticsCollection(),this.analyticsInterval=setInterval((()=>{t(this,qa,"m",Ha).call(this)}),5e3)}stopAnalyticsCollection(){this.analyticsInterval&&(clearInterval(this.analyticsInterval),this.analyticsInterval=null)}handleConnectionQualityChanged(e,i){const n=t(this,qa,"m",Ga).call(this,e);this.connectionMetrics.quality=n,this.callStats.connectionQuality=n,t(this,qa,"m",za).call(this),t(this,qa,"m",cc).call(this,n);const s={quality:e,participant:i.identity||"unknown",metrics:{quality:n}};this.emit("connectionQualityChanged",s)}handleAudioPlaybackChanged(e){this.emit("audioPlaybackChanged",e),t(this,qa,"m",Qa).call(this)}getConnectionStats(){return{quality:this.connectionMetrics.quality,connectionAttempts:this.callStats.connectionAttempts,reconnectionAttempts:this.callStats.reconnectionAttempts,connectionEstablishedTime:this.performanceMetrics.connectionEstablishedTime,isConnected:this.isConnected}}getAudioLevels(){return{userAudioLevel:this.audioMetrics.userAudioLevel,agentAudioLevel:this.audioMetrics.agentAudioLevel,userSpeakingTime:this.audioMetrics.userSpeakingTime,agentSpeakingTime:this.audioMetrics.agentSpeakingTime,audioDropouts:this.audioMetrics.audioDropouts,echoCancellationActive:this.audioMetrics.echoCancellationActive,currentUserLevel:this.audioMetrics.userAudioLevel,currentAgentLevel:this.audioMetrics.agentAudioLevel}}getPerformanceMetrics(){const e=this.callStartTime?Date.now()-this.callStartTime:0;return{responseTime:this.performanceMetrics.responseTime,connectionEstablishedTime:this.performanceMetrics.connectionEstablishedTime,reconnectionCount:this.performanceMetrics.reconnectionCount,callDuration:e,averageResponseTime:this.performanceMetrics.responseTime}}recordResponseTime(e){this.performanceMetrics.responseTime=e,this.emit("responseTimeRecorded",{responseTime:e,timestamp:Date.now()})}getVADSettings(){return{audioThreshold:lc,minSpeakingDuration:100,dropoutThreshold:uc,dropoutDetectionDuration:500}}getCallAnalytics(e,t,i,n){const s=this.getPerformanceMetrics(),o=this.getAudioLevels();return{connectionStats:this.getConnectionStats(),audioMetrics:{...o,isPaused:n,volume:i},performanceMetrics:s,participants:e,trackStats:t,callStats:this.callStats,metadata:{callStartTime:this.callStartTime,isConnected:this.isConnected,isPaused:n,volume:i},callDuration:s.callDuration}}getInternalConnectionStats(){return{latency:this.connectionMetrics.latency,packetLoss:this.connectionMetrics.packetLoss,bandwidth:this.connectionMetrics.bandwidth,quality:this.connectionMetrics.quality,jitter:this.connectionMetrics.jitter,connectionAttempts:this.callStats.connectionAttempts,reconnectionAttempts:this.callStats.reconnectionAttempts,connectionEstablishedTime:this.performanceMetrics.connectionEstablishedTime,isConnected:this.isConnected}}getInternalPerformanceMetrics(){const e=this.callStartTime?Date.now()-this.callStartTime:0;return{responseTime:this.performanceMetrics.responseTime,networkLatency:this.performanceMetrics.networkLatency||this.connectionMetrics.latency,connectionEstablishedTime:this.performanceMetrics.connectionEstablishedTime,reconnectionCount:this.performanceMetrics.reconnectionCount,callDuration:e,averageResponseTime:this.performanceMetrics.responseTime}}cleanup(){this.stopAnalyticsCollection(),t(this,qa,"m",Ka).call(this),this.lastAgentSpeakStart=null,this.lastUserSpeakStart=null,this.vadUserSpeakStart=null,this.vadAgentSpeakStart=null,this.userDropoutStartTime=null,this.agentDropoutStartTime=null,this.lastUserInputTime=null,this.lastUserAudioLevel=0,this.lastAgentAudioLevel=0,this.previousConnectionQuality="unknown"}}var pc,mc,gc,fc,vc,bc,kc,yc,Tc,Cc,Sc,wc,Ec,Pc,Rc,Ic,Mc,Oc,Ac,Dc;qa=new WeakSet,Ka=function(){this.callStats={connectionAttempts:0,reconnectionAttempts:0,totalBytesReceived:0,totalBytesSent:0,packetsLost:0,participantCount:0,trackCount:0,audioLevels:[],connectionQuality:"unknown"},this.connectionMetrics={latency:0,packetLoss:0,bandwidth:0,quality:"unknown",jitter:0},this.audioMetrics={userAudioLevel:0,agentAudioLevel:0,userSpeakingTime:0,agentSpeakingTime:0,audioDropouts:0,echoCancellationActive:!1},this.performanceMetrics={responseTime:0,networkLatency:0,connectionEstablishedTime:0,reconnectionCount:0}},Ha=function(){if(this.room&&this.isConnected)try{if(t(this,qa,"m",za).call(this),this.room?.localParticipant){const e=this.room.localParticipant.connectionQuality;if(e){const i=t(this,qa,"m",Ga).call(this,e);this.connectionMetrics.quality=i,this.callStats.connectionQuality=i}}t(this,qa,"m",Qa).call(this),t(this,qa,"m",Ya).call(this),t(this,qa,"m",dc).call(this);const e=this.getPerformanceMetrics();this.emit("analyticsUpdated",{connectionStats:this.getConnectionStats(),audioMetrics:this.getAudioLevels(),performanceMetrics:e,callDuration:e.callDuration})}catch(e){}},Ga=function(e){switch(e){case Oa.Excellent:return"excellent";case Oa.Good:return"good";case Oa.Poor:return"poor";default:return"lost"}},za=function(){t(this,qa,"m",Wa).call(this)},Wa=function(){const e=this.room?.localParticipant?.connectionQuality;if(!e)return;const i=t(this,qa,"m",Ja).call(this,e);0===this.connectionMetrics.latency&&(this.connectionMetrics.latency=i.latency,this.connectionMetrics.packetLoss=i.packetLoss,this.connectionMetrics.bandwidth=i.bandwidth)},Ja=function(e){switch(e){case Oa.Excellent:return{latency:10,packetLoss:0,bandwidth:1e6};case Oa.Good:return{latency:50,packetLoss:.1,bandwidth:5e5};case Oa.Poor:return{latency:200,packetLoss:1,bandwidth:1e5};default:return{latency:1e3,packetLoss:10,bandwidth:0}}},Qa=function(){if(!this.room)return;const e=Date.now(),i=this.room.activeSpeakers;let n=0,s=0;for(const o of i)o===this.room.localParticipant?n=t(this,qa,"m",$a).call(this,o,e):s=Math.max(s,t(this,qa,"m",Xa).call(this,o,e));this.audioMetrics.userAudioLevel=n,this.audioMetrics.agentAudioLevel=s},$a=function(e,i){const n=e.audioLevel||0,s=e.isSpeaking;return s&&!this.lastUserSpeakStart?(this.lastUserSpeakStart=i,this.lastUserInputTime=i):!s&&this.lastUserSpeakStart&&(this.audioMetrics.userSpeakingTime+=i-this.lastUserSpeakStart,this.lastUserSpeakStart=null),t(this,qa,"m",ec).call(this,"user",n,i),t(this,qa,"m",sc).call(this,"user",n,i),n},Xa=function(e,i){const n=e.audioLevel||0,s=e.isSpeaking;if(s&&!this.lastAgentSpeakStart){if(this.lastAgentSpeakStart=i,this.lastUserInputTime){const e=i-this.lastUserInputTime;this.performanceMetrics.responseTime=e,this.lastUserInputTime=null}}else!s&&this.lastAgentSpeakStart&&(this.audioMetrics.agentSpeakingTime+=i-this.lastAgentSpeakStart,this.lastAgentSpeakStart=null);return t(this,qa,"m",ec).call(this,"agent",n,i),t(this,qa,"m",sc).call(this,"agent",n,i),n},Ya=function(){this.room&&(this.callStats.participantCount=1+this.room.remoteParticipants.size,this.callStats.trackCount=t(this,qa,"m",Za).call(this))},Za=function(){let e=0;e+=this.room?.localParticipant.trackPublications.size||0;for(const t of this.room?.remoteParticipants.values()||[])e+=t.trackPublications.size;return e},ec=function(e,i,n){"user"===e?t(this,qa,"m",tc).call(this,i,n):t(this,qa,"m",ic).call(this,i,n)},tc=function(e,i){const n=e>lc;n&&!this.vadUserSpeakStart?this.vadUserSpeakStart=i:!n&&this.vadUserSpeakStart&&t(this,qa,"m",nc).call(this,"user",e,i)},ic=function(e,i){const n=e>lc;n&&!this.vadAgentSpeakStart?this.vadAgentSpeakStart=i:!n&&this.vadAgentSpeakStart&&t(this,qa,"m",nc).call(this,"agent",e,i)},nc=function(e,t,i){const n="user"===e?this.vadUserSpeakStart:this.vadAgentSpeakStart;if(!n)return;const s=i-n;s>=100&&this.emit("voiceActivityDetected",{participant:e,duration:s,audioLevel:t,timestamp:i}),"user"===e?this.vadUserSpeakStart=null:this.vadAgentSpeakStart=null},sc=function(e,i,n){"user"===e?t(this,qa,"m",oc).call(this,i,n):t(this,qa,"m",rc).call(this,i,n)},oc=function(e,i){this.lastUserAudioLevel>lc&&e<uc?this.userDropoutStartTime||(this.userDropoutStartTime=i):e>=uc&&this.userDropoutStartTime&&t(this,qa,"m",ac).call(this,"user",i),this.lastUserAudioLevel=e},rc=function(e,i){this.lastAgentAudioLevel>lc&&e<uc?this.agentDropoutStartTime||(this.agentDropoutStartTime=i):e>=uc&&this.agentDropoutStartTime&&t(this,qa,"m",ac).call(this,"agent",i),this.lastAgentAudioLevel=e},ac=function(e,t){const i="user"===e?this.userDropoutStartTime:this.agentDropoutStartTime;if(!i)return;const n=t-i;n>=500&&(this.audioMetrics.audioDropouts++,this.emit("audioDropoutDetected",{participant:e,duration:n,timestamp:t})),"user"===e?this.userDropoutStartTime=null:this.agentDropoutStartTime=null},cc=function(e){if(this.previousConnectionQuality!==e){let t=0;switch(e){case"excellent":t=5;break;case"good":t=15;break;case"poor":t=50;break;case"lost":t=200;break;default:t=30}this.connectionMetrics.jitter=t,this.previousConnectionQuality=e,this.emit("jitterChanged",{jitter:t,quality:e,previousQuality:this.previousConnectionQuality,timestamp:Date.now()})}},dc=function(){if(!this.room?.localParticipant?.audioTrackPublications)return;let e=!1;for(const t of this.room.localParticipant.audioTrackPublications.values())if(t.track){const i=t.track.getConstraints?.();if(!1!==i?.echoCancellation){e=!0;break}}this.audioMetrics.echoCancellationActive!==e&&(this.audioMetrics.echoCancellationActive=e,this.emit("echoCancellationChanged",{active:e,timestamp:Date.now()}))};class Lc extends s.EventEmitter{constructor(){super(...arguments),pc.add(this),this.audioElements=new Set,this.trackStats=new Map,this.volume=1,this.room=null,this.audioContext=null,this.inputAnalyser=null,this.outputAnalyser=null,this.audioCaptureEnabled=!1,this.audioCaptureOptions=null,this.recorders=new Map,this.processors=new Map,this.trackCaptureMap=new Map}setRoom(e){this.room=e}setVolume(e){try{const t=Number(e);Number.isFinite(t)?this.volume=Math.min(1,Math.max(0,t)):this.volume=0;for(const e of this.audioElements)e&&void 0!==e.volume&&(e.volume=this.volume);this.emit("volumeChanged",this.volume)}catch(e){this.emit("error",new Error(`Failed to set volume: ${e instanceof Error?e.message:String(e)}`))}}getOutputVolume(){return this.volume}getInputVolume(){try{if(this.inputAnalyser||t(this,pc,"m",Sc).call(this),!this.inputAnalyser)return 0;const e=this.inputAnalyser.frequencyBinCount,i=new Uint8Array(e);if(this.inputAnalyser.getByteFrequencyData(i),0===i.length)return 0;let n=0;for(const e of i)n+=e;const s=n/(255*i.length);return Math.max(0,Math.min(1,s))}catch{return 0}}setMicMuted(e){try{if(this.room?.localParticipant){const i=!e,n=this.room.localParticipant.setMicrophoneEnabled(i);return n&&"function"==typeof n.then?void n.then((()=>{t(this,pc,"m",mc).call(this,e?"micMuted":"micUnmuted",e)})).catch((i=>{t(this,pc,"m",gc).call(this,e,i)})):void t(this,pc,"m",mc).call(this,e?"micMuted":"micUnmuted",e)}t(this,pc,"m",mc).call(this,e?"micMuted":"micUnmuted",e)}catch(i){t(this,pc,"m",gc).call(this,e,i)}}isMicMuted(){try{let e;const t=this.room?.localParticipant?.getTrackPublication;if(t)try{e=t(Bs.Source.Microphone)}catch{e=t("microphone")}if(e&&"boolean"==typeof e.isMuted)return e.isMuted}catch{}return!1}getInputByteFrequencyData(){try{if(this.inputAnalyser||t(this,pc,"m",Sc).call(this),!this.inputAnalyser)return new Uint8Array(0);const e=this.inputAnalyser.frequencyBinCount,i=new Uint8Array(e);return this.inputAnalyser.getByteFrequencyData(i),i}catch{return new Uint8Array(0)}}getOutputByteFrequencyData(){try{if(this.outputAnalyser||t(this,pc,"m",wc).call(this),!this.outputAnalyser)return new Uint8Array(0);const e=this.outputAnalyser.frequencyBinCount,i=new Uint8Array(e);return this.outputAnalyser.getByteFrequencyData(i),i}catch{return new Uint8Array(0)}}handleTrackSubscribed(e,i,n){e.kind===Bs.Kind.Audio&&(t(this,pc,"m",fc).call(this,e,i,n),t(this,pc,"m",vc).call(this,e,i,n))}handleTrackUnsubscribed(e,t,i){if(e.kind===Bs.Kind.Audio){this.trackStats.delete(e.sid||e.mediaStreamTrack?.id||"unknown");for(const t of e.detach()){try{t?.parentNode?.removeChild&&t.parentNode.removeChild(t)}catch{}this.audioElements.delete(t)}const n={track:e,publication:t,participant:i.identity||"unknown"};this.emit("trackUnsubscribed",n)}}pauseAllAudio(){for(const e of this.audioElements)e.pause&&e.pause()}resumeAllAudio(){for(const e of this.audioElements)e.play&&e.play().catch((()=>{}))}getTrackStats(){return{totalTracks:this.trackStats.size,activeTracks:this.trackStats.size,audioElements:this.audioElements.size,trackDetails:Array.from(this.trackStats.entries())}}enableAudioCapture(e){const i=e.callback||e.onData;if(!i)throw new Error('Audio capture requires either "callback" or "onData" option');this.audioCaptureEnabled=!0,this.audioCaptureOptions={source:e.source||"agent",format:e.format||"opus-webm",chunkSize:e.chunkSize||100,bufferSize:e.bufferSize||4096,callback:i},t(this,pc,"m",Pc).call(this)}disableAudioCapture(){this.audioCaptureEnabled=!1,t(this,pc,"m",Ac).call(this),this.audioCaptureOptions=null}cleanup(){t(this,pc,"m",Ac).call(this);for(const e of this.audioElements)try{e?.parentNode?.removeChild&&e.parentNode.removeChild(e)}catch{}this.audioElements.clear(),this.trackStats.clear()}}var xc,_c,Nc,Uc,jc,Fc,Bc,Vc,qc,Kc,Hc,Gc,zc,Wc,Jc,Qc,$c,Xc,Yc,Zc,ed,td,id,nd,sd,od,rd,ad,cd,dd,ld,ud;pc=new WeakSet,mc=function(e,t){try{this.emit(e)}catch(e){this.listenerCount("error")>0&&this.emit("error",new Error(`Failed to ${t?"mute":"unmute"} microphone: ${e instanceof Error?e.message:String(e)}`))}},gc=function(e,t){this.listenerCount("error")>0&&this.emit("error",new Error(`Failed to ${e?"mute":"unmute"} microphone: ${t instanceof Error?t.message:String(t)}`))},fc=function(e,i,n){this.trackStats.set(e.sid||e.mediaStreamTrack?.id||"unknown",{trackId:e.sid||e.mediaStreamTrack?.id||"unknown",kind:e.kind,participant:n.identity||"unknown",subscriptionTime:Date.now(),publication:i,source:t(this,pc,"m",Ec).call(this,i.source),muted:i.isMuted,enabled:i.isEnabled,dimensions:i.dimensions,simulcasted:i.simulcasted})},vc=function(e,i,n){const s=e.attach();s&&(s.volume=this.volume,s.autoplay=!0,t(this,pc,"m",Tc).call(this,s),this.audioElements.add(s),t(this,pc,"m",bc).call(this,e,i,n),t(this,pc,"m",kc).call(this,s),t(this,pc,"m",yc).call(this,e,n))},bc=function(e,t,i){const n={track:e,publication:t,participant:i.identity||"unknown",trackStats:this.trackStats.get(e.sid||e.mediaStreamTrack?.id||"unknown")};this.emit("trackSubscribed",n)},kc=function(e){e.style.display="none";try{document.body.appendChild(e)}catch{}},yc=function(e,i){if(!this.audioCaptureEnabled||!this.audioCaptureOptions)return;const n=e.sid||e.mediaStreamTrack?.id||"unknown",s=(i.identity||"").toLowerCase().includes("agent")?"agent":"user",{source:o,format:r}=this.audioCaptureOptions;"both"!==o&&o!==s||!r||t(this,pc,"m",Rc).call(this,n,i.identity||"unknown",s,r)},Tc=function(e){let t=!1;e.addEventListener("play",(()=>{t||(t=!0,this.emit("speaking"))})),e.addEventListener("pause",(()=>{t=!1,this.emit("listening")})),e.addEventListener("ended",(()=>{t=!1,this.emit("listening")}))},Cc=function(){if(this.audioContext)return;const e=globalThis.AudioContext,t="function"==typeof e?e:null;if(t)try{this.audioContext=new t}catch{this.audioContext=null}},Sc=function(){try{if(t(this,pc,"m",Cc).call(this),!this.audioContext)return;let e=null;const i=this.room?.localParticipant?.getTrackPublication;if(i)try{e=i(Bs.Source.Microphone)}catch{e=i("microphone")}const n=e?.track?.mediaStreamTrack;if(!n)return;const s=new MediaStream([n]),o=this.audioContext.createMediaStreamSource(s),r=this.audioContext.createAnalyser();r.fftSize=256;{const e=o;e&&"function"==typeof e.connect&&e.connect(r)}this.inputAnalyser=r}catch{this.inputAnalyser=null}},wc=function(){try{if(t(this,pc,"m",Cc).call(this),!this.audioContext)return;const e=this.audioElements.values().next().value;if(!e)return;const i=this.audioContext.createMediaElementSource(e),n=this.audioContext.createAnalyser();n.fftSize=256;{const e=i;e&&"function"==typeof e.connect&&e.connect(n)}this.outputAnalyser=n}catch{this.outputAnalyser=null}},Ec=function(e){switch(e){case Bs.Source.Microphone:return"microphone";case Bs.Source.Camera:return"camera";case Bs.Source.ScreenShare:return"screen_share";case Bs.Source.ScreenShareAudio:return"screen_share_audio";default:return"unknown"}},Pc=function(){if(!this.audioCaptureOptions)return;const{source:e,format:i}=this.audioCaptureOptions;if(i)for(const[n,s]of this.trackStats.entries()){const o=s.participant.toLowerCase().includes("agent")?"agent":"user";"both"!==e&&e!==o||t(this,pc,"m",Rc).call(this,n,s.participant,o,i)}},Rc=function(e,i,n,s){if(!this.audioCaptureOptions)return;const o=t(this,pc,"m",Oc).call(this,e);if(!o?.mediaStreamTrack)return;this.trackCaptureMap.set(e,{participant:i,source:n});const r=new MediaStream([o.mediaStreamTrack]);"opus-webm"===s?t(this,pc,"m",Ic).call(this,r,e,i,n):t(this,pc,"m",Mc).call(this,{stream:r,trackId:e,participant:i,source:n,format:s})},Ic=function(e,i,n,s){if(!this.audioCaptureOptions?.callback)return;const{chunkSize:o,callback:r}=this.audioCaptureOptions;try{const a=t(this,pc,"m",Dc).call(this),c=new MediaRecorder(e,a?{mimeType:a}:{});c.ondataavailable=e=>{e.data.size>0&&e.data.arrayBuffer().then((e=>{const t={participant:n,source:s,timestamp:Date.now(),trackId:i,format:"opus-webm"};r(e,t)}))},c.start(o),this.recorders.set(i,c)}catch(e){this.emit("error",new Error(`Failed to setup encoded audio capture: ${e instanceof Error?e.message:String(e)}`))}},Mc=function(e){const{stream:t,trackId:i,participant:n,source:s,format:o}=e;if(!this.audioCaptureOptions?.callback)return;const{bufferSize:r,callback:a}=this.audioCaptureOptions;try{this.audioContext||(this.audioContext=new AudioContext);const e=this.audioContext;"suspended"===e.state&&e.resume().catch((()=>{}));const c=e.createMediaStreamSource(t),d=e.createScriptProcessor(r,1,1);d.onaudioprocess=e=>{const t=e.inputBuffer,r=t.getChannelData(0);let c=r;if("pcm-i16"===o){const e=new Int16Array(r.length);for(let t=0;t<r.length;t++)e[t]=Math.max(-32768,Math.min(32767,32768*r[t]));c=e}const d={participant:n,source:s,timestamp:Date.now(),trackId:i,format:o,sampleRate:t.sampleRate,channels:t.numberOfChannels};a(c,d)},c.connect(d),d.connect(e.destination),this.processors.set(i,d)}catch(e){this.emit("error",new Error(`Failed to setup PCM audio capture: ${e instanceof Error?e.message:String(e)}`))}},Oc=function(e){if(!this.room)return null;for(const t of Array.from(this.room.remoteParticipants.values()))for(const i of Array.from(t.trackPublications.values()))if(i.track?.sid===e||i.track?.mediaStreamTrack?.id===e)return i.track;if(this.room.localParticipant)for(const t of Array.from(this.room.localParticipant.trackPublications.values()))if(t.track?.sid===e||t.track?.mediaStreamTrack?.id===e)return t.track;return null},Ac=function(){for(const e of this.recorders.values())try{e.stop()}catch{}this.recorders.clear();for(const e of this.processors.values())try{e.disconnect()}catch{}if(this.processors.clear(),this.trackCaptureMap.clear(),this.audioContext){const e=this.audioContext;"closed"!==e.state&&e.close().catch((()=>{})),this.audioContext=null}},Dc=function(){const e=["audio/webm;codecs=opus","audio/mp4","audio/aac","audio/webm","audio/ogg"];for(const t of e)if(MediaRecorder.isTypeSupported(t))return t;return""};class hd extends s.EventEmitter{constructor(e,i,n=!1){super(),xc.add(this),this.room=null,this.isConnected=!1,this.isPaused=!1,this.participants=new Map,this.callStartTime=null,this.connectionAttempts=0,this.reconnectionAttempts=0,this.hasEmittedConnected=!1,this.lkUrl=e,this.accessToken=i,this.logger=Va(n),this.room=new Na({adaptiveStream:!0,dynacast:!0,videoCaptureDefaults:{resolution:Qs.h720.resolution},audioCaptureDefaults:{echoCancellation:!0,noiseSuppression:!0}}),t(this,xc,"m",_c).call(this)}getRoom(){return this.room}async connect(){try{this.logger.log("connect() called",{source:"LiveKitConnection",error:{lkUrl:this.lkUrl,attempt:this.connectionAttempts+1,stack:new Error("Connection call stack").stack}}),this.callStartTime=Date.now(),this.connectionAttempts++,this.room?.prepareConnection(this.lkUrl,this.accessToken);const e=Date.now();await(this.room?.connect(this.lkUrl,this.accessToken)),this.logger.log("room.connect() completed successfully",{source:"LiveKitConnection",error:{connectionTimeMs:Date.now()-e,roomName:this.room?.name,state:this.room?.state}});const t=Date.now()-e;this.emit("connectionEstablished",t),this.isConnected=!0,this.hasEmittedConnected||(this.emit("connected"),this.hasEmittedConnected=!0)}catch(e){this.logger.error("connect() failed",{source:"LiveKitConnection",error:{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}}),this.emit("connectionError",new Error(`LiveKit connection failed: ${e instanceof Error?e.message:String(e)}`))}}forceDisconnect(){this.isConnected=!1,this.emit("disconnected"),t(this,xc,"m",Qc).call(this)}async disconnect(){const e=Date.now();try{if(this.logger.log("LiveKitConnection.disconnect() - START",{source:"LiveKitConnection",error:{timestamp:e,isConnected:this.isConnected,roomName:this.room?.name,state:this.room?.state,participantCount:this.participants.size,hasRoom:!!this.room,stack:new Error("Disconnect call stack").stack}}),this.room){const e=Date.now();this.logger.log("Calling room.disconnect() (LiveKit SDK)",{source:"LiveKitConnection",error:{timestamp:e,roomName:this.room?.name,state:this.room?.state}}),await this.room.disconnect();const t=Date.now();this.logger.log("room.disconnect() completed (LiveKit SDK)",{source:"LiveKitConnection",error:{timestamp:t,roomDisconnectDuration:t-e,roomName:this.room?.name,state:this.room?.state}})}else this.logger.log("No room to disconnect (room is null)",{source:"LiveKitConnection",error:{timestamp:Date.now()}});const i=Date.now();t(this,xc,"m",Qc).call(this);const n=Date.now();this.logger.log("LiveKitConnection.disconnect() - COMPLETE",{source:"LiveKitConnection",error:{timestamp:n,cleanupDuration:n-i,totalDisconnectDuration:n-e}})}catch(t){const i=Date.now();this.logger.error("LiveKitConnection.disconnect() - FAILED",{source:"LiveKitConnection",error:{timestamp:i,timeSinceStart:i-e,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}}),this.emit("connectionError",new Error(`LiveKit disconnection failed: ${t instanceof Error?t.message:String(t)}`))}}pause(){try{this.isPaused=!0,this.room?.localParticipant&&this.room.localParticipant.setMicrophoneEnabled(!1),this.emit("connectionPaused")}catch(e){this.emit("connectionError",new Error(`Failed to pause call: ${e instanceof Error?e.message:String(e)}`))}}resume(){try{this.isPaused=!1,this.room?.localParticipant&&this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("connectionResumed")}catch(e){this.emit("connectionError",new Error(`Failed to resume call: ${e instanceof Error?e.message:String(e)}`))}}getConnectionStats(){return{connectionAttempts:this.connectionAttempts,reconnectionAttempts:this.reconnectionAttempts,isConnected:this.isConnected,participantCount:this.participants.size}}getConnectionAttempts(){return this.connectionAttempts}getReconnectionAttempts(){return this.reconnectionAttempts}getParticipants(){return Array.from(this.participants.values())}cleanup(){t(this,xc,"m",Qc).call(this)}}xc=new WeakSet,_c=function(){this.room&&this.room.on(fs.Connected,t(this,xc,"m",Nc).bind(this)).on(fs.Disconnected,t(this,xc,"m",Uc).bind(this)).on(fs.Reconnecting,t(this,xc,"m",jc).bind(this)).on(fs.Reconnected,t(this,xc,"m",Fc).bind(this)).on(fs.ParticipantConnected,t(this,xc,"m",Bc).bind(this)).on(fs.ParticipantDisconnected,t(this,xc,"m",Vc).bind(this)).on(fs.ParticipantAttributesChanged,t(this,xc,"m",qc).bind(this)).on(fs.ConnectionStateChanged,t(this,xc,"m",Kc).bind(this)).on(fs.SignalConnected,t(this,xc,"m",Hc).bind(this)).on(fs.SignalReconnecting,t(this,xc,"m",Gc).bind(this)).on(fs.MediaDevicesError,t(this,xc,"m",zc).bind(this)).on(fs.ConnectionQualityChanged,t(this,xc,"m",Wc).bind(this)).on(fs.DCBufferStatusChanged,t(this,xc,"m",Jc).bind(this))},Nc=async function(){try{this.isConnected=!0,this.logger.log("Room Connected event fired",{source:"LiveKitConnection",error:{roomName:this.room?.name,localParticipant:this.room?.localParticipant?.identity,state:this.room?.state}}),await(this.room?.localParticipant?.setMicrophoneEnabled(!0)),this.hasEmittedConnected||(this.emit("connected"),this.hasEmittedConnected=!0)}catch(e){this.logger.error("Error in handleConnected",{source:"LiveKitConnection",error:e}),this.emit("connectionError",new Error(`Failed to initialize after connection: ${e instanceof Error?e.message:String(e)}`))}},Uc=function(){const e=Date.now();this.logger.log("Room Disconnected event fired (from LiveKit SDK) - TIMING",{source:"LiveKitConnection",error:{timestamp:e,roomName:this.room?.name,state:this.room?.state,participantCount:this.participants.size}}),this.isConnected=!1;const i=Date.now();this.emit("disconnected");const n=Date.now();this.logger.log("disconnected event emitted to parent - TIMING",{source:"LiveKitConnection",error:{timestamp:n,emitDuration:n-i}});const s=Date.now();t(this,xc,"m",Qc).call(this);const o=Date.now();this.logger.log("Room Disconnected handler complete - TIMING",{source:"LiveKitConnection",error:{timestamp:o,cleanupDuration:o-s,totalHandlerDuration:o-e}})},jc=function(){this.reconnectionAttempts++,this.logger.log("Room Reconnecting",{source:"LiveKitConnection",error:{attempt:this.reconnectionAttempts,roomName:this.room?.name,state:this.room?.state}}),this.emit("reconnecting")},Fc=function(){this.isConnected=!0,this.logger.log("Room Reconnected successfully",{source:"LiveKitConnection",error:{roomName:this.room?.name,state:this.room?.state,participantCount:this.participants.size}}),this.emit("reconnected")},Bc=function(e){this.logger.log("Participant connected in LiveKit layer",{source:"LiveKitConnection",error:{identity:e.identity,sid:e.sid,metadata:e.metadata,totalParticipants:this.participants.size+1}}),this.participants.set(e.sid||"unknown",{identity:e.identity||"unknown",sid:e.sid||"unknown",connectionTime:Date.now(),metadata:e.metadata}),this.emit("participantConnected",e)},Vc=function(e){this.logger.log("Participant disconnected in LiveKit layer",{source:"LiveKitConnection",error:{identity:e.identity,sid:e.sid,totalParticipantsBeforeRemoval:this.participants.size}}),this.participants.delete(e.sid||"unknown"),this.emit("participantDisconnected",e)},qc=function(e,t){if("lk.agent.state"in e){const t=e["lk.agent.state"];void 0!==t&&this.emit("agentStateChanged",t)}},Kc=function(e){this.logger.log("Connection state changed",{source:"LiveKitConnection",error:{newState:e,roomName:this.room?.name,participantCount:this.participants.size}}),this.emit("connectionStateChanged",e)},Hc=function(){this.logger.log("Signal connection established",{source:"LiveKitConnection",error:{roomName:this.room?.name,state:this.room?.state}})},Gc=function(){this.logger.log("Signal reconnecting (signaling server connection lost)",{source:"LiveKitConnection",error:{roomName:this.room?.name,state:this.room?.state,participantCount:this.participants.size}})},zc=function(e){this.logger.error("Media devices error",{source:"LiveKitConnection",error:{error:e.message,stack:e.stack,roomName:this.room?.name}})},Wc=function(e,t){this.logger.log("Connection quality changed",{source:"LiveKitConnection",error:{participant:t.identity,quality:e,roomName:this.room?.name}})},Jc=function(e,t){this.logger.log("DataChannel buffer status changed",{source:"LiveKitConnection",error:{isLow:e,kind:t,roomName:this.room?.name,participantCount:this.participants.size}})},Qc=function(){this.participants.clear(),this.isConnected=!1,this.isPaused=!1,this.hasEmittedConnected=!1};class pd extends s.EventEmitter{constructor(e=[],t=!1){super(),this.room=null,this.tools=[],this.tools=e,this.logger=Va(t)}setRoom(e){this.room=e,e&&this.tools.length>0&&this.registerTools()}setTools(e){this.tools=Array.isArray(e)?e:[],this.room&&this.registerTools()}registerTools(){if(this.room&&0!==this.tools.length){for(const e of this.tools)e.function_name&&"function"==typeof e.fn&&this.room?.registerRpcMethod(e.function_name,(async t=>{try{const i=JSON.parse(t.payload||"{}"),n=await(e.fn?.(...Object.values(i)));return JSON.stringify(n)}catch(e){return JSON.stringify({error:e instanceof Error?e.message:String(e)})}}));this.emit("toolsRegistered",this.tools.length)}}handleDataReceived(e,t){try{const i=(new TextDecoder).decode(e);this.logger.log("📦 Data received from participant",{source:"LiveKitToolRegistry",error:{participant:t||"unknown",payloadLength:e.length,decodedText:i.substring(0,pd.PAYLOAD_PREVIEW_LENGTH)}});const n=JSON.parse(i),s=n.event,o=n.content||n.data||n;switch(this.logger.log("📨 Parsed message structure",{source:"LiveKitToolRegistry",error:{eventType:s,hasContent:!!n.content,hasData:!!n.data,contentType:typeof o,contentPreview:"string"==typeof o?o.substring(0,pd.TEXT_PREVIEW_LENGTH):JSON.stringify(o).substring(0,pd.TEXT_PREVIEW_LENGTH)}}),s){case"answer":this.logger.log("✅ Emitting answerReceived event",{source:"LiveKitToolRegistry",error:{eventData:o.substring(0,pd.TEXT_PREVIEW_LENGTH),participant:t}}),this.emit("answerReceived",o);break;case"transcription":this.logger.log("✅ Emitting transcriptionReceived event (from data)",{source:"LiveKitToolRegistry",error:{eventData:o.substring(0,pd.TEXT_PREVIEW_LENGTH),participant:t}}),this.emit("transcriptionReceived",o);break;default:this.logger.log("⚡ Emitting customEvent",{source:"LiveKitToolRegistry",error:{eventType:s,eventData:"string"==typeof o?o.substring(0,pd.TEXT_PREVIEW_LENGTH):JSON.stringify(o).substring(0,pd.TEXT_PREVIEW_LENGTH),participant:t}}),this.emit("customEvent",s,o,{timestamp:Date.now(),participant:t||"unknown",rawMessage:n})}this.emit("dataReceived",n,t||"unknown")}catch(i){this.logger.error("❌ Error parsing data received",{source:"LiveKitToolRegistry",error:{message:i instanceof Error?i.message:String(i),participant:t,payloadLength:e.length}})}}handleTranscriptionReceived(e,t){try{this.logger.log("🎤 Transcription received from LiveKit",{source:"LiveKitToolRegistry",error:{participantIdentity:t||"unknown",segmentCount:e.length,segments:e.map((e=>({text:e.text?.substring(0,pd.TEXT_PREVIEW_LENGTH),final:e.final,textLength:e.text?.length})))}});const i=t?.toLowerCase().includes("agent")??!1;this.logger.log("🔍 Participant type detected",{source:"LiveKitToolRegistry",error:{participantIdentity:t,isAgent:i,willEmit:i?"answerReceived":"transcriptionReceived"}});for(const n of e)n.text&&(i?(this.logger.log("✅ Emitting answerReceived event (from LiveKit)",{source:"LiveKitToolRegistry",error:{text:n.text.substring(0,pd.TEXT_PREVIEW_LENGTH),final:n.final,textLength:n.text.length,participant:t}}),this.emit("answerReceived",n.text)):(this.logger.log("✅ Emitting transcriptionReceived event (from LiveKit)",{source:"LiveKitToolRegistry",error:{text:n.text.substring(0,pd.TEXT_PREVIEW_LENGTH),final:n.final,textLength:n.text.length,participant:t}}),this.emit("transcriptionReceived",n.text)))}catch(i){this.logger.error("❌ Error processing transcription",{source:"LiveKitToolRegistry",error:{message:i instanceof Error?i.message:String(i),transcriptionsCount:e.length,participant:t}})}}getToolCount(){return this.tools.length}getTools(){return this.tools}cleanup(){}}pd.TEXT_PREVIEW_LENGTH=100,pd.PAYLOAD_PREVIEW_LENGTH=200;class md extends s.EventEmitter{constructor(e,i,n=[],s=!1){super(),$c.add(this),this.lkUrl=e,this.accessToken=i,this.logger=Va(s),this.logger.log("Initializing LiveKitManager",{source:"LiveKitManager",error:{lkUrl:e,toolsCount:n.length,debug:s}}),this.logger.log("Creating LiveKitConnection module",{source:"LiveKitManager"}),this.connection=new hd(e,i,s),this.logger.log("Creating LiveKitAnalytics module",{source:"LiveKitManager"}),this.analytics=new hc,this.logger.log("Creating LiveKitAudioManager module",{source:"LiveKitManager"}),this.audioManager=new Lc,this.logger.log("Creating LiveKitToolRegistry module",{source:"LiveKitManager",error:{toolsCount:n.length}}),this.toolRegistry=new pd(n,s),n.length>0&&this.logger.log("Registered client-side tools",{source:"LiveKitManager",error:{toolNames:n.map((e=>e.function_name)),totalTools:n.length}}),this.logger.log("Setting up module communication",{source:"LiveKitManager"}),t(this,$c,"m",Xc).call(this),this.logger.log("Setting up event forwarding",{source:"LiveKitManager"}),t(this,$c,"m",Yc).call(this),this.logger.log("Setting up room event handlers",{source:"LiveKitManager"}),t(this,$c,"m",Zc).call(this),this.logger.log("LiveKitManager initialization complete",{source:"LiveKitManager"})}async connect(){if(this.connection.isConnected)return void this.logger.log("Already connected, skipping duplicate connection",{source:"LiveKitManager"});this.logger.log("Starting LiveKit room connection",{source:"LiveKitManager"});const e=this.connection.getConnectionStats();this.logger.log("Updating connection analytics",{source:"LiveKitManager",error:{currentAttempts:e.connectionAttempts,reconnectionAttempts:e.reconnectionAttempts}}),this.analytics.updateConnectionStats(e.connectionAttempts+1,e.reconnectionAttempts);const t=Date.now();await this.connection.connect();const i=Date.now()-t;this.logger.log("LiveKit room connection established",{source:"LiveKitManager",error:{duration:`${i}ms`}}),this.connection.room&&this.audioManager.setRoom(this.connection.room)}async disconnect(){const e=Date.now();this.logger.log("LiveKitManager.disconnect() - START",{source:"LiveKitManager",error:{timestamp:e,isConnected:this.connection.isConnected,participantCount:this.connection.participants.size,hasRoom:!!this.connection.room}});const t=Date.now();await this.connection.disconnect();const i=Date.now();this.logger.log("LiveKitManager.disconnect() - connection.disconnect() completed",{source:"LiveKitManager",error:{timestamp:i,connectionDisconnectDuration:i-t}});const n=Date.now();this.logger.log("Performing cleanup of all modules",{source:"LiveKitManager",error:{timestamp:n}}),this.cleanup();const s=Date.now();this.logger.log("LiveKitManager.disconnect() - COMPLETE",{source:"LiveKitManager",error:{timestamp:s,cleanupDuration:s-n,totalDisconnectDuration:s-e}})}pause(){this.logger.log("Pausing voice conversation",{source:"LiveKitManager",error:{isConnected:this.connection.isConnected,wasPaused:this.connection.isPaused}}),this.connection.pause(),this.audioManager.pauseAllAudio(),this.logger.log("Voice conversation paused",{source:"LiveKitManager"})}resume(){this.logger.log("Resuming voice conversation",{source:"LiveKitManager",error:{isConnected:this.connection.isConnected,wasPaused:this.connection.isPaused}}),this.connection.resume(),this.audioManager.resumeAllAudio(),this.logger.log("Voice conversation resumed",{source:"LiveKitManager"})}setVolume(e){this.logger.log("Setting audio volume",{source:"LiveKitManager",error:{volume:e,percentage:`${Math.round(100*e)}%`}}),this.audioManager.setVolume(e)}get room(){return this.connection.room}get isConnected(){return this.connection.isConnected}get isPaused(){return this.connection.isPaused}get volume(){return this.audioManager.volume}get audioElements(){return this.audioManager.audioElements}get tools(){return this.toolRegistry.getTools()}get callStats(){return this.analytics.callStats}get connectionMetrics(){return this.analytics.connectionMetrics}get audioMetrics(){return this.analytics.audioMetrics}get performanceMetrics(){return this.analytics.performanceMetrics}get analyticsInterval(){return this.analytics.analyticsInterval}get callStartTime(){return this.analytics.callStartTime||this.connection.callStartTime}get participants(){return this.connection.participants}get trackStats(){return this.audioManager.trackStats}getConnectionStats(){return this.analytics.getConnectionStats()}getAudioLevels(){return{...this.analytics.getAudioLevels(),isPaused:this.connection.isPaused,volume:this.audioManager.volume}}getPerformanceMetrics(){return this.analytics.getPerformanceMetrics()}getParticipants(){return this.connection.getParticipants()}getTrackStats(){return this.audioManager.getTrackStats()}getCallAnalytics(){return this.analytics.getCallAnalytics(this.getParticipants(),this.getTrackStats(),this.audioManager.volume,this.connection.isPaused)}registerTools(e){this.logger.log("Registering client-side tools",{source:"LiveKitManager",error:{newToolsCount:Array.isArray(e)?e.length:0,hasRoom:!!this.room,isConnected:this.connection.isConnected}}),Array.isArray(e)&&e.length>0&&(this.logger.log("Setting new tools in registry",{source:"LiveKitManager",error:{toolNames:e.map((e=>e.function_name)),totalTools:e.length}}),this.toolRegistry.setTools(e)),this.room&&this.toolRegistry.setRoom(this.room),this.toolRegistry.registerTools(),this.logger.log("Tools registration complete",{source:"LiveKitManager",error:{registeredTools:this.toolRegistry.getTools().length}})}cleanup(){this.connection.cleanup(),this.audioManager.cleanup(),this.analytics.cleanup(),this.toolRegistry.cleanup()}}$c=new WeakSet,Xc=function(){this.connection.on("connected",(()=>{const e=this.connection.room;this.analytics.setRoom(e),this.toolRegistry.setRoom(e),this.audioManager.setRoom(e),this.analytics.setConnectionState(!0,this.connection.callStartTime),this.toolRegistry.registerTools(),this.analytics.startAnalyticsCollection(),t(this,$c,"m",Zc).call(this)})),this.connection.on("connectionEstablished",(e=>{this.analytics.setConnectionEstablishedTime(e)})),this.connection.on("connected",(()=>{const e=this.connection.getConnectionStats();this.analytics.updateConnectionStats(e.connectionAttempts,e.reconnectionAttempts)})),this.connection.on("reconnecting",(()=>{const e=this.connection.getConnectionStats();this.analytics.updateConnectionStats(e.connectionAttempts,e.reconnectionAttempts)})),this.connection.on("disconnected",(()=>{this.analytics.stopAnalyticsCollection(),this.analytics.setConnectionState(!1),this.audioManager.cleanup(),this.toolRegistry.cleanup(),this.analytics.cleanup()})),this.connection.on("participantConnected",(()=>{t(this,$c,"m",ed).call(this)})),this.connection.on("participantDisconnected",(()=>{t(this,$c,"m",ed).call(this)})),this.audioManager.on("trackSubscribed",(()=>{t(this,$c,"m",ed).call(this)})),this.audioManager.on("trackUnsubscribed",(()=>{t(this,$c,"m",ed).call(this)}))},Yc=function(){this.connection.on("connected",(()=>this.emit("connected"))),this.connection.on("disconnected",(()=>this.emit("disconnected"))),this.connection.on("reconnecting",(()=>this.emit("reconnecting"))),this.connection.on("reconnected",(()=>this.emit("reconnected"))),this.connection.on("participantConnected",(e=>this.emit("participantConnected",e))),this.connection.on("participantDisconnected",(e=>this.emit("participantDisconnected",e))),this.connection.on("agentStateChanged",(e=>this.emit("agentStateChanged",e))),this.connection.on("connectionStateChanged",(e=>this.emit("connectionStateChanged",e))),this.connection.on("connectionError",(e=>{this.listenerCount("error")>0&&this.emit("error",e)})),this.audioManager.on("trackSubscribed",(e=>this.emit("trackSubscribed",e))),this.audioManager.on("trackUnsubscribed",(e=>this.emit("trackUnsubscribed",e))),this.audioManager.on("speaking",(()=>this.emit("speaking"))),this.audioManager.on("listening",(()=>this.emit("listening"))),this.audioManager.on("volumeChanged",(e=>this.emit("volumeChanged",e))),this.audioManager.on("error",(e=>{this.listenerCount("error")>0&&this.emit("error",e)})),this.audioManager.on("micMuted",(()=>this.emit("micMuted"))),this.audioManager.on("micUnmuted",(()=>this.emit("micUnmuted"))),this.analytics.on("connectionQualityChanged",(e=>this.emit("connectionQualityChanged",e))),this.analytics.on("audioPlaybackChanged",(e=>this.emit("audioPlaybackChanged",e))),this.analytics.on("analyticsUpdated",(e=>this.emit("analyticsUpdated",e))),this.toolRegistry.on("answerReceived",(e=>{this.logger.log("🔄 Forwarding answerReceived to external listeners",{source:"LiveKitManager",error:{answerPreview:e.substring(0,100),answerLength:e.length}}),this.emit("answerReceived",e)})),this.toolRegistry.on("transcriptionReceived",(e=>{this.logger.log("🔄 Forwarding transcriptionReceived to external listeners",{source:"LiveKitManager",error:{transcriptionPreview:e.substring(0,100),transcriptionLength:e.length}}),this.emit("transcriptionReceived",e)})),this.toolRegistry.on("customEvent",((e,t,i)=>this.emit("customEvent",e,t,i))),this.toolRegistry.on("dataReceived",((e,t)=>this.emit("dataReceived",e,t))),this.toolRegistry.on("toolsRegistered",(e=>this.emit("toolsRegistered",e)))},Zc=function(){const e=this.connection.room;if(!e)return;const t=[[fs.TrackSubscribed,(e,t,i)=>{this.logger.log("Track subscribed",{source:"LiveKitManager",error:{trackSid:e.sid,trackKind:e.kind,participantIdentity:i.identity,isMuted:t.isMuted}}),this.audioManager.handleTrackSubscribed(e,t,i)}],[fs.TrackUnsubscribed,(e,t,i)=>{this.logger.log("Track unsubscribed",{source:"LiveKitManager",error:{trackSid:e.sid,trackKind:e.kind,participantIdentity:i.identity}}),this.audioManager.handleTrackUnsubscribed(e,t,i)}],[fs.DataReceived,(e,t)=>{this.logger.log("🔔 RoomEvent.DataReceived triggered",{source:"LiveKitManager",error:{payloadSize:e.length,participantIdentity:t?.identity||"unknown",participantSid:t?.sid}}),this.toolRegistry.handleDataReceived(e,t?.identity)}],[fs.TranscriptionReceived,(e,t)=>{this.logger.log("🔔 RoomEvent.TranscriptionReceived triggered",{source:"LiveKitManager",error:{participantIdentity:t?.identity||"unknown",participantSid:t?.sid,isLocal:t?.isLocal,segmentCount:e.length,segments:e.map((e=>({text:e.text?.substring(0,50),final:e.final})))}}),this.toolRegistry.handleTranscriptionReceived(e,t?.identity)}],[fs.ConnectionQualityChanged,(e,t)=>{this.logger.log("Connection quality changed",{source:"LiveKitManager",error:{quality:e,participantIdentity:t.identity,isLocal:t.isLocal}}),this.analytics.handleConnectionQualityChanged(e,t)}],[fs.AudioPlaybackStatusChanged,e=>{this.logger.log("Audio playback status changed",{source:"LiveKitManager",error:{playing:e,state:e?"started":"stopped"}}),this.analytics.handleAudioPlaybackChanged(e)}],[fs.MediaDevicesError,e=>{this.logger.error("Media devices error",{source:"LiveKitManager",error:{message:e.message,name:e.name}}),this.emit("mediaDevicesError",e)}],[fs.LocalTrackPublished,e=>{this.logger.log("Local track published",{source:"LiveKitManager",error:{trackSid:e.trackSid,trackKind:e.kind,isMuted:e.isMuted}}),this.emit("localTrackPublished",{publication:e,track:e.track})}]];for(const[i,n]of t)e.on(i,n)},ed=function(){const e=this.connection.participants.size,t=this.audioManager.trackStats.size;this.logger.log("Updating analytics counts",{source:"LiveKitManager",error:{participants:e,tracks:t}}),this.analytics.updateCounts(e,t)};class gd{constructor(){this._wakeLock=null,this._wakeLock=null}async acquire(){if("wakeLock"in(e=navigator)&&"object"==typeof e.wakeLock)try{this._wakeLock=await navigator.wakeLock.request("screen"),this._wakeLock.addEventListener("release",(()=>{this._wakeLock=null}))}catch{}var e}async release(){if(null!==this._wakeLock)try{await this._wakeLock.release(),this._wakeLock=null}catch{}}isActive(){return null!==this._wakeLock}}class fd extends Error{constructor(e,t){super(e),this.name="HamsaApiError",this.messageKey=t}}class vd extends s.EventEmitter{constructor(e,{API_URL:t="https://api.tryhamsa.com",LIVEKIT_URL:i="wss://rtc.eu.tryhamsa.com",debug:n=!1}={}){super(),td.add(this),this.liveKitManager=null,this.jobId=null,this.userInitiatedEnd=!1,this.liveKitManager=null,this.apiKey=e,this.API_URL=t,this.LIVEKIT_URL=i,this.debug=n,this.logger=Va(n),this.jobId=null,this.wakeLockManager=new gd}setVolume(e){this.liveKitManager&&this.liveKitManager.setVolume(e)}getOutputVolume(){return this.liveKitManager?.audioManager.getOutputVolume()??vd.DEFAULT_OUTPUT_VOLUME}getJobId(){return this.jobId}getInputVolume(){return this.liveKitManager?.audioManager.getInputVolume()??vd.DEFAULT_INPUT_VOLUME}setMicMuted(e){this.liveKitManager&&this.liveKitManager.audioManager.setMicMuted(e)}isMicMuted(){return this.liveKitManager?.audioManager.isMicMuted()??!1}sendUserActivity(){this.liveKitManager?.isConnected&&this.logger.log("User activity detected - preventing agent interruption",{source:"HamsaVoiceAgent"})}sendContextualUpdate(e){this.liveKitManager?.isConnected&&this.logger.log("Sending contextual update",{source:"HamsaVoiceAgent",error:{context:e}})}getInputByteFrequencyData(){return this.liveKitManager?.audioManager.getInputByteFrequencyData()??new Uint8Array(0)}getOutputByteFrequencyData(){return this.liveKitManager?.audioManager.getOutputByteFrequencyData()??new Uint8Array(0)}enableAudioCapture(e){if(!this.liveKitManager)throw new Error("Cannot enable audio capture: not connected to agent");this.liveKitManager.audioManager.enableAudioCapture(e)}disableAudioCapture(){this.liveKitManager?.audioManager.disableAudioCapture()}async start({agentId:e,params:i={},voiceEnablement:n=!1,tools:s=[],userId:o,preferHeadphonesForIosDevices:r=!1,connectionDelay:a,disableWakeLock:c=!1,onAudioData:d,captureAudio:l}){try{this.logger.log("SDK initialized - disconnect debugging enabled",{source:"HamsaVoiceAgent"}),this.userInitiatedEnd=!1,this.logger.log("Starting conversation initialization",{source:"HamsaVoiceAgent",error:{agentId:e,voiceEnablement:n,toolsCount:s?.length??0,hasParams:Object.keys(i).length>0}});const o=await t(this,td,"m",od).call(this,e,i,n,s);this.logger.log("Creating LiveKitManager instance",{source:"HamsaVoiceAgent",error:{livekitUrl:this.LIVEKIT_URL,tokenLength:o.length,debug:this.debug}}),this.liveKitManager=new md(this.LIVEKIT_URL,o,s,this.debug),this.logger.log("LiveKitManager created, setting up event listeners",{source:"HamsaVoiceAgent"}),this.liveKitManager.on("error",(e=>{this.logger.error("LiveKitManager error event",{source:"HamsaVoiceAgent",error:e}),this.emit("error",e)})).on("connected",(()=>{this.logger.log("LiveKit connection established",{source:"HamsaVoiceAgent"}),l?(this.logger.log("Enabling audio capture via captureAudio options",{source:"HamsaVoiceAgent",error:{source:l.source,format:l.format}}),this.liveKitManager?.audioManager.enableAudioCapture(l)):d&&(this.logger.log("Enabling audio capture via onAudioData",{source:"HamsaVoiceAgent"}),this.liveKitManager?.audioManager.enableAudioCapture({source:"agent",format:"opus-webm",chunkSize:100,callback:d})),this.emit("start")})).on("transcriptionReceived",(e=>{this.logger.log("Transcription received from user",{source:"HamsaVoiceAgent",error:{length:e.length,preview:e.substring(0,50)}}),this.emit("transcriptionReceived",e)})).on("answerReceived",(e=>{this.logger.log("Answer received from agent",{source:"HamsaVoiceAgent",error:{length:e.length,preview:e.substring(0,50)}}),this.emit("answerReceived",e)})).on("speaking",(()=>{this.logger.log("Agent started speaking",{source:"HamsaVoiceAgent"}),this.emit("speaking")})).on("listening",(()=>{this.logger.log("Agent started listening",{source:"HamsaVoiceAgent"}),this.emit("listening")})).on("disconnected",(()=>{const e=Date.now();this.logger.log("disconnected event fired - room connection closed - TIMING",{source:"HamsaVoiceAgent",error:{timestamp:e,userInitiatedEnd:this.userInitiatedEnd}}),this.emit("callEnded");const t=Date.now();this.emit("closed"),this.logger.log("closed event emitted - TIMING",{source:"HamsaVoiceAgent",error:{timestamp:t,timeSinceDisconnected:t-e}}),this.userInitiatedEnd=!1})).on("trackSubscribed",(e=>{this.logger.log("Track subscribed",{source:"HamsaVoiceAgent",error:{kind:e.track?.kind,trackSid:e.track?.sid,participant:e.participant}}),this.emit("trackSubscribed",e)})).on("trackUnsubscribed",(e=>{this.logger.log("Track unsubscribed",{source:"HamsaVoiceAgent",error:{kind:e.track?.kind,trackSid:e.track?.sid,participant:e.participant}}),this.emit("trackUnsubscribed",e)})).on("localTrackPublished",(e=>{this.logger.log("Local track published",{source:"HamsaVoiceAgent",error:{kind:e.publication?.kind,trackSid:e.publication?.trackSid}}),this.emit("localTrackPublished",e)})).on("info",(e=>{this.logger.log("Info message received",{source:"HamsaVoiceAgent",error:{info:e}}),this.emit("info",e)})).on("reconnecting",(()=>{this.logger.warn("Connection reconnecting",{source:"HamsaVoiceAgent"}),this.emit("reconnecting")})).on("reconnected",(()=>{this.logger.log("Connection reconnected successfully",{source:"HamsaVoiceAgent"}),this.emit("reconnected")})).on("participantConnected",(e=>{this.logger.log("Participant connected",{source:"HamsaVoiceAgent",error:{identity:e.identity,sid:e.sid}}),this.emit("participantConnected",e)})).on("participantDisconnected",(e=>{this.logger.log("Participant disconnected",{source:"HamsaVoiceAgent",error:{identity:e.identity,sid:e.sid,hasAgentInIdentity:e.identity?.includes("agent"),remainingCount:this.liveKitManager?.connection.participants.size??0}}),this.emit("participantDisconnected",e)})).on("agentStateChanged",(e=>{this.logger.log("Agent state changed",{source:"HamsaVoiceAgent",error:{state:e}}),this.emit("agentStateChanged",e)})).on("connectionQualityChanged",(e=>{this.logger.log("Connection quality changed",{source:"HamsaVoiceAgent",error:{quality:e.quality,participant:e.participant}}),this.emit("connectionQualityChanged",e)})).on("connectionStateChanged",(e=>{this.logger.log("Connection state changed",{source:"HamsaVoiceAgent",error:{state:e}}),this.emit("connectionStateChanged",e)})).on("audioPlaybackChanged",(e=>{this.logger.log("Audio playback state changed",{source:"HamsaVoiceAgent",error:{playing:e}}),this.emit("audioPlaybackChanged",e)})).on("micMuted",(()=>{this.logger.log("Microphone muted",{source:"HamsaVoiceAgent"}),this.emit("micMuted")})).on("micUnmuted",(()=>{this.logger.log("Microphone unmuted",{source:"HamsaVoiceAgent"}),this.emit("micUnmuted")})).on("analyticsUpdated",(e=>this.emit("analyticsUpdated",e))).on("customEvent",((e,t,i)=>this.emit("customEvent",e,t,i))).on("dataReceived",((e,t)=>this.emit("dataReceived",e,t))),this.logger.log("Connecting to LiveKit room",{source:"HamsaVoiceAgent",error:{livekitUrl:this.LIVEKIT_URL}});const r=Date.now();await this.liveKitManager.connect();const a=Date.now()-r;this.logger.log("Connected to LiveKit room",{source:"HamsaVoiceAgent",error:{duration:`${a}ms`}}),this.logger.log("Acquiring screen wake lock",{source:"HamsaVoiceAgent"});try{await this.wakeLockManager.acquire(),this.logger.log("Screen wake lock acquired successfully",{source:"HamsaVoiceAgent"})}catch(e){this.logger.warn("Failed to acquire screen wake lock",{source:"HamsaVoiceAgent",error:{error:e instanceof Error?e.message:String(e)}})}this.logger.log("Call started successfully",{source:"HamsaVoiceAgent",error:{totalStartupTime:Date.now()-r+"ms",jobId:this.jobId}}),this.emit("callStarted",{jobId:this.jobId??""})}catch(e){if(this.logger.error("Failed to start call",{source:"HamsaVoiceAgent",error:{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,isHamsaApiError:e instanceof fd}}),this.listenerCount("error")>0)if(e instanceof fd)this.emit("error",e);else{const t=e instanceof Error?e.message:String(e);this.emit("error",new Error(`Failed to start call: ${t}`))}}}end(){const e=Date.now();this.logger.log("end() called - START DISCONNECT TIMING",{source:"HamsaVoiceAgent",error:{timestamp:e,userInitiatedEnd:this.userInitiatedEnd,isConnected:this.liveKitManager?.isConnected??!1,stack:new Error("Stack trace").stack}}),t(this,td,"m",id).call(this,e).then((()=>{const t=Date.now();this.logger.log("end() completed - END DISCONNECT TIMING",{source:"HamsaVoiceAgent",error:{timestamp:t,totalDuration:t-e}})})).catch((i=>{t(this,td,"m",sd).call(this,i,e)})),t(this,td,"m",nd).call(this)}pause(){this.liveKitManager&&(this.liveKitManager.pause(),this.wakeLockManager?.isActive()&&this.wakeLockManager.release().catch((e=>{})),this.emit("callPaused"))}resume(){this.liveKitManager&&(this.liveKitManager.resume(),this.wakeLockManager.acquire().catch((e=>{})),this.emit("callResumed"))}async getJobDetails(e=5,i=1e3,n=2){if(!this.jobId)throw new Error("Cannot fetch job details: jobId is not set. Start a conversation first.");const s=`${this.API_URL}/v1/voice-agents/conversation/${this.jobId}`,o={Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},r=new URLSearchParams({jobId:this.jobId});let a=i;const c=async(i=1)=>{try{const e=await fetch(`${s}?${r.toString()}`,{method:"GET",headers:o});if(!e.ok){const t=await e.text();throw new Error(`API Error: ${e.status} ${e.statusText} - ${t}`)}const t=await e.json();if("COMPLETED"===t.data.status)return t.data;throw new Error(`Job status is not COMPLETED: ${t.data.status}`)}catch(s){if(i<e)return await t(this,td,"m",ud).call(this,a),a*=n,c(i+1);throw new Error(`Failed to fetch job details after ${e} attempts: ${s instanceof Error?s.message:String(s)}`)}};return await c()}getConnectionStats(){return this.liveKitManager?this.liveKitManager.getConnectionStats():null}getAudioLevels(){return this.liveKitManager?this.liveKitManager.getAudioLevels():null}getPerformanceMetrics(){return this.liveKitManager?this.liveKitManager.getPerformanceMetrics():null}getParticipants(){return this.liveKitManager?this.liveKitManager.getParticipants():[]}getTrackStats(){return this.liveKitManager?this.liveKitManager.getTrackStats():null}getCallAnalytics(){return this.liveKitManager?this.liveKitManager.getCallAnalytics():null}getRoom(){return this.liveKitManager?.connection.getRoom()??null}getRemoteAudioTrack(){const e=this.liveKitManager?.connection.getRoom();if(e?.remoteParticipants)for(const t of e.remoteParticipants.values()){const e=Array.from(t.audioTrackPublications.values())[0];if(e?.track)return e.track}}}td=new WeakSet,id=async function(e){if(!this.liveKitManager)return;this.userInitiatedEnd=!0;const t=this.liveKitManager.connection.room?.name;if(t){const e=Date.now();this.logger.log("Calling room destroy API",{source:"HamsaVoiceAgent",error:{timestamp:e,roomName:t}});try{const i=await fetch(`${this.API_URL}/v1/voice-agents/room/destroy`,{method:"DELETE",headers:{Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({roomName:t})}),n=Date.now();if(i.ok){const t=await i.json();this.logger.log("Room destroy API succeeded",{source:"HamsaVoiceAgent",error:{timestamp:n,duration:n-e,success:t.success,message:t.message}})}else{const t=await i.text();this.logger.error("Room destroy API failed",{source:"HamsaVoiceAgent",error:{timestamp:n,duration:n-e,status:i.status,statusText:i.statusText,errorText:t}})}}catch(t){const i=Date.now();this.logger.error("Room destroy API threw error",{source:"HamsaVoiceAgent",error:{timestamp:i,duration:i-e,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0}})}}else this.logger.warn("Skipping room destroy API - missing roomName",{source:"HamsaVoiceAgent",error:{hasRoomName:!!t}});const i=Date.now();this.logger.log("Calling liveKitManager.disconnect()",{source:"HamsaVoiceAgent",error:{timestamp:i,timeSinceEndCalled:i-e}}),await this.liveKitManager.disconnect();const n=Date.now();this.logger.log("liveKitManager.disconnect() completed",{source:"HamsaVoiceAgent",error:{timestamp:n,disconnectCallDuration:n-i}}),this.emit("callEnded");const s=Date.now();this.logger.log("callEnded event emitted",{source:"HamsaVoiceAgent",error:{timestamp:s,totalTimeInEndMethod:s-e}})},nd=function(){this.wakeLockManager?.isActive()&&this.wakeLockManager.release().catch((e=>{}))},sd=function(e,t){if(this.logger.error("end() threw error",{source:"HamsaVoiceAgent",error:{error:e instanceof Error?e.message:String(e),timeSinceStart:Date.now()-t}}),this.listenerCount("error")>0)if(e instanceof fd)this.emit("error",e);else{const t=e instanceof Error?e.message:String(e);this.emit("error",new Error(`Failed to end call: ${t}`))}},od=async function(e,i,n,s){const o={Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},r=await t(this,td,"m",ad).call(this,e,i,o),a=r.liveKitAccessToken,c=t(this,td,"m",dd).call(this,a,r.jobId,e);return await t(this,td,"m",cd).call(this,{voiceAgentId:e,params:i,voiceEnablement:n,tools:s,headers:o,jobIdFromToken:c,tokenData:r}),this.jobId=c,a},rd=function(e,t,i=!1){try{const e=JSON.parse(t);if(e.message)throw new fd(e.message,e.messageKey)}catch(e){if(e instanceof fd)throw e}const n=i?`${e.status} ${e.statusText} - ${t}`:t;throw new fd(n)},ad=async function(e,i,n){this.logger.log("Fetching participant token from API",{source:"HamsaVoiceAgent",error:{voiceAgentId:e,apiUrl:this.API_URL,paramsCount:Object.keys(i).length}});const s=Date.now(),o=await fetch(`${this.API_URL}/v1/voice-agents/room/participant-token`,{method:"POST",headers:n,body:JSON.stringify({voiceAgentId:e,params:i})}),r=Date.now()-s;if(this.logger.log("Received API response for participant token",{source:"HamsaVoiceAgent",error:{status:o.status,ok:o.ok,duration:`${r}ms`}}),!o.ok){const e=await o.text();this.logger.error("API request failed for participant token",{source:"HamsaVoiceAgent",error:{status:o.status,statusText:o.statusText,errorText:e}}),t(this,td,"m",rd).call(this,o,e,!0)}const a=await o.json();if(!a?.success||!a?.data?.liveKitAccessToken)throw this.logger.error("Invalid token response structure",{source:"HamsaVoiceAgent",error:{success:a?.success,hasToken:!!a?.data?.liveKitAccessToken}}),new Error("Failed to get LiveKit access token");return this.logger.log("Successfully received LiveKit access token",{source:"HamsaVoiceAgent",error:{tokenLength:a.data.liveKitAccessToken.length,hasJobId:!!a.data.jobId,jobId:a.data.jobId}}),a.data},cd=async function(e){const{voiceAgentId:i,params:n,voiceEnablement:s,tools:o,headers:r,jobIdFromToken:a,tokenData:c}=e,d=o?.length>0?t(this,td,"m",ld).call(this,o):[],l={tools:d,voiceEnablement:s,voiceAgentId:i,params:n,jobId:a??c.jobId??i,channelType:"Web"};this.logger.log("Initializing conversation with API",{source:"HamsaVoiceAgent",error:{voiceAgentId:i,toolsCount:d.length,voiceEnablement:s,jobId:l.jobId,channelType:l.channelType}});const u=Date.now(),h=await fetch(`${this.API_URL}/v1/voice-agents/room/conversation-init`,{method:"POST",headers:r,body:JSON.stringify(l),redirect:"follow"}),p=Date.now()-u;if(this.logger.log("Received conversation init response",{source:"HamsaVoiceAgent",error:{status:h.status,ok:h.ok,duration:`${p}ms`}}),!h.ok){const e=await h.text();this.logger.error("Conversation initialization failed",{source:"HamsaVoiceAgent",error:{status:h.status,statusText:h.statusText,errorText:e}}),t(this,td,"m",rd).call(this,h,e,!1)}this.logger.log("Conversation initialized successfully",{source:"HamsaVoiceAgent"})},dd=function(e,t,i){this.logger.log("Parsing JWT token for jobId",{source:"HamsaVoiceAgent",error:{tokenPreview:e.substring(0,20),endpointJobId:t,voiceAgentId:i}});try{const t=function(e,t){if("string"!=typeof e)throw new o("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,n=e.split(".")[i];if("string"!=typeof n)throw new o(`Invalid token specified: missing part #${i+1}`);let s;try{s=r(n)}catch(e){throw new o(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new o(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e);this.logger.log("JWT token parsed successfully",{source:"HamsaVoiceAgent",error:{hasRoomConfig:!!t.roomConfig,hasAgents:!!t.roomConfig?.agents,agentsCount:t.roomConfig?.agents?.length??0}});const i=t?.roomConfig?.agents?.[0]?.metadata;if("string"==typeof i){const e=JSON.parse(i);if("string"==typeof e.jobId&&e.jobId.length>0)return this.logger.log("Extracted jobId from token metadata",{source:"HamsaVoiceAgent",error:{jobId:e.jobId}}),e.jobId}}catch(e){this.logger.warn("Failed to parse jobId from token, using fallback",{source:"HamsaVoiceAgent",error:{error:e instanceof Error?e.message:String(e)}})}const n=t??i;return this.logger.log("Using fallback jobId",{source:"HamsaVoiceAgent",error:{jobId:n,source:t?"endpoint":"voiceAgentId"}}),n},ld=function(e){return e.map((e=>({type:"function",function:{name:e.function_name,description:e.description,parameters:{type:"object",properties:e.parameters?.reduce(((e,t)=>(e[t.name]={type:t.type,description:t.description},e)),{})||{},required:e.required||[]},func_map:e.func_map}})))},ud=function(e){return new Promise((t=>setTimeout(t,e)))},vd.DEFAULT_OUTPUT_VOLUME=0,vd.DEFAULT_INPUT_VOLUME=0,e.HamsaApiError=fd,e.HamsaVoiceAgent=vd,e.default=vd,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|