@hamsa-ai/voice-agents-sdk 0.6.0-beta.4 → 0.6.0-beta.5

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.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";function e(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)}Object.defineProperty(exports,"__esModule",{value:!0}),"function"==typeof SuppressedError&&SuppressedError;var t,i={exports:{}};var n=function(){if(t)return i.exports;t=1;var e,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}i.exports=a,i.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}f(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&f(e,"error",t,i)}(e,r,{once:!0})}))},a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=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?a.defaultMaxListeners:e._maxListeners}function l(e,t,i,n){var r,s,a,o;if(c(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),a=s[t]),void 0===a)a=s[t]=i,++e._eventsCount;else if("function"==typeof a?a=s[t]=n?[i,a]:[a,i]:n?a.unshift(i):a.push(i),(r=d(e))>0&&a.length>r&&!a.warned){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=a.length,o=l,console&&console.warn&&console.warn(o)}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},r=u.bind(n);return r.listener=i,n.wrapFn=r,r}function p(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):g(r,r.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 r(s){n.once&&e.removeEventListener(t,r),i(s)}))}}return Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),a.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||s(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},a.prototype.getMaxListeners=function(){return d(this)},a.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,s=this._events;if(void 0!==s)n=n&&void 0===s.error;else if(!n)return!1;if(n){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)r(c,this,t);else{var d=c.length,l=g(c,d);for(i=0;i<d;++i)r(l[i],this,t)}return!0},a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)},a.prototype.once=function(e,t){return c(t),this.on(e,h(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,h(this,e,t)),this},a.prototype.removeListener=function(e,t){var i,n,r,s,a;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(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},a.prototype.listeners=function(e){return p(this,e,!0)},a.prototype.rawListeners=function(e){return p(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},a.prototype.listenerCount=m,a.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},i.exports}();class r extends Error{}function s(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)}r.prototype.name="InvalidTokenError";var o=Object.defineProperty,c=(e,t,i)=>((e,t,i)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class d{constructor(){c(this,"_locking"),c(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 l(e,t){if(!e)throw new Error(t)}function u(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 h(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 p(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 m=Symbol("@bufbuild/protobuf/enum-type");function g(e){const t=e[m];return l(t,"missing enum type on enum object"),t}function f(e,t,i,n){e[m]=v(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function v(e,t,i){const n=Object.create(null),r=Object.create(null),s=[];for(const e of t){const t=y(e);s.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:s,findName:e=>n[e],findNumber:e=>r[e]}}function 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 f(n,e,t),n}function y(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class b{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function T(){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 r=e>>>n,s=!(r>>>7==0&&0==t),a=255&(s?128|r:r);if(i.push(a),!s)return}const n=e>>>28&15|(7&t)<<4,r=!!(t>>3);if(i.push(255&(r?128|n:n)),r){for(let e=3;e<31;e+=7){const n=t>>>e,r=!(n>>>7==0),s=255&(r?128|n:n);if(i.push(s),!r)return}i.push(t>>>31&1)}}const C=4294967296;function w(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,r=0;function s(t,s){const a=Number(e.slice(t,s));r*=i,n=n*i+a,n>=C&&(r+=n/C|0,n%=C)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?P(n,r):R(n,r)}function E(e,t){var i=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=i.lo,(t=i.hi)<=2097151)return String(C*t+e);const n=16777215&(e>>>24|t<<8),r=t>>16&65535;let s=(16777215&e)+6777216*n+6710656*r,a=n+8147497*r,o=2*r;const c=1e7;return s>=c&&(a+=Math.floor(s/c),s%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+I(a)+I(s)}function R(e,t){return{lo:0|e,hi:0|t}}function P(e,t){return t=~t,e?e=1+~e:t+=1,R(e,t)}const I=e=>{const t=String(e);return"0000000".slice(t.length)+t};function M(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 D(){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 A=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>r||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>l(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>l(/^[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),w(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),w(e)),dec:(e,t)=>function(e,t){let i=R(e,t);const n=2147483648&i.hi;n&&(i=P(i.lo,i.hi));const r=E(i.lo,i.hi);return n?"-"+r:r}(e,t),uDec:(e,t)=>E(e,t)}}();var _,L,O;function x(e,t,i){if(t===i)return!0;if(e==_.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case _.UINT64:case _.FIXED64:case _.INT64:case _.SFIXED64:case _.SINT64:return t==i}return!1}function N(e,t){switch(e){case _.BOOL:return!1;case _.UINT64:case _.FIXED64:case _.INT64:case _.SFIXED64:case _.SINT64:return 0==t?A.zero:"0";case _.DOUBLE:case _.FLOAT:return 0;case _.BYTES:return new Uint8Array(0);case _.STRING:return"";default:return 0}}function U(e,t){switch(e){case _.BOOL:return!1===t;case _.STRING:return""===t;case _.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function F(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i<t;i++)n[i]=e[i];return n}function j(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function B(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var n,r,s,a,o=[],c=!0,d=!1;try{if(s=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(n=s.call(i)).done)&&(o.push(n.value),o.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(d)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return F(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?F(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!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"}(_||(_={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(L||(L={})),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"}(O||(O={}));class V{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(h(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return u(e),M(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){p(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){h(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){u(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return u(e),M(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=A.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=A.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=A.enc(e);return S(t.lo,t.hi,this.buf),this}sint64(e){let t=A.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=A.uEnc(e);return S(t.lo,t.hi,this.buf),this}}class q{constructor(e,t){this.varint64=T,this.uint32=D,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 O.Varint:for(;128&this.buf[this.pos++];);break;case O.Bit64:this.pos+=4;case O.Bit32:this.pos+=4;break;case O.LengthDelimited:let i=this.uint32();this.pos+=i;break;case O.StartGroup:for(;;){const e=B(this.tag(),2),i=e[0],n=e[1];if(n===O.EndGroup){if(void 0!==t&&i!==t)throw new Error("invalid end group tag");break}this.skip(n,i)}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 A.dec(...this.varint64())}uint64(){return A.uDec(...this.varint64())}sint64(){let e=B(this.varint64(),2),t=e[0],i=e[1],n=-(1&t);return t=(t>>>1|(1&i)<<31)^n,i=i>>>1^n,A.dec(t,i)}bool(){let e=B(this.varint64(),2),t=e[0],i=e[1];return 0!==t||0!==i}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return A.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return A.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 K(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 N(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 H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),W=[];for(let e=0;e<H.length;e++)W[H[e].charCodeAt(0)]=e;W["-".charCodeAt(0)]=H.indexOf("+"),W["_".charCodeAt(0)]=H.indexOf("/");const z={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),r=0,s=0,a=0;for(let t=0;t<e.length;t++){if(i=W[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=i,s=1;break;case 1:n[r++]=a<<2|(48&i)>>4,a=i,s=2;break;case 2:n[r++]=(15&a)<<4|(60&i)>>2,a=i,s=3;break;case 3:n[r++]=(3&a)<<6|i,s=0}}if(1==s)throw Error("invalid base64 string.");return n.subarray(0,r)},enc(e){let t,i="",n=0,r=0;for(let s=0;s<e.length;s++)switch(t=e[s],n){case 0:i+=H[t>>2],r=(3&t)<<4,n=1;break;case 1:i+=H[r|t>>4],r=(15&t)<<2,n=2;break;case 2:i+=H[r|t>>6],i+=H[63&t],n=0}return n&&(i+=H[r],i+="=",1==n&&(i+="=")),i}};function G(e,t,i){Y(t,e);const n=t.runtime.bin.makeReadOptions(i),r=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),s=B(K(t),2),a=s[0],o=s[1];for(const e of r)t.runtime.bin.readField(a,n.readerFactory(e.data),t.field,e.wireType,n);return o()}function J(e,t,i,n){Y(t,e);const r=t.runtime.bin.makeReadOptions(n),s=t.runtime.bin.makeWriteOptions(n);if(Q(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const a=s.writerFactory();let o=t.field;o.opt||o.repeated||"enum"!=o.kind&&"scalar"!=o.kind||(o=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(o,i,a,s);const c=r.readerFactory(a.finish());for(;c.pos<c.len;){const t=B(c.tag(),2),i=t[0],n=t[1],r=c.skip(n,i);e.getType().runtime.bin.onUnknownField(e,i,n,r)}}function Q(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 Y(e,t){l(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function $(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:!U(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function X(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?N(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Z(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(b.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 ee(e,t){return Z(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}_.DOUBLE,_.FLOAT,_.INT64,_.UINT64,_.INT32,_.UINT32,_.BOOL,_.STRING,_.BYTES;const te={ignoreUnknownFields:!1},ie={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ne(e){return e?Object.assign(Object.assign({},te),e):te}function re(e){return e?Object.assign(Object.assign({},ie),e):ie}const se=Symbol(),ae=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 ce(e,t,i,n,r){let s=i.localName;if(i.repeated){if(l("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const a=e[s];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(oe(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=ue(i.T,e,n.ignoreUnknownFields,!0);t!==ae&&a.push(t);break;case"scalar":try{a.push(le(i.T,e,i.L,!0))}catch(t){let n="cannot decode field ".concat(r.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(r.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const o=e[s];for(const e of Object.entries(t)){var a=B(e,2);const s=a[0],c=a[1];if(null===c)throw new Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: map value null"));let d;try{d=de(i.K,s)}catch(e){let n="cannot decode map key for field ".concat(r.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":o[d]=i.V.T.fromJson(c,n);break;case"enum":const e=ue(i.V.T,c,n.ignoreUnknownFields,!0);e!==ae&&(o[d]=e);break;case"scalar":try{o[d]=le(i.V.T,c,L.BIGINT,!0)}catch(e){let n="cannot decode map value for field ".concat(r.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:s},s="value"),i.kind){case"message":const a=i.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let o=e[s];Z(o)?o.fromJson(t,n):(e[s]=o=a.fromJson(t,n),a.fieldWrapper&&!i.oneof&&(e[s]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=ue(i.T,t,n.ignoreUnknownFields,!1);switch(c){case se:X(i,e);break;case ae:break;default:e[s]=c}break;case"scalar":try{const n=le(i.T,t,i.L,!1);if(n===se)X(i,e);else e[s]=n}catch(e){let n="cannot decode field ".concat(r.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 de(e,t){if(e===_.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return le(e,t,L.BIGINT,!0).toString()}function le(e,t,i,n){if(null===t)return n?N(e,i):se;switch(e){case _.DOUBLE:case _.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==_.FLOAT&&p(n),n;case _.INT32:case _.FIXED32:case _.SFIXED32:case _.SINT32:case _.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==_.UINT32||e==_.FIXED32?h(r):u(r),r;case _.INT64:case _.SFIXED64:case _.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const s=A.parse(t);return i?s.toString():s;case _.FIXED64:case _.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=A.uParse(t);return i?a.toString():a;case _.BOOL:if("boolean"!=typeof t)break;return t;case _.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case _.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return z.dec(t)}throw new Error}function ue(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:se;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 ae}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(oe(t)))}function he(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function pe(e,t,i){if("map"==e.kind){l("object"==typeof t&&null!=t);const a={},o=Object.entries(t);switch(e.V.kind){case"scalar":for(const t of o){var n=B(t,2);const i=n[0],r=n[1];a[i.toString()]=ge(e.V.T,r)}break;case"message":for(const e of o){var r=B(e,2);const t=r[0],n=r[1];a[t.toString()]=n.toJson(i)}break;case"enum":const t=e.V.T;for(const e of o){var s=B(e,2);const n=s[0],r=s[1];a[n.toString()]=me(t,r,i.enumAsInteger)}}return i.emitDefaultValues||o.length>0?a:void 0}if(e.repeated){l(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(ge(e.T,t[i]));break;case"enum":for(let r=0;r<t.length;r++)n.push(me(e.T,t[r],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 ge(e.T,t);case"enum":return me(e.T,t,i.enumAsInteger);case"message":return ee(e.T,t).toJson(i)}}function me(e,t,i){var n;if(l("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const r=e.findNumber(t);return null!==(n=null==r?void 0:r.name)&&void 0!==n?n:t}function ge(e,t){switch(e){case _.INT32:case _.SFIXED32:case _.SINT32:case _.FIXED32:case _.UINT32:return l("number"==typeof t),t;case _.FLOAT:case _.DOUBLE:return l("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case _.STRING:return l("string"==typeof t),t;case _.BOOL:return l("boolean"==typeof t),t;case _.UINT64:case _.FIXED64:case _.INT64:case _.SFIXED64:case _.SINT64:return l("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case _.BYTES:return l(t instanceof Uint8Array),z.enc(t)}}const fe=Symbol("@bufbuild/protobuf/unknown-fields"),ve={readUnknownFields:!0,readerFactory:e=>new q(e)},ke={writeUnknownFields:!0,writerFactory:()=>new V};function ye(e){return e?Object.assign(Object.assign({},ve),e):ve}function be(e){return e?Object.assign(Object.assign({},ke),e):ke}function Te(e,t,i,n,r){let s=i.repeated,a=i.localName;switch(i.oneof&&((e=e[i.oneof.localName]).case!=a&&delete e.value,e.case=a,a="value"),i.kind){case"scalar":case"enum":const o="enum"==i.kind?_.INT32:i.T;let c=we;if("scalar"==i.kind&&i.L>0&&(c=Ce),s){let i=e[a];if(n==O.LengthDelimited&&o!=_.STRING&&o!=_.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,o))}else i.push(c(t,o))}else e[a]=c(t,o);break;case"message":const d=i.T;s?e[a].push(Se(t,new d,r,i)):Z(e[a])?Se(t,e[a],r,i):(e[a]=Se(t,new d,r,i),!d.fieldWrapper||i.oneof||i.repeated||(e[a]=d.fieldWrapper.unwrapField(e[a])));break;case"map":let l=function(e,t,i){const n=t.uint32(),r=t.pos+n;let s,a;for(;t.pos<r;){switch(B(t.tag(),1)[0]){case 1:s=we(t,e.K);break;case 2:switch(e.V.kind){case"scalar":a=we(t,e.V.T);break;case"enum":a=t.int32();break;case"message":a=Se(t,new e.V.T,i,void 0)}}}void 0===s&&(s=N(e.K,L.BIGINT));"string"!=typeof s&&"number"!=typeof s&&(s=s.toString());if(void 0===a)switch(e.V.kind){case"scalar":a=N(e.V.T,L.BIGINT);break;case"enum":a=e.V.T.values[0].no;break;case"message":a=new e.V.T}return[s,a]}(i,t,r),u=B(l,2),h=u[0],p=u[1];e[a][h]=p}}function Se(e,t,i,n){const r=t.getType().runtime.bin,s=null==n?void 0:n.delimited;return r.readMessage(t,e,s?n.no:e.uint32(),i,s),t}function Ce(e,t){const i=we(e,t);return"bigint"==typeof i?i.toString():i}function we(e,t){switch(t){case _.STRING:return e.string();case _.BOOL:return e.bool();case _.DOUBLE:return e.double();case _.FLOAT:return e.float();case _.INT32:return e.int32();case _.INT64:return e.int64();case _.UINT64:return e.uint64();case _.FIXED64:return e.fixed64();case _.BYTES:return e.bytes();case _.FIXED32:return e.fixed32();case _.SFIXED32:return e.sfixed32();case _.SFIXED64:return e.sfixed64();case _.SINT64:return e.sint64();case _.UINT32:return e.uint32();case _.SINT32:return e.sint32()}}function Ee(e,t,i,n){l(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let a="enum"==e.kind?_.INT32:e.T;if(r)if(l(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,O.LengthDelimited).fork();let r=B(Me(t),2)[1];for(let t=0;t<n.length;t++)e[r](n[t]);e.join()}(i,a,e.no,t);else for(const n of t)Ie(i,a,e.no,n);else Ie(i,a,e.no,t);break;case"message":if(r){l(Array.isArray(t));for(const r of t)Pe(i,n,e,r)}else Pe(i,n,e,t);break;case"map":l("object"==typeof t&&null!=t);for(const r of Object.entries(t)){var s=B(r,2);Re(i,n,e,s[0],s[1])}}}function Re(e,t,i,n,r){e.tag(i.no,O.LengthDelimited),e.fork();let s=n;switch(i.K){case _.INT32:case _.FIXED32:case _.UINT32:case _.SFIXED32:case _.SINT32:s=Number.parseInt(n);break;case _.BOOL:l("true"==n||"false"==n),s="true"==n}switch(Ie(e,i.K,1,s),i.V.kind){case"scalar":Ie(e,i.V.T,2,r);break;case"enum":Ie(e,_.INT32,2,r);break;case"message":l(void 0!==r),e.tag(2,O.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Pe(e,t,i,n){const r=ee(i.T,n);i.delimited?e.tag(i.no,O.StartGroup).raw(r.toBinary(t)).tag(i.no,O.EndGroup):e.tag(i.no,O.LengthDelimited).bytes(r.toBinary(t))}function Ie(e,t,i,n){l(void 0!==n);let r=B(Me(t),2),s=r[0],a=r[1];e.tag(i,s)[a](n)}function Me(e){let t=O.Varint;switch(e){case _.BYTES:case _.STRING:t=O.LengthDelimited;break;case _.DOUBLE:case _.FIXED64:case _.SFIXED64:t=O.Bit64;break;case _.FIXED32:case _.SFIXED32:case _.FLOAT:t=O.Bit32}return[t,_[e].toLowerCase()]}function De(e){if(void 0===e)return e;if(Z(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ae(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class _e{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 Le(e,t){const i=xe(e);return t?i:Be(je(i))}const Oe=xe;function xe(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}const Ne=new Set(["constructor","toString","toJSON","valueOf"]),Ue=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Fe=e=>"".concat(e,"$"),je=e=>Ue.has(e)?Fe(e):e,Be=e=>Ne.has(e)?Fe(e):e;class Ve{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=Le(e,!1)}addField(e){l(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 qe=(Ke=e=>new _e(e,(e=>function(e){var t,i,n,r,s,a;const o=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Le(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Oe(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:L.BIGINT),e.delimited=null!==(r=d.delimited)&&void 0!==r&&r,e.req=null!==(s=d.req)&&void 0!==s&&s,e.opt=null!==(a=d.opt)&&void 0!==a&&a,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=_.BYTES&&d.T!=_.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Ve(t)),e.oneof=c,c.addField(e)}o.push(e)}return o}(e))),He=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]=N(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ne,makeWriteOptions:re,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 r=new Map,s=i.typeRegistry;for(const o of Object.entries(t)){var a=B(o,2);const t=a[0],c=a[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const i=r.get(d.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(i,'", "').concat(t,'"'));r.set(d.oneof,t)}ce(n,c,d,i,e)}else{let r=!1;if((null==s?void 0:s.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const a=s.findExtension(t.substring(1,t.length-1));if(a&&a.extendee.typeName==e.typeName){r=!0;const e=B(K(a),2),t=e[0],s=e[1];ce(t,c,a.field,i,a),J(n,a,s(),i)}}if(!r&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let r;try{for(r of i.fields.byNumber()){if(!$(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!he(r))continue}const i=pe(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t);void 0!==i&&(n[t.useProtoFieldName?r.name:r.jsonName]=i)}const s=t.typeRegistry;if(null==s?void 0:s.findExtensionFor)for(const r of i.runtime.bin.listUnknownFields(e)){const a=s.findExtensionFor(i.typeName,r.no);if(a&&Q(e,a)){const i=G(e,a,t),r=pe(a.field,i,t);void 0!==r&&(n[a.field.jsonName]=r)}}}catch(e){const t=r?"cannot encode field ".concat(i.typeName,".").concat(r.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)=>le(e,t,null!=i?i:L.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||U(e,t)?ge(e,t):void 0},debug:oe},bin:{makeReadOptions:ye,makeWriteOptions:be,listUnknownFields(e){var t;return null!==(t=e[fe])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[fe]},writeUnknownFields(e,t){const i=e[fe];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const r=e;Array.isArray(r[fe])||(r[fe]=[]),r[fe].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,r){const s=e.getType(),a=r?t.len:t.pos+i;let o,c;for(;t.pos<a;){var d=B(t.tag(),2);if(o=d[0],c=d[1],!0===r&&c==O.EndGroup)break;const i=s.fields.find(o);if(i)Te(e,t,i,c,n);else{const i=t.skip(c,o);n.readUnknownFields&&this.onUnknownField(e,o,c,i)}}if(r&&(c!=O.EndGroup||o!==i))throw new Error("invalid end group tag")},readField:Te,writeMessage(e,t,i){const n=e.getType();for(const r of n.fields.byNumber())if($(r,e))Ee(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t,i);else if(r.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Ee(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:f,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const r of i.fields.byMember()){const i=r.localName,s=t,a=e;if(null!=a[i])switch(r.kind){case"oneof":const e=a[i].case;if(void 0===e)continue;const t=r.findField(e);let o=a[i].value;t&&"message"==t.kind&&!Z(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===_.BYTES&&(o=Ae(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let c=a[i];r.T===_.BYTES&&(c=r.repeated?c.map(Ae):Ae(c)),s[i]=c;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===_.BYTES)for(const e of Object.entries(a[i])){var n=B(e,2);const t=n[0],r=n[1];s[i][t]=Ae(r)}else Object.assign(s[i],a[i]);break;case"message":const e=r.V.T;for(const t of Object.keys(a[i])){let n=a[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const d=r.T;if(r.repeated)s[i]=a[i].map((e=>Z(e,d)?e:new d(e)));else{const e=a[i];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?s[i]=Ae(e):s[i]=e:s[i]=Z(e,d)?e:new d(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,r[i])));case"scalar":return n.every(((t,i)=>x(e.T,t,r[i])));case"enum":return n.every(((e,t)=>x(_.INT32,e,r[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=n,i=r;return e.T.fieldWrapper&&(void 0===t||Z(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===i||Z(i)||(i=e.T.fieldWrapper.wrapField(i))),e.T.equals(t,i);case"enum":return x(_.INT32,n,r);case"scalar":return x(e.T,n,r);case"oneof":if(n.case!==r.case)return!1;const s=e.findField(n.case);if(void 0===s)return!0;switch(s.kind){case"message":return s.T.equals(n.value,r.value);case"enum":return x(_.INT32,n.value,r.value);case"scalar":return x(s.T,n.value,r.value)}throw new Error("oneof cannot contain ".concat(s.kind));case"map":const a=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return a.every((e=>t.equals(n[e],r[e])));case"enum":return a.every((e=>x(_.INT32,n[e],r[e])));case"scalar":const i=e.V.T;return a.every((e=>x(i,n[e],r[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const i of t.fields.byMember()){const t=e[i.localName];let s;if(i.repeated)s=t.map(De);else if("map"==i.kind){s=n[i.localName];for(const e of Object.entries(t)){var r=B(e,2);const t=r[0],i=r[1];s[t]=De(i)}}else s="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:De(t.value)}:{case:void 0}:De(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:Ke,initFields:He}),makeMessageType(e,t,i){return function(e,t,i,n){var r;const s=null!==(r=null==n?void 0:n.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),a={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(a.prototype,new b),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new a).fromBinary(e,t),fromJson:(e,t)=>(new a).fromJson(e,t),fromJsonString:(e,t)=>(new a).fromJsonString(e,t),equals:(t,i)=>e.util.equals(a,t,i)}),a}(this,e,t,i)},makeEnum:k,makeEnumType:v,getEnumType:g,makeExtension(e,t,i){return function(e,t,i,n){let r;return{typeName:t,extendee:i,get field(){if(!r){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),r=e.util.newFieldList([i]).list()[0]}return r},runtime:e}}(this,e,t,i)}});var Ke,He;class We extends b{constructor(e){super(),this.seconds=A.zero,this.nanos=0,qe.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(qe.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=A.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 We.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new We({seconds:A.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new We).fromBinary(e,t)}static fromJson(e,t){return(new We).fromJson(e,t)}static fromJsonString(e,t){return(new We).fromJsonString(e,t)}static equals(e,t){return qe.util.equals(We,e,t)}}We.runtime=qe,We.typeName="google.protobuf.Timestamp",We.fields=qe.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const ze=qe.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:We},{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:Qe,repeated:!0}])),Ge=qe.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:Je,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Je=qe.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:We},{no:3,name:"value",kind:"scalar",T:2}])),Qe=qe.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:We},{no:7,name:"normalized_end_timestamp",kind:"message",T:We,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Ye=qe.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),$e=qe.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Xe=qe.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"}]),Ze=qe.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),et=qe.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),tt=qe.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),it=qe.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"},{no:16,name:"AGENT_ERROR"}]),nt=qe.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"}]),rt=qe.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),st=qe.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"}]),at=qe.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"}]),ot=qe.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:ct,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:Wt}])),ct=qe.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),dt=qe.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:qe.getEnumType(Xe),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}])),lt=qe.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:qe.getEnumType(ut)},{no:4,name:"tracks",kind:"message",T:ft,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:dt},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:qe.getEnumType(ht)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:qe.getEnumType(it)},{no:18,name:"kind_details",kind:"enum",T:qe.getEnumType(pt),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:vt,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5}])),ut=qe.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ht=qe.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),pt=qe.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"}]),mt=qe.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),gt=qe.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:yt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:qe.getEnumType(bt)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),ft=qe.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:qe.getEnumType($e)},{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:qe.getEnumType(Xe)},{no:10,name:"layers",kind:"message",T:yt,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:gt,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:qe.getEnumType(mt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Wt},{no:19,name:"audio_features",kind:"enum",T:qe.getEnumType(st),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:qe.getEnumType(Ye)},{no:21,name:"packet_trailer_features",kind:"enum",T:qe.getEnumType(at),repeated:!0}])),vt=qe.makeMessageType("livekit.DataTrackInfo",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:qe.getEnumType(mt)}])),kt=qe.makeMessageType("livekit.DataTrackSubscriptionOptions",(()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}])),yt=qe.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:qe.getEnumType(Ze)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}])),bt=qe.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),Tt=qe.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:qe.getEnumType(St)},{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:Pt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Et,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:It,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Mt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:ze,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:At,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:_t,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Lt,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ot,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Qt,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Yt,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:$t,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Ct,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),St=qe.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Ct=qe.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:qe.getEnumType(mt)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}])),wt=qe.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Pt,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:At,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:_t,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Lt,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Ot,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Qt,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Yt,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:$t,oneof:"value"}])),Et=qe.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Rt,repeated:!0}])),Rt=qe.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}])),Pt=qe.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}])),It=qe.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Mt=qe.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:Dt,repeated:!0}])),Dt=qe.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}])),At=qe.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}])),_t=qe.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},{no:6,name:"compressed_payload",kind:"scalar",T:12}])),Lt=qe.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Ot=qe.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:xt,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}])),xt=qe.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}])),Nt=qe.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Ut=qe.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:qe.getEnumType(Ft)},{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}])),Ft=qe.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),jt=qe.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:qe.getEnumType(Bt)},{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},{no:12,name:"client_protocol",kind:"scalar",T:5},{no:13,name:"capabilities",kind:"enum",T:qe.getEnumType(Vt),repeated:!0}])),Bt=qe.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"}]),Vt=qe.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"}]),qt=qe.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Kt},{no:2,name:"screen",kind:"message",T:Kt},{no:3,name:"resume_connection",kind:"enum",T:qe.getEnumType(tt)},{no:4,name:"disabled_codecs",kind:"message",T:Ht},{no:5,name:"force_relay",kind:"enum",T:qe.getEnumType(tt)}])),Kt=qe.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:qe.getEnumType(tt)}])),Ht=qe.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ct,repeated:!0},{no:2,name:"publish",kind:"message",T:ct,repeated:!0}])),Wt=qe.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),zt=qe.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Gt=qe.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:qe.getEnumType(zt)},{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"}),Jt=qe.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Qt=qe.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:qe.getEnumType(mt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Gt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Jt,oneof:"content_header"}]),{localName:"DataStream_Header"}),Yt=qe.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"}),$t=qe.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"}),Xt=qe.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Zt=qe.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),ei=qe.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),ti=qe.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ii=qe.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:ki,oneof:"message"},{no:2,name:"answer",kind:"message",T:ki,oneof:"message"},{no:3,name:"trickle",kind:"message",T:hi,oneof:"message"},{no:4,name:"add_track",kind:"message",T:si,oneof:"message"},{no:5,name:"mute",kind:"message",T:pi,oneof:"message"},{no:6,name:"subscription",kind:"message",T:bi,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ci,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ri,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Ii,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:qi,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Wi,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ji,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Mi,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Qi,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:wi,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Ei,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:ai,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:ci,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Ti,oneof:"message"}])),ni=qe.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:mi,oneof:"message"},{no:2,name:"answer",kind:"message",T:ki,oneof:"message"},{no:3,name:"offer",kind:"message",T:ki,oneof:"message"},{no:4,name:"trickle",kind:"message",T:hi,oneof:"message"},{no:5,name:"update",kind:"message",T:yi,oneof:"message"},{no:6,name:"track_published",kind:"message",T:fi,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ri,oneof:"message"},{no:9,name:"mute",kind:"message",T:pi,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ai,oneof:"message"},{no:11,name:"room_update",kind:"message",T:_i,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Oi,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Ni,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ji,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Ki,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:vi,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:gi,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Yi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Zi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:en,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:nn,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Hi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:cn,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Bi,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:oi,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:di,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:li,oneof:"message"}])),ri=qe.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:yt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:qe.getEnumType(bt)}])),si=qe.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:qe.getEnumType($e)},{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:qe.getEnumType(Xe)},{no:9,name:"layers",kind:"message",T:yt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ri,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:qe.getEnumType(mt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:qe.getEnumType(Ye)},{no:17,name:"audio_features",kind:"enum",T:qe.getEnumType(st),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:qe.getEnumType(at),repeated:!0}])),ai=qe.makeMessageType("livekit.PublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:qe.getEnumType(mt)}])),oi=qe.makeMessageType("livekit.PublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:vt}])),ci=qe.makeMessageType("livekit.UnpublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}])),di=qe.makeMessageType("livekit.UnpublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:vt}])),li=qe.makeMessageType("livekit.DataTrackSubscriberHandles",(()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:ui}}])),ui=qe.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",(()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}]),{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),hi=qe.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:qe.getEnumType(Zt)},{no:3,name:"final",kind:"scalar",T:8}])),pi=qe.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),mi=qe.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:ot},{no:2,name:"participant",kind:"message",T:lt},{no:3,name:"other_participants",kind:"message",T:lt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Di,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:qt},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Ut},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ct,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),gi=qe.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Di,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:qt},{no:3,name:"server_info",kind:"message",T:Ut},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),fi=qe.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ft}])),vi=qe.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),ki=qe.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}])),yi=qe.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:lt,repeated:!0}])),bi=qe.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:Nt,repeated:!0}])),Ti=qe.makeMessageType("livekit.UpdateDataSubscription",(()=>[{no:1,name:"updates",kind:"message",T:Si,repeated:!0}])),Si=qe.makeMessageType("livekit.UpdateDataSubscription.Update",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:kt}]),{localName:"UpdateDataSubscription_Update"}),Ci=qe.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:qe.getEnumType(Ze)},{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}])),wi=qe.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:qe.getEnumType(st),repeated:!0}])),Ei=qe.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}])),Ri=qe.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:qe.getEnumType(it)},{no:3,name:"action",kind:"enum",T:qe.getEnumType(Pi)},{no:4,name:"regions",kind:"message",T:$i}])),Pi=qe.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Ii=qe.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:yt,repeated:!0}])),Mi=qe.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}])),Di=qe.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}])),Ai=qe.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Rt,repeated:!0}])),_i=qe.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:ot}])),Li=qe.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:qe.getEnumType(et)},{no:3,name:"score",kind:"scalar",T:2}])),Oi=qe.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Li,repeated:!0}])),xi=qe.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:qe.getEnumType(ei)}])),Ni=qe.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:xi,repeated:!0}])),Ui=qe.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:qe.getEnumType(Ze)},{no:2,name:"enabled",kind:"scalar",T:8}])),Fi=qe.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Ui,repeated:!0}])),ji=qe.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Ui,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Fi,repeated:!0}])),Bi=qe.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Xt,repeated:!0}])),Vi=qe.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}])),qi=qe.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Vi,repeated:!0}])),Ki=qe.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}])),Hi=qe.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:ot},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:lt},{no:4,name:"other_participants",kind:"message",T:lt,repeated:!0}])),Wi=qe.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:ki},{no:2,name:"subscription",kind:"message",T:bi},{no:3,name:"publish_tracks",kind:"message",T:fi,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Gi,repeated:!0},{no:5,name:"offer",kind:"message",T:ki},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:zi,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:oi,repeated:!0}])),zi=qe.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Gi=qe.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:qe.getEnumType(Zt)}])),Ji=qe.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:qe.getEnumType(ti),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"}])),Qi=qe.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Yi=qe.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),$i=qe.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Xi,repeated:!0}])),Xi=qe.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}])),Zi=qe.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:qe.getEnumType(rt)}])),en=qe.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:qe.getEnumType(tn)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:hi,oneof:"request"},{no:5,name:"add_track",kind:"message",T:si,oneof:"request"},{no:6,name:"mute",kind:"message",T:pi,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Mi,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:wi,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Ei,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:ai,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:ci,oneof:"request"}])),tn=qe.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),nn=qe.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),rn=qe.makeMessageType("livekit.ConnectionSettings",(()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}])),sn=qe.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:jt},{no:2,name:"connection_settings",kind:"message",T:rn},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:si,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:ki},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:qe.getEnumType(nt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Wi}])),an=qe.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:qe.getEnumType(on)},{no:2,name:"join_request",kind:"scalar",T:12}])),on=qe.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),cn=qe.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]));function dn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ln,un={exports:{}};var hn,pn,mn,gn,fn,vn=(ln||(ln=1,pn=un.exports,mn=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"],r={},s=null;function a(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),r=0;r<n.length;r++){var s=n[r];this[s]=r<i?e:this.methodFactory(s,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,r,s){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?o:void 0!==console[n]?a(console,n):void 0!==console.log?a(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var a,o,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+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!=o?o:a},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(a=m(s.getLevel())),c.call(u),s===u)for(var e in r)r[e].rebuild()},a=m(s?s.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(s=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=r[e];return t||(t=r[e]=new u(e,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return r},s.default=s,s},(hn=un).exports?hn.exports=mn():pn.log=mn()),un.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"}(gn||(gn={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",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",e.DataTracks="livekit-data-tracks"}(fn||(fn={}));let kn=vn.getLogger(fn.Default);function yn(e,t){const i=vn.getLogger(e);return i.setDefaultLevel(kn.getLevel()),t?function(e,t){const i=i=>(n,r)=>{const s=t(),a=s||r?Object.assign(Object.assign({},s),r):void 0;e[i](n,a)},n=Object.create(e);return n.trace=i("trace"),n.debug=i("debug"),n.info=i("info"),n.warn=i("warn"),n.error=i("error"),n}(i,t):i}Object.values(fn).map((e=>vn.getLogger(e))),kn.setDefaultLevel(gn.info);const bn=vn.getLogger(fn.E2EE),Tn=7e3,Sn=[0,300,1200,2700,4800,Tn,Tn,Tn,Tn,Tn];function Cn(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{c(n.next(e))}catch(e){s(e)}}function o(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}c((n=n.apply(e,t||[])).next())}))}function wn(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 En(e){return this instanceof En?(this.v=e,this):new En(e)}function Rn(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,r=i.apply(e,t||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",(function(e){return function(t){return Promise.resolve(t).then(e,d)}})),n[Symbol.asyncIterator]=function(){return this},n;function a(e,t){r[e]&&(n[e]=function(t){return new Promise((function(i,n){s.push([e,t,i,n])>1||o(e,t)}))},t&&(n[e]=t(n[e])))}function o(e,t){try{(i=r[e](t)).value instanceof En?Promise.resolve(i.value.v).then(c,d):l(s[0][2],i)}catch(e){l(s[0][3],e)}var i}function c(e){o("next",e)}function d(e){o("throw",e)}function l(e,t){e(t),s.shift(),s.length&&o(s[0][0],s[0][1])}}function Pn(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=wn(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,r){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,r,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var In,Mn={exports:{}};var Dn=function(){if(In)return Mn.exports;In=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 r(){r.init.call(this)}Mn.exports=r,Mn.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}m(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,r,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var r,s,c,d;if(a(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),c=s[t]),void 0===c)c=s[t]=i,++e._eventsCount;else if("function"==typeof c?c=s[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(r=o(e))>0&&c.length>r&&!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},r=d.bind(n);return r.listener=i,n.wrapFn=r,r}function u(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):p(r,r.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 r(s){n.once&&e.removeEventListener(t,r),i(s)}))}}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return s},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+".");s=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||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},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=s[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},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,r,s,o;if(a(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){o=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},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 r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},Mn.exports}();let An=!0,_n=!0;function Ln(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function On(e,t,i){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable)return void Un("Unable to polyfill events");const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function xn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(An=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Nn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(_n=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Un(){if("object"==typeof window){if(An)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Fn(e,t){_n&&console.warn(e+" is deprecated, please use "+t+" instead.")}function jn(e){return"[object Object]"===Object.prototype.toString.call(e)}function Bn(e){return jn(e)?Object.keys(e).reduce((function(t,i){const n=jn(e[i]),r=n?Bn(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function Vn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Vn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Vn(e,e.get(t),i)}))})))}function qn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Vn(e,i,r)}))})),r}const Kn=Un;function Hn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const a=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let a=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=n(e.video),Kn("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return Kn("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function Wn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function zn(e,t){if(!(t.version>102))if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else On(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Gn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Jn(e,t){if(t.version>=67)return;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=>qn(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}),On(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>qn(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const i=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 i.apply(this,arguments)}}function Qn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function Yn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Qn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function $n(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 Xn(e,t){t.version>102||On(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Zn=Object.freeze({__proto__:null,fixNegotiationNeeded:Xn,shimAddTrackRemoveTrack:Yn,shimAddTrackRemoveTrackWithNative:Qn,shimGetSendersWithDtmf:Gn,shimGetUserMedia:Hn,shimMediaStream:Wn,shimOnTrack:zn,shimPeerConnection:$n,shimSenderReceiverGetStats:Jn});function er(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Fn("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 tr(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 ir(e,t){"object"==typeof e&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!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]})))}function nr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;if(t.version>=151)return;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=Array.prototype.slice.call(arguments),r=e[0],s=e[1],a=e[2];return"closed"===this.signalingState?Promise.resolve(new Map):n.apply(this,[r||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,a)}}function rr(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 sr(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}),On(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ar(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Fn("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function or(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function cr(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 t=n.sender,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 dr(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 lr(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 ur(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 hr=Object.freeze({__proto__:null,shimAddTransceiver:cr,shimCreateAnswer:ur,shimCreateOffer:lr,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:dr,shimGetStats:nr,shimGetUserMedia:er,shimOnTrack:tr,shimPeerConnection:ir,shimRTCDataChannel:or,shimReceiverGetStats:sr,shimRemoveStream:ar,shimSenderGetStats:rr});function pr(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function mr(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 gr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,o=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=o,o=function(e,t,i){const n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=o}function fr(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(vr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function vr(e){return e&&void 0!==e.video?Object.assign({},e,{video:Bn(e.video)}):e}function kr(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?(Fn("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 yr(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 br(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 Tr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Sr,Cr=Object.freeze({__proto__:null,shimAudioContext:Tr,shimCallbacksAPI:gr,shimConstraints:vr,shimCreateOfferLegacy:br,shimGetUserMedia:fr,shimLocalStreamsAPI:pr,shimRTCIceServerUrls:kr,shimRemoteStreamsAPI:mr,shimTrackEventTransceiver:yr}),wr={exports:{}};var Er=(Sr||(Sr=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&&void 0!==e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],a=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(a){const n=t.parseRtpMap(a),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=a.length>0&&a[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===o&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&o&&i.push({ssrc:o});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;return r=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(wr)),wr.exports),Rr=dn(Er),Pr=a({__proto__:null,default:Rr},[Er]);function Ir(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=Rr.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,On(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Mr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||On(e,"icecandidate",(e=>{if(e.candidate){const t=Rr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function Dr(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){"plan-b"===this.getConfiguration().sdpSemantics&&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=Rr.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Rr.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Rr.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return i.apply(this,arguments)}}function Ar(e,t){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;if("chrome"===t.browser&&t.version>149)return;if("firefox"===t.browser&&t.version>60)return;function i(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return i(e,this),e},On(e,"datachannel",(e=>(i(e.channel,e.target),e)))}function _r(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 Lr(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 Or(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 xr(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 Nr,Ur,Fr=Object.freeze({__proto__:null,removeExtmapAllowMixed:Lr,shimAddIceCandidateNullOrEmpty:Or,shimConnectionState:_r,shimMaxMessageSize:Dr,shimParameterlessSetLocalDescription:xr,shimRTCIceCandidate:Ir,shimRTCIceCandidateRelayProtocol:Mr,shimSendThrowTypeError:Ar});!function(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=Un,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 i=e.navigator;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(Ln(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(Ln(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(Ln(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=Ln(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:n,commonShim:Fr,extractVersion:Ln,disableLog:xn,disableWarnings:Nn,sdp:Pr};switch(n.browser){case"chrome":if(!Zn||!$n||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=Zn,Or(e,n),xr(e),Hn(e,n),Wn(e),$n(e,n),zn(e,n),Yn(e,n),Gn(e),Jn(e,n),Xn(e,n),Ir(e),Mr(e),_r(e),Dr(e,n),Ar(e,n),Lr(e,n);break;case"firefox":if(!hr||!ir||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=hr,Or(e,n),xr(e),er(e,n),ir(e,n),nr(e,n),tr(e),ar(e),rr(e),sr(e),or(e),cr(e),dr(e),lr(e),ur(e),Ir(e),_r(e),Dr(e,n),Ar(e,n);break;case"safari":if(!Cr||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=Cr,Or(e,n),xr(e),kr(e),br(e),gr(e),pr(e),mr(e),yr(e),fr(e),Tr(e),Ir(e),Mr(e),Dr(e,n),Ar(e,n),Lr(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class jr extends(Ur=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}Nr=jr,jr.resolve=e=>Reflect.get(Ur,"resolve",Nr).call(Nr,e);const Br=/version\/(\d+(\.?_?\d+)+)/i;let Vr;function qr(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===Vr||t){const e=Kr.find((e=>e.test.test(i)));Vr=null==e?void 0:e.describe(i)}return Vr}const Kr=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Hr(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Wr(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Hr(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Wr(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Hr(Br,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Wr(e)})}];function Hr(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 Wr(e){return e.includes("mac os")?Hr(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class zr extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==i?void 0:i.cause)&&(this.cause=null==i?void 0:i.cause)}}class Gr extends zr{}var Jr,Qr,Yr,$r,Xr,Zr,es;!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",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(Jr||(Jr={}));class ts extends Gr{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=Jr[t]}static notAllowed(e,t,i){return new ts(e,Jr.NotAllowed,t,i)}static timeout(e){return new ts(e,Jr.Timeout)}static leaveRequest(e,t){return new ts(e,Jr.LeaveRequest,void 0,t)}static internal(e,t){return new ts(e,Jr.InternalError,void 0,t)}static cancelled(e){return new ts(e,Jr.Cancelled)}static serverUnreachable(e,t){return new ts(e,Jr.ServerUnreachable,t)}static websocket(e,t,i){return new ts(e,Jr.WebSocket,t,i)}static serviceNotFound(e,t){return new ts(e,Jr.ServiceNotFound,void 0,t)}}class is extends zr{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class ns extends zr{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class rs extends zr{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class ss extends zr{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class as extends zr{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class os extends zr{constructor(e){super(14,null!=e?e:"unable to publish data"),this.name="PublishDataError"}}class cs extends zr{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class ds extends Gr{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:tn[t]}}!function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(Qr||(Qr={}));class ls extends Gr{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=Qr[t]}}class us extends zr{constructor(e){super(18,e),this.name="SignalReconnectError"}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(Yr||(Yr={})),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}}(Yr||(Yr={}));class hs{}hs.setTimeout=function(){return setTimeout(...arguments)},hs.setInterval=function(){return setInterval(...arguments)},hs.clearTimeout=function(){return clearTimeout(...arguments)},hs.clearInterval=function(){return clearInterval(...arguments)},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",e.DataTrackPublished="dataTrackPublished",e.DataTrackUnpublished="dataTrackUnpublished",e.LocalDataTrackPublished="localDataTrackPublished",e.LocalDataTrackUnpublished="localDataTrackUnpublished"}($r||($r={})),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"}(Xr||(Xr={})),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",e.PublishDataTrackResponse="publishDataTrackResponse",e.UnPublishDataTrackResponse="unPublishDataTrackResponse",e.DataTrackSubscriberHandles="dataTrackSubscriberHandles",e.DataTrackPacketReceived="dataTrackPacketReceived",e.Joined="joined",e.TokenRefreshed="tokenRefreshed",e.ServerRegionsReported="serverRegionsReported"}(Zr||(Zr={})),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"}(es||(es={}));class ps{constructor(e,t,i,n,r){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:r}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const ms=["vp8","h264"],gs=["vp8","h264","vp9","av1","h265"];function fs(e){return!!ms.find((t=>t===e))}const vs=fs;var ks,ys;!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(ks||(ks={})),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}}(ys||(ys={}));const bs={h90:new ps(160,90,9e4,20),h180:new ps(320,180,16e4,20),h216:new ps(384,216,18e4,20),h360:new ps(640,360,45e4,20),h540:new ps(960,540,8e5,25),h720:new ps(1280,720,17e5,30),h1080:new ps(1920,1080,3e6,30),h1440:new ps(2560,1440,5e6,30),h2160:new ps(3840,2160,8e6,30)},Ts={h120:new ps(160,120,7e4,20),h180:new ps(240,180,125e3,20),h240:new ps(320,240,14e4,20),h360:new ps(480,360,33e4,20),h480:new ps(640,480,5e5,20),h540:new ps(720,540,6e5,25),h720:new ps(960,720,13e5,30),h1080:new ps(1440,1080,23e5,30),h1440:new ps(1920,1440,38e5,30)},Ss={h360fps3:new ps(640,360,2e5,3,"medium"),h360fps15:new ps(640,360,4e5,15,"medium"),h720fps5:new ps(1280,720,8e5,5,"medium"),h720fps15:new ps(1280,720,15e5,15,"medium"),h720fps30:new ps(1280,720,2e6,30,"medium"),h1080fps15:new ps(1920,1080,25e5,15,"medium"),h1080fps30:new ps(1920,1080,5e6,30,"medium"),original:new ps(0,0,7e6,30,"medium")};function Cs(e,t,i){var n,r,s,a;const o=Ls(null!=e?e:{}),c=o.optionsWithoutProcessor,d=o.audioProcessor,l=o.videoProcessor,u=null==t?void 0:t.processor,h=null==i?void 0:i.processor,p=null!=c?c:{};return!0===p.audio&&(p.audio={}),!0===p.video&&(p.video={}),p.audio&&(ws(p.audio,t),null!==(n=(s=p.audio).deviceId)&&void 0!==n||(s.deviceId={ideal:"default"}),(d||u)&&(p.audio.processor=null!=d?d:u)),p.video&&(ws(p.video,i),null!==(r=(a=p.video).deviceId)&&void 0!==r||(a.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=null!=l?l:h)),p}function ws(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function Es(e){var t,i,n,r;const s={};if(e.video)if("object"==typeof e.video){const i={},r=i,a=e.video;Object.keys(a).forEach((e=>{if("resolution"===e)ws(r,a.resolution);else r[e]=a[e]})),s.video=i,null!==(t=(n=s.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else s.video=!!e.video&&{deviceId:{ideal:"default"}};else s.video=!1;return e.audio?"object"==typeof e.audio?(s.audio=e.audio,null!==(i=(r=s.audio).deviceId)&&void 0!==i||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Rs(e){return Cn(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Ps();if(i){const n=i.createAnalyser();n.fftSize=2048;const r=n.frequencyBinCount,s=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield Vs(t),n.getByteTimeDomainData(s);const a=s.some((e=>128!==e&&0!==e));return i.close(),!a}return!1}()}))}function Ps(){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=()=>Cn(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}}));i.addEventListener("statechange",(()=>{var t;"closed"===i.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))})),window.document.body.addEventListener("click",e)}return i}}function Is(e){return"audioinput"===e?Us.Source.Microphone:"videoinput"===e?Us.Source.Camera:Us.Source.Unknown}function Ms(e){return e===Us.Source.Microphone?"audioinput":e===Us.Source.Camera?"videoinput":void 0}function Ds(e){return e.split("/")[1].toLowerCase()}function As(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new fi({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function _s(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?_s(e.track):{})}}function Ls(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:(r=t,void 0===r?r:"function"==typeof structuredClone?"object"==typeof r&&null!==r?structuredClone(Object.assign({},r)):structuredClone(r):JSON.parse(JSON.stringify(r)))};var r}function Os(e,t){return e.width*e.height<t.width*t.height}const xs=[];var Ns;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(Ns||(Ns={}));class Us extends Dn.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Us.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=kn,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=yn(null!==(n=i.loggerName)&&void 0!==n?n:fn.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Us.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),_s(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Us.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===Us.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(xs.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&xs.splice(xs.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Fs(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?es.AudioPlaybackStarted:es.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?es.AudioPlaybackFailed:es.VideoPlaybackFailed,t):"AbortError"===t.name?kn.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):kn.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(es.ElementAttached,e),e}detach(e){try{if(e){js(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(es.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{js(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(es.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=yn(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),xs.forEach((e=>{e.parentElement||(t=!1)})),t&&xs.push(e)}}handleAppVisibilityChanged(){return Cn(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Us.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){$s()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){$s()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Fs(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)),Js()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Js()||zs())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function js(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 $e.AUDIO;case t.Video:return $e.VIDEO;default:return $e.DATA}},e.kindFromProto=function(e){switch(e){case $e.AUDIO:return t.Audio;case $e.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return Xe.CAMERA;case i.Microphone:return Xe.MICROPHONE;case i.ScreenShare:return Xe.SCREEN_SHARE;case i.ScreenShareAudio:return Xe.SCREEN_SHARE_AUDIO;default:return Xe.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case Xe.CAMERA:return i.Camera;case Xe.MICROPHONE:return i.Microphone;case Xe.SCREEN_SHARE:return i.ScreenShare;case Xe.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case ei.ACTIVE:return n.Active;case ei.PAUSED:return n.Paused;default:return n.Unknown}}}(Us||(Us={}));const Bs="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Vs(e){return new jr((t=>hs.setTimeout(t,e)))}function qs(){return"addTransceiver"in RTCPeerConnection.prototype}function Ks(){return"addTrack"in RTCPeerConnection.prototype}function Hs(e){return"av1"===e||"vp9"===e}function Ws(e){return!(!document||Qs())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function zs(){var e;return"Firefox"===(null===(e=qr())||void 0===e?void 0:e.name)}function Gs(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform&&!function(){const e=qr();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}()}function Js(){var e;return"Safari"===(null===(e=qr())||void 0===e?void 0:e.name)}function Qs(){const e=qr();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function Ys(){var e,t;return!!$s()&&(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 $s(){return"undefined"!=typeof document}function Xs(){return"ReactNative"==navigator.product}function Zs(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function ea(e){return Zs(e)?e.hostname.split(".")[0]:null}function ta(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ia(){if(!Xs())return;let e=ta();return e?e.platform:void 0}function na(){if($s())return window.devicePixelRatio;if(Xs()){let e=ta();if(e)return e.devicePixelRatio}return 1}function ra(e,t){const i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){const t=parseInt(i[e],10),s=parseInt(n[e],10);if(t>s)return 1;if(t<s)return-1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function sa(e){for(const t of e)t.target.handleResize(t)}function aa(e){for(const t of e)t.target.handleVisibilityChanged(t)}let oa=null;const ca=()=>(oa||(oa=new ResizeObserver(sa)),oa);let da=null;const la=()=>(da||(da=new IntersectionObserver(aa,{root:null,rootMargin:"0px"})),da);function ua(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const r=document.createElement("canvas");r.width=e,r.height=t;const s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const a=B(r.captureStream().getTracks(),1)[0];if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let ha;function pa(){if(!ha){const t=new AudioContext,i=t.createOscillator(),n=t.createGain();n.gain.setValueAtTime(0,0);const r=t.createMediaStreamDestination();i.connect(n),n.connect(r),i.start();var e=B(r.stream.getAudioTracks(),1);if(ha=e[0],!ha)throw Error("Could not get empty media stream audio track");ha.enabled=!1}return ha.clone()}class ma{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,i)=>Cn(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 ga(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function fa(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function va(e){switch(e.reason){case Jr.LeaveRequest:return e.context;case Jr.Cancelled:return it.CLIENT_INITIATED;case Jr.NotAllowed:return it.USER_REJECTED;case Jr.ServerUnreachable:return it.JOIN_FAILURE;default:return it.UNKNOWN_REASON}}function ka(e){return void 0!==e?Number(e):void 0}function ya(e){return void 0!==e?BigInt(e):void 0}function ba(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Ta(e){return!!e&&e.kind==Us.Kind.Audio}function Sa(e){return!!e&&e.kind==Us.Kind.Video}function Ca(e){return ba(e)&&Sa(e)}function wa(e){return ba(e)&&Ta(e)}function Ea(e){return!!e&&!e.isLocal}function Ra(e){return!!e&&!e.isLocal}function Pa(e){return Ea(e)&&Sa(e)}function Ia(){return"undefined"!=typeof CompressionStream}function Ma(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=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)})),Aa(i,"rtc")}(e,t);return i?n:Aa(n,"v1")}function Da(e){return e.endsWith("/")?e:"".concat(e,"/")}function Aa(e,t){return e.pathname="".concat(Da(e.pathname)).concat(t),e}function _a(e){if("string"==typeof e)return ni.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return ni.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const La="lk_e2ee";var Oa,xa,Na,Ua,Fa;function ja(){return Ba()||"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform}function Ba(){return"undefined"!=typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(Oa||(Oa={})),function(e){e.KeyRatcheted="keyRatcheted"}(xa||(xa={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(Na||(Na={})),function(e){e.Error="cryptorError"}(Ua||(Ua={}));Dn.EventEmitter;function Va(){return Gs()}function qa(e){return!!(null==e?void 0:e.worker)&&(Ba()||Va())}function Ka(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}function Ha(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n,r;let s;const a=null!==(n=i.isImmediate)&&void 0!==n&&n,o=null!==(r=i.callback)&&void 0!==r&&r,c=i.maxWait;let d=Date.now(),l=[];const u=function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];const u=this;return new Promise(((i,r)=>{const h=a&&void 0===s;if(void 0!==s&&hs.clearTimeout(s),s=hs.setTimeout((function(){if(s=void 0,d=Date.now(),!a){const t=e.apply(u,n);o&&o(t),l.forEach((e=>(0,e.resolve)(t))),l=[]}}),function(){if(void 0!==c){const e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){const t=e.apply(u,n);return o&&o(t),i(t)}l.push({resolve:i,reject:r})}))};return u.cancel=function(e){void 0!==s&&hs.clearTimeout(s),l.forEach((t=>(0,t.reject)(e))),l=[]},u}!function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(Fa||(Fa={}));const Wa=2e3;function za(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class Ga extends Us{constructor(e,t,i,n,r){super(e,i,r),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?es.Muted:es.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(es.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Cn(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()),Wa)),"undefined"!=typeof RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&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 e=i.timestamp,t=i.rtpTimestamp;t&&this.rtpTimestamp!==t&&(this.emit(es.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Ja extends Ga{constructor(e,t,i,n,r){super(e,t,Us.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>Cn(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=za(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Ha((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}lookupFrameMetadata(e){let t=e.rtpTimestamp;var i;return null===(i=this.frameMetadataExtractor)||void 0===i?void 0:i.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===Us.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?js(this._mediaStreamTrack,t):Fs(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 Qa(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){if(e)return this.stopObservingElement(e),super.detach(e);const 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 Cn(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 Cn(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(e){var t,i;const n=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),r=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!r||s;(this.lastVisible!==a||e)&&(!a&&Date.now()-n<100?hs.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(es.VisibilityChanged,a,this)))}updateDimensions(){var e,t;let i=0,n=0;const r=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*r,s=e.height()*r;t+s>i+n&&(i=t,n=s)}(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(es.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return na();if(!t){return na()>2?2:1}return t}}class Qa{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const i=e.target,n=e.isIntersecting;i===this.element&&(this.isIntersecting=n,this.isPiP=Ya(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),queueMicrotask((()=>{requestAnimationFrame((()=>{var e;this.isPiP=Ya(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)}))}))},this.onLeavePiP=()=>{var e;this.isPiP=Ya(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:$a(e),this.isPiP=$s()&&Ya(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=$a(this.element),this.isPiP=Ya(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,la().observe(this.element),ca().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,r;null===(e=la())||void 0===e||e.unobserve(this.element),null===(t=ca())||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===(r=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===r||r.removeEventListener("pagehide",this.onLeavePiP)}}function Ya(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&$a(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function $a(e,t){const i=t||window;let n=e.offsetTop,r=e.offsetLeft;const s=e.offsetWidth,a=e.offsetHeight,o=e.hidden,c=getComputedStyle(e).display;for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&r<i.pageXOffset+i.innerWidth&&n+a>i.pageYOffset&&r+s>i.pageXOffset&&!o&&"none"!==c}class Xa extends Dn.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;const n=e.data,r=n.kind,s=n.data;switch(r){case"error":if(kn.error(s.error.message),s.uuid){const e=this.decryptDataRequests.get(s.uuid);if(null==e?void 0:e.reject){e.reject(s.error);break}const t=this.encryptDataRequests.get(s.uuid);if(null==t?void 0:t.reject){t.reject(s.error);break}}this.emit(Na.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(Na.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(Na.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(Oa.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const e=this.decryptDataRequests.get(s.uuid);(null==e?void 0:e.resolve)&&e.resolve(s);break;case"encryptDataResponse":const n=this.encryptDataRequests.get(s.uuid);(null==n?void 0:n.resolve)&&n.resolve(s);break;case"packetTrailerMetadata":this.handleFrameMetadata(s.trackId,s.rtpTimestamp,s.ssrc,s.metadata)}},this.onWorkerError=e=>{kn.error("e2ee worker encountered an error:",{error:e.error}),this.emit(Na.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!ja())throw new is("tried to setup end-to-end encryption on an unsupported browser");if(kn.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:bn.getLevel()}};this.worker&&(kn.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){kn.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):kn.warn("ignoring server sent trailer as it's empty")}handleFrameMetadata(e,t,i,n){if(this.room)for(const r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const s of r.trackPublications.values())if(s.track&&s.track.mediaStreamID===e&&s.track instanceof Ja&&s.track.frameMetadataExtractor)return void s.track.frameMetadataExtractor.storeMetadata(t,i,n)}setupEngine(e){e.on(Zr.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on($r.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==mt.NONE,t.identity))),e.on($r.ConnectionStateChanged,(t=>{t===Vd.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==mt.NONE,e.identity)}))}))})).on($r.TrackUnsubscribed,((e,t,i)=>{var n;const r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(r)})).on($r.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on($r.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach((t=>{var i;this.postKey(t,e===(null!==(i=t.keyIndex)&&void 0!==i?i:0))})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),e.localParticipant.on(Xr.LocalSenderCreated,((e,t)=>Cn(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),e.localParticipant.on(Xr.LocalTrackPublished,(e=>{if(!Sa(e.track)||!Qs())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:Ds(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)})),t.on(Oa.SetKey,((e,t)=>this.postKey(e,null==t||t))).on(Oa.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}encryptData(e){return Cn(this,void 0,void 0,(function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new ma;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise}))}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),s={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:n}},a=new ma;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(s),a.promise}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,t){let i=e.key,n=e.participantIdentity,r=e.keyIndex;var s;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:i,keyIndex:r,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}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)return;if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const n="video"===e.kind&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?Ds(i.mimeType):void 0,n)}setupE2EESender(e,t){var i,n,r;ba(e)&&t?this.handleSender(t,e.mediaStreamID,void 0,Sa(e)?null!==(n=null===(i=e.publishOptions)||void 0===i?void 0:i.frameMetadata)&&void 0!==n?n:null===(r=e.publishOptions)||void 0===r?void 0:r.packetTrailer:void 0):t||kn.warn("early return because sender is not ready")}handleReceiver(e,t,i,n,r){return Cn(this,void 0,void 0,(function*(){if(this.worker){if(Gs()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n,hasPacketTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(La in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i,hasPacketTrailer:r}};return void this.worker.postMessage(e)}let s=e.writableStream,a=e.readableStream;if(!s||!a){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,a=t.readable}const o={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:n,participantIdentity:i,isReuse:La in e,hasPacketTrailer:r}};this.worker.postMessage(o,[a,s])}e[La]=!0}}))}handleSender(e,t,i,n){var r;if(!(La in e)&&this.worker){if(!(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Gs()){kn.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:Ka(n),packetTrailer:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{kn.info("initialize encoded streams");const r=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:Ka(n),packetTrailer:n}};this.worker.postMessage(s,[r.readable,r.writable])}e[La]=!0}}}class Za{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,i){for(0!==this.activeSsrc&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=300;){const e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,i)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class eo{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{const t=e.data;if("metadata"===t.kind){const e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{kn.error("frame metadata worker encountered an error:",{error:e.error})},this.worker=null==e?void 0:e.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),e.on($r.TrackSubscribed,((e,t,i)=>{"video"===e.kind&&this.setupReceiver(e,t.trackInfo)})).on($r.TrackUnsubscribed,(e=>{this.teardownTrack(e)})).on($r.Disconnected,(()=>{this.cleanup()})))}setupReceiver(e,t){var i,n,r;const s=e.receiver;if(!s)return;if(!(!!(null==t?void 0:t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0))return void((null===(i=this.room)||void 0===i?void 0:i.hasE2EESetup)||this.setupPassthroughReceiver(s,e.mediaStreamID));if(!qa(this.worker?{worker:this.worker}:void 0)&&!(null===(n=this.room)||void 0===n?void 0:n.hasE2EESetup))return void kn.warn("frame metadata transform not supported; skipping extraction");const a=new Za,o=e.mediaStreamID;this.extractors.set(o,a),e.frameMetadataExtractor=a,(null===(r=this.room)||void 0===r?void 0:r.hasE2EESetup)||this.setupWorkerReceiver(s,o,!0)}setupPassthroughReceiver(e,t){Va()?"transform"in e&&(e.transform=null):(this.worker&&qa({worker:this.worker})&&!this.workerPipelines.has(e)||this.worker&&this.workerPipelines.has(e))&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const n=this.worker;if(!n)return;if(Va())return void(e.transform=new RTCRtpScriptTransform(n,{kind:"decode",trackId:t}));const r=this.workerPipelines.get(e);if(r){const s={kind:"updateTrackId",data:{oldTrackId:r,newTrackId:t,hasPacketTrailer:i}};return n.postMessage(s),void this.workerPipelines.set(e,t)}if(!("createEncodedStreams"in e))return void kn.warn("createEncodedStreams not supported");let s;try{s=e.createEncodedStreams()}catch(e){return void kn.warn("failed to create encoded streams",{error:e})}const a={kind:"decode",data:{readableStream:s.readable,writableStream:s.writable,trackId:t,hasPacketTrailer:i}};n.postMessage(a,[s.readable,s.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,i=this.extractors.get(t);i&&(i.dispose(),this.extractors.delete(t)),e instanceof Ja&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(const e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear(),null===(e=this.worker)||void 0===e||e.terminate()}}class to{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new to),this._instance}addFailedConnectionAttempt(e){var t;const i=ea(new URL(e));if(!i)return;let n=null!==(t=this.failedConnectionAttempts.get(i))&&void 0!==t?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,Vs(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){const t=new URL(e),i=t&&ea(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&ea(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}to._instance=null;const io="default";class no{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new no),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Cn(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=no.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){kn.debug("awaiting getUserMedia promise");try{e?yield no.userMediaPromiseMap.get(e):yield Promise.all(no.userMediaPromiseMap.values())}catch(e){kn.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(i&&(!Js()||!t.hasDeviceInUse(e))){if(0===r.filter((t=>t.kind===e)).length||r.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);r=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=r,e&&(r=r.filter((t=>t.kind===e))),r}()}))}normalizeDeviceId(e,t,i){return Cn(this,void 0,void 0,(function*(){if(t!==io)return t;const n=yield this.getDevices(e),r=n.find((e=>e.deviceId===io));if(!r)return void kn.warn("could not reliably determine default device");const s=n.find((e=>e.deviceId!==io&&e.groupId===(null!=i?i:r.groupId)));if(s)return null==s?void 0:s.deviceId;kn.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?no.userMediaPromiseMap.has(e):no.userMediaPromiseMap.size>0}}no.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],no.userMediaPromiseMap=new Map;const ro=65535,so=4294967295;class ao{static u16(e){return new ao(e,ro)}static u32(e){return new ao(e,so)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new ao(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t+e))}decrement(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t-e))}getThenIncrement(){const e=this.value;return this.increment(),new ao(e,this.maxSize)}isBefore(e){const t=this.value>>>0,i=(e.value>>>0)-t>>>0;return 0!==i&&i<this.maxSize+1}}class oo{static fromRtpTicks(e){return new oo(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*so);return oo.fromRtpTicks(e)}constructor(e,t){this.timestamp=ao.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new oo(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class co{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new co(t,new Date,e)}static startingAtTime(e,t,i){return new co(i,e,t)}static rtpStartingNow(e){return co.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return co.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=co.durationInMsToTicks(t,this.rateInHz),n=this.base.clone();return n.wrappingAdd(i),n.isBefore(this.previous)&&(n=this.previous),this.previous=n.clone(),n.clone()}static durationInMsToTicks(e,t){let i=(1e6*e*t+5e8)/1e9;return Math.round(i)}}function lo(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw new Error("Error coercing ".concat(e," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var uo;!function(e){e[e.Reserved=0]="Reserved",e[e.TooLarge=1]="TooLarge"}(uo||(uo={}));class ho extends Gr{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=uo[t]}isReason(e){return this.reason===e}static tooLarge(){return new ho("Value too large to be a valid track handle",uo.TooLarge)}static reserved(e){return new ho("0x".concat(e.toString(16)," is a reserved value."),uo.Reserved)}}const po={fromNumber(e){if(0===e)throw ho.reserved(e);if(e>ro)throw ho.tooLarge();return e}};class mo{constructor(){this.value=0}get(){return this.value+=1,this.value>ro?null:this.value}reset(){this.value=0}}const go={from:e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==mt.NONE}),toProtobuf:e=>new vt({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?mt.GCM:mt.NONE})};var fo;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(fo||(fo={}));class vo{constructor(){this.pendingTasks=new Map,this.taskMutex=new d,this.nextTaskIndex=0}run(e){return Cn(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:fo.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=fo.RUNNING,yield e()}finally{t.status=fo.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Cn(this,void 0,void 0,(function*(){return this.run((()=>Cn(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}class ko{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;if(null===(i=t.signal)||void 0===i?void 0:i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,null!==(n=t.protocols)&&void 0!==n?n:[]);r.binaryType="arraybuffer",this.ws=r;const s=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.closeCode,i=e.reason;return r.close(t,i)};this.opened=new jr(((e,t)=>{const i=()=>{t(ts.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let i=t.data;return e.enqueue(i)},r.onerror=t=>e.error(t)},cancel:s}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:s}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",i)},r.addEventListener("error",i)})),this.closed=new jr(((e,t)=>{const i=()=>Cn(this,void 0,void 0,(function*(){const i=new jr((e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",(t=>{e(t)}),{once:!0})})),n=yield jr.race([Vs(250),i]);n?e(n):t(ts.websocket("Encountered unspecified websocket error without a timely close event"))}));r.onclose=t=>{let n=t.code,s=t.reason;e({closeCode:n,reason:s}),r.removeEventListener("error",i)},r.addEventListener("error",i)})),t.signal&&(t.signal.onabort=()=>r.close()),this.close=s}}const yo=["syncState","trickle","offer","answer","simulate","leave"];var bo;!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"}(bo||(bo={}));class To{get currentState(){return this.state}get isDisconnected(){return this.state===bo.DISCONNECTING||this.state===bo.DISCONNECTED}get isEstablishingConnection(){return this.state===bo.CONNECTING||this.state===bo.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=bo.DISCONNECTED,this.log=kn,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=t.loggerContextCb,this.log=yn(null!==(i=t.loggerName)&&void 0!==i?i:fn.Signal,(()=>this.logContext)),this.useJSON=e,this.requestQueue=new vo,this.queuedRequests=[],this.closingLock=new d,this.connectionLock=new d,this.state=bo.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 Cn(this,arguments,void 0,(function(e,t,i,n){var r=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=arguments.length>5?arguments[5]:void 0;return function*(){r.state=bo.CONNECTING,r.options=i;return yield r.connect(e,t,i,n,s,a)}()}))}reconnect(e,t,i,n){return Cn(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring");this.state=bo.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath)}))}connect(e,t,i,n){return Cn(this,arguments,void 0,(function(e,t,i,n){var r=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=arguments.length>5?arguments[5]:void 0;return function*(){const o=yield r.connectionLock.lock();r.connectOptions=i,r.useV0SignalPath=s;const c=function(e){var t;const i=new jt({capabilities:e,sdk:Bt.JS,protocol:17,clientProtocol:1,version:"2.20.0"});return Xs()&&(i.os=null!==(t=ia())&&void 0!==t?t:""),i}(i.clientInfoCapabilities),d=s?function(e,t,i){var n;const r=new URLSearchParams;r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid));r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",Xs()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),r.set("client_protocol",t.clientProtocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);i.adaptiveStream&&r.set("adaptive_stream","1");i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&r.set("network",navigator.connection.type);return r}(t,c,i):yield function(e,t,i,n){return Cn(this,void 0,void 0,(function*(){const r=new URLSearchParams;r.set("access_token",e);const s=new sn({clientInfo:t,connectionSettings:new rn({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0,publisherOffer:n});i.reconnectReason&&(s.reconnectReason=i.reconnectReason);const a=s.toBinary();let o,c;if(Ia()){const e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(a)),t.close();const i=[],n=e.readable.getReader();for(;;){const e=yield n.read(),t=e.done,r=e.value;if(t)break;i.push(r)}const r=i.reduce(((e,t)=>e+t.length),0),s=new Uint8Array(r);let d=0;for(const e of i)s.set(e,d),d+=e.length;o=s,c=on.GZIP}else o=a,c=on.NONE;const d=new an({joinRequest:o,compression:c}).toBinary(),l=e=>{const t=Array.from(e,(e=>String.fromCodePoint(e))).join("");return btoa(t)};return r.set("join_request",l(d).replace(/\+/g,"-").replace(/\//g,"_")),r}))}(t,c,i,a),l=Ma(e,d,s).toString(),u=(h=l,Aa(new URL(fa(h)),"validate")).toString();var h;return new Promise(((e,t)=>Cn(r,void 0,void 0,(function*(){var r,s;try{let a=!1;const o=e=>Cn(this,void 0,void 0,(function*(){if(a)return;a=!0;const i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;const i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then((()=>this.close(i))).catch((e=>{this.log.error(e),this.close()})):this.close(),c(),t(ts.cancelled(i))}));null==n||n.addEventListener("abort",o);const c=()=>{clearTimeout(d),null==n||n.removeEventListener("abort",o)},d=setTimeout((()=>{o(ts.timeout("room connection has timed out (signal)"))}),i.websocketTimeout),h=(e,t)=>{this.handleSignalConnected(e,d,t)},p=new URL(l);if(p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.ws){const e=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-e,"ms"))}this.log.info("signal connecting to ".concat(p),{reconnect:i.reconnect,reconnectReason:i.reconnectReason}),this.ws=new ko(l);try{this.ws.closed.then((e=>{var i;this.isEstablishingConnection&&t(ts.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state}),this.state===bo.CONNECTED&&this.handleOnClose(null!==(i=e.reason)&&void 0!==i?i:"Unexpected WS error"))})).catch((e=>{this.isEstablishingConnection&&t(ts.internal("Websocket error during a (re)connection attempt: ".concat(e)))}));const n=yield this.ws.opened.catch((e=>Cn(this,void 0,void 0,(function*(){if(this.state===bo.CONNECTED)this.handleWSError(e),t(e);else{this.state=bo.DISCONNECTED,clearTimeout(d);const i=yield this.handleConnectionError(e,u);t(i)}}))));if(clearTimeout(d),!n)return;const a=n.readable.getReader();this.streamWriter=n.writable.getWriter();const o=yield a.read();if(a.releaseLock(),!o.value)throw ts.internal("no message received as first message");const c=_a(o.value),l=this.validateFirstMessage(c,null!==(r=i.reconnect)&&void 0!==r&&r);if(!l.isValid)return void t(l.error);"join"===(null===(s=c.message)||void 0===s?void 0:s.case)&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(c.message.value));h(n,l.shouldProcessFirstMessage?c:void 0),e(l.response)}catch(e){t(e)}finally{c()}}finally{o()}}))))}()}))}startReadingLoop(e,t){return Cn(this,void 0,void 0,(function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Vs(this.signalLatency));const t=yield e.read(),i=t.done,n=t.value;if(i)break;const r=_a(n);this.handleSignalResponse(r)}}))}close(){return Cn(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([bo.DISCONNECTING||bo.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=bo.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,Vs(250)])}}catch(t){e.log.debug("websocket error while closing",{error:t})}finally{t&&(e.state=bo.DISCONNECTED),n()}}()}))}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Co(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Co(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new hi({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new pi({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Cn(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const r=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new Mi({requestId:r,metadata:e,name:t,attributes:n})}),r}()}))}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 Ii({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new qi({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:A.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Qi({timestamp:A.parse(Date.now()),rtt:A.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new wi({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ri({reason:it.CLIENT_INITIATED,action:Pi.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new ai({pubHandle:e,name:t,encryption:i?mt.GCM:mt.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new ci({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Ti({updates:[new Si({trackSid:e,subscribe:t})]})})}sendRequest(e){return Cn(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=yo.indexOf(e.case)>=0;return kn.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===bo.RECONNECTING)return void t.queuedRequests.push((()=>Cn(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield Vs(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case));const r=new ii({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary().buffer)}catch(e){t.log.error("error sending signal message",{error:e})}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message");let r=!1;if("answer"===n.case){const e=So(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const e=So(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}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(),r=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(n.value):"publishDataTrackResponse"===n.case?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(n.value):"unpublishDataTrackResponse"===n.case?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(n.value):"dataTrackSubscriberHandles"===n.case?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(n.value):this.log.debug("unsupported message",{msgCase:n.case}));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Cn(this,void 0,void 0,(function*(){if(this.state===bo.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=hs.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&hs.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval"),this.pingInterval=hs.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set")}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&hs.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=bo.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,r,s,a;return"join"===(null===(i=e.message)||void 0===i?void 0:i.case)?{isValid:!0,response:e.message.value}:this.state===bo.RECONNECTING&&"leave"!==(null===(n=e.message)||void 0===n?void 0:n.case)?"reconnect"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&"leave"===(null===(s=e.message)||void 0===s?void 0:s.case)?{isValid:!1,error:ts.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:ts.internal("Unexpected first message")}:{isValid:!1,error:ts.internal("did not receive join response, got ".concat(null===(a=e.message)||void 0===a?void 0:a.case," instead"))}}handleConnectionError(e,t){return Cn(this,void 0,void 0,(function*(){try{const i=yield fetch(t);switch(i.status){case 404:const e=yield i.text();return e.includes("requested room does not exist")?ts.notAllowed(e,i.status):ts.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield i.text();return ts.notAllowed(t,i.status)}return e instanceof ts?e:ts.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(e){return e instanceof ts?e:ts.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}}))}}function So(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 Co(e,t){return new ki({sdp:e.sdp,type:e.type,id:t})}class wo{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 Eo{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 i of this._map.entries()){var t=B(i,2);const n=t[0];t[1].expiresAt<e&&this._map.delete(n)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const i of this._map.entries()){var t=B(i,2);const n=t[0],r=t[1];r.expiresAt>=Date.now()&&e(r.value,n,this.asValueMap())}}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const r of i.entries()){var n=B(r,2);const s=n[0],a=n[1];t.push(e(a,s,i))}return t}asValueMap(){const e=new Map;for(const i of this._map.entries()){var t=B(i,2);const n=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(n,r.value)}return e}}var Ro,Po,Io,Mo,Do,Ao={},_o={},Lo={exports:{}};function Oo(){if(Ro)return Lo.exports;Ro=1;var e=Lo.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")}))})),Lo.exports}function xo(){return Po||(Po=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;!function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=Oo(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(r))return i(c,a,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(_o)),_o}function No(){if(Mo)return Io;Mo=1;var e=Oo(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,r=n.length;return e.replace(t,(function(e){if(i>=r)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 r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?r.push(n[t.name][a]):r.push(n[t.names[s]])}else r.push(n[t.name]);return i.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return Io=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var a=i.outerOrder||r,o=i.innerOrder||s,c=[];return a.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))})),t.media.forEach((function(t){c.push(n("m",e.m[0],t)),o.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))}))})),c.join("\r\n")+"\r\n"},Io}var Uo=function(){if(Do)return Ao;Do=1;var e=xo(),t=No(),i=Oo();return Ao.grammar=i,Ao.write=t,Ao.parse=e.parse,Ao.parseParams=e.parseParams,Ao.parseFmtpConfig=e.parseFmtpConfig,Ao.parsePayloads=e.parsePayloads,Ao.parseRemoteCandidates=e.parseRemoteCandidates,Ao.parseImageAttributes=e.parseImageAttributes,Ao.parseSimulcastStreamList=e.parseSimulcastStreamList,Ao}();const Fo="negotiationStarted",jo="negotiationComplete",Bo="offerAnswered",Vo="rtpVideoPayloadTypes";class qo extends Dn.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=kn,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Ha((e=>Cn(this,void 0,void 0,(function*(){this.emit(Fo);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this.pendingInitialOffer=void 0,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=yn(null!==(i=t.loggerName)&&void 0!==i?i:fn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new d}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 Cn(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 Cn(this,void 0,void 0,(function*(){var i,n;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 r;if("offer"===e.type){let t=function(e){var t;const i=[],n=[],r=Uo.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return r.media.forEach((e=>{var t;const r=Wo(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(s=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===s&&"nack"===e.type)))&&n.push(r),e.fmtp.some((e=>e.payload===s&&(e.config.includes("sprop-stereo=1")&&i.push(r),!0))))})),{stereoMids:i,nackMids:n}}(e),i=t.stereoMids,n=t.nackMids;this.remoteStereoMids=i,this.remoteNackMids=n}else if("answer"===e.type){if(this.pendingInitialOffer&&this._pc){const e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const t=Uo.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{Ho(e)})),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(e,Uo.write(t))}const t=Uo.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{const t=Wo(e.mid);"audio"===e.type&&this.trackBitrates.some((i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;let r=!1;for(const t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),r=!0;break}return r||i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0}))})),r=Uo.write(t)}if(yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,"answer"===e.type&&(this.latestAcknowledgedOfferId=t,this.emit(Bo,t)),this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(jo),e.sdp)){Uo.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Vo,e.rtp)}))}return!0}))}createInitialOffer(){return Cn(this,void 0,void 0,(function*(){var e;const t=yield this.offerLock.lock();try{if("stable"!==this.pc.signalingState)return void this.log.warn("signaling state is not stable, cannot create initial offer",this.logContext);const t=this.latestOfferId+1;this.latestOfferId=t;const i=yield this.pc.createOffer();this.pendingInitialOffer={sdp:i.sdp,type:i.type};const n=Uo.parse(null!==(e=i.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{Ho(e)})),i.sdp=Uo.write(n),{offer:i,offerId:t}}finally{t()}}))}createAndSendOffer(e){return Cn(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||this.pendingInitialOffer)){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return this.renegotiate=!0,void this.log.debug("requesting renegotiation",Object.assign({},this.logContext));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 r=Uo.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(r.media.forEach((e=>{Ho(e),"audio"===e.type?Ko(e,["all"],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(Hs(t.codec)&&!Js()&&this.ensureVideoDDExtensionForSVC(e,r),!Hs(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,Uo.write(r)),this.onOffer(n,this.latestOfferId)}finally{i()}}))}createAndSetAnswer(){return Cn(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=Uo.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Ho(e),"audio"===e.type&&Ko(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Uo.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ss("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 ss("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()}getMaxMessageSize(){var e,t;return null===(t=null===(e=this._pc)||void 0===e?void 0:e.sctp)||void 0===t?void 0:t.maxMessageSize}getConnectedAddress(){return Cn(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 r=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==r?n.get(r):void 0}))}setMungedSDP(e,t,i){return Cn(this,void 0,void 0,(function*(){var n,r;const s=e.sdp;if(t){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,mungedSdp:t,originalSdp:s})),e.sdp=s}}try{i?yield null===(n=this._pc)||void 0===n?void 0:n.setRemoteDescription(e):yield null===(r=this._pc)||void 0===r?void 0:r.setLocalDescription(e)}catch(n){let r="unknown error";n instanceof Error?r=n.message:"string"==typeof n&&(r=n);const a={error:r,sdp:e.sdp};throw t&&t!==s&&(a.mungedSdp=t),!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new as(r)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Bs)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;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:Bs})}}}function Ko(e,t,i){const n=Wo(e.mid);let r=0;e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),r>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some((e=>e.payload===r&&"nack"===e.type))&&e.rtcpFb.push({payload:r,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some((e=>e.payload===r&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Ho(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)}}function Wo(e){return"number"==typeof e?e.toFixed(0):e}const zo="vp8",Go={audioPreset:ys.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ss.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:zo,backupCodec:!0,preConnectBuffer:!1},Jo={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Qo={deviceId:{ideal:"default"},resolution:bs.h720.resolution},Yo={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Sn}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,singlePeerConnection:!0},$o={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Xo;!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"}(Xo||(Xo={}));class Zo{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var n;this.peerConnectionTimeout=$o.peerConnectionTimeout,this.log=kn,this.updateState=()=>{var e,t;const i=this.state,n=this.requiredTransports.map((e=>e.getConnectionState()));n.every((e=>"connected"===e))?this.state=Xo.CONNECTED:n.some((e=>"failed"===e))?this.state=Xo.FAILED:n.some((e=>"connecting"===e))?this.state=Xo.CONNECTING:n.every((e=>"closed"===e))?this.state=Xo.CLOSED:n.some((e=>"closed"===e))?this.state=Xo.CLOSING:n.every((e=>"new"===e))&&(this.state=Xo.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(Xo[i]," to ").concat(Xo[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.log=yn(null!==(n=t.loggerName)&&void 0!==n?n:fn.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired="subscriber-primary"!==e,this.isSubscriberConnectionRequired="subscriber-primary"===e,this.publisher=new qo(i,t),this._mode=e,"publisher-only"!==e&&(this.subscriber=new qo(i,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Zt.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.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Zt.PUBLISHER)},this.publisher.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=Xo.NEW,this.connectionLock=new d,this.remoteOfferLock=new d}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()}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 Cn(this,void 0,void 0,(function*(){var e;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(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()}))}triggerIceRestart(){return Cn(this,void 0,void 0,(function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Cn(this,void 0,void 0,(function*(){var i;t===Zt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return Cn(this,void 0,void 0,(function*(){var i,n,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(i=this.subscriber)||void 0===i?void 0:i.getSignallingState().toString()}));const s=yield this.remoteOfferLock.lock();try{if(!(yield null===(n=this.subscriber)||void 0===n?void 0:n.setRemoteDescription(e,t)))return;return yield null===(r=this.subscriber)||void 0===r?void 0:r.createAndSetAnswer()}finally{s()}}))}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null===(i=this.subscriber)||void 0===i||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Cn(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 Cn(this,void 0,void 0,(function*(){return new jr(((t,i)=>{const n=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>n)return this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),void t();let r=!1;const s=()=>{r||(r=!0,clearTimeout(c),this.publisher.off(Bo,a),e.signal.removeEventListener("abort",o))},a=e=>{e>n&&(s(),t())},o=()=>{s(),i(new as("negotiation aborted"))},c=setTimeout((()=>{s(),i(new as("negotiation timed out"))}),this.peerConnectionTimeout);e.signal.addEventListener("abort",o),this.publisher.on(Bo,a),this.publisher.negotiate((e=>{s(),e instanceof Error?i(e):i(new Error(String(e)))}))}))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find((t=>t.receiver===e));return null==t?void 0:t.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Zt.PUBLISHER||e===Zt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return Cn(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,r)=>Cn(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),hs.clearTimeout(s),r(ts.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const s=hs.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),r(ts.internal("could not establish pc connection"))}),n);for(;this.state!==Xo.CONNECTED;)if(yield Vs(50),null==t?void 0:t.signal.aborted)return void r(ts.cancelled("room connection has been cancelled"));hs.clearTimeout(s),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}const ec="undefined"!=typeof MediaRecorder;const tc=ec?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class ic extends tc{constructor(e,t){if(!ec)throw new Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([e.mediaStreamTrack]),t);const r=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",s),null==n||n.close(),n=void 0},s=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",s),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>Cn(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:()=>{r()}}),this.addEventListener("stop",r),this.addEventListener("error",s)}}class nc extends Us{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.pendingDeviceChange=!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=Ha((()=>Cn(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Cn(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(es.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new d,this.pauseUpstreamLock=new d,this.trackChangeLock=new d,this.trackChangeLock.lock().then((t=>Cn(this,void 0,void 0,(function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})))),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Us.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,i=e.height;return t&&i?{width:t,height:i}: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,i){return Cn(this,void 0,void 0,(function*(){var n;if(e===this._mediaStreamTrack&&!t)return;let r;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{js(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Fs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),r=this.processor.processedTrack}this.sender&&"closed"!==(null===(n=this.sender.transport)||void 0===n?void 0:n.state)&&(yield this.sender.replaceTrack(null!=r?r:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!!i||!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Fs(null!=r?r:e,t)})))}))}waitForDimensions(){return Cn(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===Us.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=qr())||void 0===i?void 0:i.os)&&(yield Vs(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield Vs(50)}throw new ns("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Cn(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===ga(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),ga(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Cn(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===Us.Source.ScreenShare)return;const i=e._mediaStreamTrack.getSettings(),n=i.deviceId,r=i.groupId,s=e.kind===Us.Kind.Audio?"audioinput":"videoinput";return t?no.getInstance().normalizeDeviceId(s,n,r):n}()}))}mute(){return Cn(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Cn(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Cn(this,void 0,void 0,(function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new ns("unable to replace an unpublished track");let i,n;"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor())}finally{i()}return yield this.onSenderTrackSwapped(),this}))}onSenderTrackSwapped(){return Cn(this,void 0,void 0,(function*(){}))}restart(e,t){return Cn(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const i=e,n=i.deviceId,r=i.facingMode,s=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 r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===Us.Kind.Video?a.video=!n&&!r||{deviceId:n,facingMode:r}:a.audio=!n||Object.assign({deviceId:n},s),this.attachedElements.forEach((e=>{js(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===Us.Kind.Video&&(yield o.applyConstraints(s)),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(es.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}}))}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?es.Muted:es.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 Cn(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ys()&&(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 Cn(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(es.UpstreamPaused,this);const t=qr();if("Safari"===(null==t?void 0:t.name)&&ra(t.version,"12.0")<0)throw new is("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 Cn(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(es.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 Cn(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 Cn(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 r=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);const r=document.createElement(t.kind),s={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext,localTrack:t};if(yield e.init(s),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(Fs(t._mediaStreamTrack,r),r.muted=!0,r.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((()=>{r.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=r,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(js(t._mediaStreamTrack,e),Fs(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(es.TrackProcessorUpdate,t.processor)}finally{r()}yield t.onSenderTrackSwapped()}()}))}getProcessor(){return this.processor}stopProcessor(){return Cn(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.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}yield e.onSenderTrackSwapped()}()}))}internalStopProcessor(){return Cn(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(es.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(ec)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 ic(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 rc extends nc{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,r=arguments.length>4?arguments[4]:void 0;super(e,Us.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Cn(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=za(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(es.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(es.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Cn(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===Us.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 Cn(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Us.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!this.pendingDeviceChange||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}restartTrack(e){return Cn(this,void 0,void 0,(function*(){let t;if(e){const i=Es({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e,t){const i=Object.create(null,{restart:{get:()=>super.restart}});return Cn(this,void 0,void 0,(function*(){const n=yield i.restart.call(this,e,t);return this.checkForSilence(),n}))}startMonitor(){$s()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Wa)))}setProcessor(e){return Cn(this,void 0,void 0,(function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Xs()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};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(es.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Cn(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 Cn(this,void 0,void 0,(function*(){const e=yield Rs(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(es.AudioSilenceDetected)),e}))}}const sc=Object.values(bs),ac=Object.values(Ts),oc=Object.values(Ss),cc=[bs.h180,bs.h360],dc=[Ts.h180,Ts.h360],lc=["q","h","f"];function uc(e,t,i,n){var r,s;let a=null==n?void 0:n.videoEncoding;e&&(a=null==n?void 0:n.screenShareEncoding);const o=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!a&&!o&&!c||!t||!i)return[{}];a||(a=function(e,t,i,n){const r=function(e,t,i){if(e)return oc;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return sc;return ac}(e,t,i);let s=r[0].encoding;const a=Math.max(t,i);for(let e=0;e<r.length;e+=1){const t=r[e];if(s=t.encoding,t.width>=a)break}if(n)switch(n){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,i,d),kn.debug("using video encoding",a));const l=a.maxFramerate,u=new ps(t,i,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Hs(d)){const e=new fc(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=qr();if(Qs()||Xs()||"Chrome"===(null==i?void 0:i.name)&&ra(null==i?void 0:i.version,"113")<0){const n="h"==e.suffix?2:3,r=function(e){return e||(e=qr()),"Safari"===(null==e?void 0:e.name)&&ra(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&ra(e.osVersion,"18.3")>0}(i);for(let i=0;i<e.spatial;i+=1)t.push({rid:lc[2-i],maxBitrate:a.maxBitrate/Math.pow(n,i),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,i):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),kn.debug("using svc encoding",{encodings:t}),t}if(!o)return[a];let h,p;if(h=e?null!==(r=gc(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==r?r:pc(e,u):null!==(s=gc(null==n?void 0:n.videoSimulcastLayers))&&void 0!==s?s:pc(e,u),h.length>0){const e=h[0];if(h.length>1)p=B(h,2)[1];const n=Math.max(t,i);if(n>=960&&p)return mc(t,i,[e,p,u],l);if(n>=480)return mc(t,i,[e,u],l)}return mc(t,i,[u])}function hc(e,t,i){var n,r,s,a;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&kn.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const o=e.mediaStreamTrack.getSettings(),c=null!==(n=o.width)&&void 0!==n?n:null===(r=e.dimensions)||void 0===r?void 0:r.width,d=null!==(s=o.height)&&void 0!==s?s:null===(a=e.dimensions)||void 0===a?void 0:a.height;e.source===Us.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1);return uc(e.source===Us.Source.ScreenShare,c,d,i)}function pc(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new ps(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 n=t.width,r=t.height,s=n>r?n/r:r/n;return Math.abs(s-16/9)<Math.abs(s-4/3)?cc:dc}function mc(e,t,i,n){const r=[];if(i.forEach(((i,s)=>{if(s>=lc.length)return;const a=Math.min(e,t),o={rid:lc[s],scaleResolutionDownBy:Math.max(1,a/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(o.maxFramerate=c);const d=qr(),l="Firefox"===(null==d?void 0:d.name)&&"iOS"!==d.os||0===s;i.encoding.priority&&l&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),r.push(o)})),Xs()&&"ios"===ia()){let e;r.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;r.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,kn.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),kn.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return r}function gc(e){if(e)return e.slice().sort(((e,t)=>{const i=e.encoding,n=t.encoding;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 fc{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 vc extends nc{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,Us.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Cn(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(es.CpuConstrained)),this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const r=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=za(t,r)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new d}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!$s())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()}),Wa))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;yield e.pauseUpstream.call(this);try{for(var a,o=!0,c=Pn(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){r=a.value,o=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(null)}}catch(e){i={error:e}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;yield e.resumeUpstream.call(this);try{for(var a,o=!0,c=Pn(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){r=a.value,o=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(e.mediaStreamTrack)}}catch(e){i={error:e}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Cn(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!==Us.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 Cn(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Us.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),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 Cn(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 r={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},s=i.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}})),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=Ns.LOW;i<=Ns.HIGH;i+=1)t.push(new Ui({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Hs(this.codec),t)}restartTrack(e){return Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;let a;if(e){const t=Es({video:e});"boolean"!=typeof t.video&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o,c=!0,d=Pn(this.simulcastCodecs.values());!(t=(o=yield d.next()).done);c=!0){r=o.value,c=!1;const e=r;e.sender&&"closed"!==(null===(s=e.sender.transport)||void 0===s?void 0:s.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}}yield this.onSenderTrackSwapped()}))}onSenderTrackSwapped(){return Cn(this,void 0,void 0,(function*(){yield this.refreshSenderEncodings()}))}refreshSenderEncodings(){return Cn(this,void 0,void 0,(function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let t;try{t=yield this.waitForDimensions()}catch(e){return void this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:e}))}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;const n=uc(this.source===Us.Source.ScreenShare,t.width,t.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,n),this.encodings=n,this.lastEncodedDimensions=t;for(const t of this.simulcastCodecs){var i=B(t,2);const n=i[0],r=i[1];if(!r.sender||"closed"===(null===(e=r.sender.transport)||void 0===e?void 0:e.state))continue;if(!fs(n))continue;const s=hc(this,n,Object.assign({},this.publishOptions));s&&(yield this.applyEncodingsToSender(r.sender,s),r.encodings=s)}}catch(e){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:e}))}finally{t()}}))}applyEncodingsToSender(e,t){return Cn(this,void 0,void 0,(function*(){const i=e.getParameters();i.encodings&&i.encodings.length===t.length&&(i.encodings.forEach(((e,i)=>{if(!1===e.active)return;const n=t[i];void 0!==n.scaleResolutionDownBy&&(e.scaleResolutionDownBy=n.scaleResolutionDownBy),void 0!==n.maxBitrate&&(e.maxBitrate=n.maxBitrate),void 0!==n.maxFramerate&&(e.maxFramerate=n.maxFramerate),void 0!==n.priority&&(e.priority=n.priority,e.networkPriority=n.priority)})),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:i.encodings})),yield e.setParameters(i))}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Cn(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r,s,a,o,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Pn(i.simulcastCodecs.values());!(r=(l=yield h.next()).done);u=!0){o=l.value,u=!1;const e=o;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(e){s={error:e}}finally{try{u||r||!(a=h.return)||(yield a.call(h))}finally{if(s)throw s.error}}}()}))}setDegradationPreference(e){return Cn(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 Cn(this,void 0,void 0,(function*(){var t,i,n,r,s,a,o;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Hs(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Pn(e);!(r=(n=yield i.next()).done);t=!0){o=n.value,t=!1;const e=o;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield kc(t.sender,t.encodings,e.qualities,this.senderLock,Hs(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(Hs(e.codec),e.qualities)}}catch(e){s={error:e}}finally{try{t||r||!(a=i.return)||(yield a.call(i))}finally{if(s)throw s.error}}return c}))}setPublishingLayers(e,t){return Cn(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 kc(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return Cn(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&&Hs(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 Cn(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ys()&&this.isInBackground&&this.source===Us.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function kc(e,t,i,n,r,s,a){return Cn(this,void 0,void 0,(function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),o=n.encodings;if(!o)return;if(o.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:o,senderEncodings:t}));let c=!1;if(!1&&o[0].scalabilityMode);else{if(r){i.some((e=>e.enabled))&&i.forEach((e=>e.enabled=!0))}o.forEach(((e,n)=>{var r;let o=null!==(r=e.rid)&&void 0!==r?r:"";""===o&&(o="q");const d=yc(o),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),a),zs()&&(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=o,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}}))}function yc(e){switch(e){case"f":default:return Ns.HIGH;case"h":return Ns.MEDIUM;case"q":return Ns.LOW}}function bc(e,t,i,n){if(!i)return[new yt({quality:Ns.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,r=new fc(n),s=[],a="h"==r.suffix?1.5:2,o="h"==r.suffix?2:3;for(let n=0;n<r.spatial;n+=1)s.push(new yt({quality:Math.min(Ns.HIGH,r.spatial-1)-n,width:Math.ceil(e/Math.pow(a,n)),height:Math.ceil(t/Math.pow(a,n)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(o,n)):0,ssrc:0}));return s}return i.map((i=>{var n,r,s;const a=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let o=yc(null!==(r=i.rid)&&void 0!==r?r:"");return new yt({quality:o,width:Math.ceil(e/a),height:Math.ceil(t/a),bitrate:null!==(s=i.maxBitrate)&&void 0!==s?s:0,ssrc:0})}))}const Tc="_lossy",Sc="_reliable",Cc="_data_track",wc="leave-reconnect";var Ec,Rc;!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"}(Ec||(Ec={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"}(Rc||(Rc={}));class Pc extends Dn.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=$o.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ec.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=kn,this.reliableDataSequence=1,this.reliableMessageBuffer=new wo,this.reliableReceivedState=new Eo(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new ma,this.handleDataChannel=e=>Cn(this,[e],void 0,(function(e){var t=this;let i=e.channel;return function*(){if(!i)return;let e;if(i.label===Sc)t.reliableDCSub=i,e=t.handleDataMessage;else if(i.label===Tc)t.lossyDCSub=i,e=t.handleDataMessage;else{if(i.label!==Cc)return;t.dataTrackDCSub=i,e=t.handleDataTrackMessage}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label)),i.onmessage=e}()})),this.handleDataMessage=e=>Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;const a=yield this.dataProcessLock.lock();try{let a;if(e.data instanceof ArrayBuffer)a=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",{data:e.data});a=yield e.data.arrayBuffer()}const o=Tt.fromBinary(new Uint8Array(a));if(o.sequence>0&&""!==o.participantSid){const e=this.reliableReceivedState.get(o.participantSid);if(e&&o.sequence<=e)return;this.reliableReceivedState.set(o.participantSid,o.sequence)}if("speaker"===(null===(t=o.value)||void 0===t?void 0:t.case))this.emit(Zr.ActiveSpeakersUpdate,o.value.value.speakers);else if("encryptedPacket"===(null===(i=o.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up");const e=yield null===(n=this.e2eeManager)||void 0===n?void 0:n.handleEncryptedData(o.value.value.encryptedValue,o.value.value.iv,o.participantIdentity,o.value.value.keyIndex),t=wt.fromBinary(e.payload),i=new Tt({value:t.value,participantIdentity:o.participantIdentity,participantSid:o.participantSid});"user"===(null===(r=i.value)||void 0===r?void 0:r.case)&&Ic(i,i.value.value),this.emit(Zr.DataPacketReceived,i,o.value.value.encryptionType)}else"user"===(null===(s=o.value)||void 0===s?void 0:s.case)&&Ic(o,o.value.value),this.emit(Zr.DataPacketReceived,o,mt.NONE)}finally{a()}})),this.handleDataTrackMessage=e=>Cn(this,void 0,void 0,(function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",{data:e.data});t=yield e.data.arrayBuffer()}this.emit("dataTrackPacketReceived",new Uint8Array(t))})),this.handleDataError=e=>{if(this._isClosed)return;const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if("undefined"!=typeof RTCErrorEvent&&e instanceof RTCErrorEvent&&e.error){const i=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(i.message),{error:i,errorDetail:i.errorDetail,sctpCauseCode:i.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleDataChannelClose=e=>()=>{var t;this._isClosed||"connected"!==(null===(t=this.pcManager)||void 0===t?void 0:t.publisher.getConnectionState())||this.log.error("publisher data channel '".concat(Rc[e],"' closed unexpectedly"),this.logContext)},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected")),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.emit(Zr.Disconnected),this.close()},n=Date.now()-this.reconnectStart;let r=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==r?(e===wc&&(r=0),this.log.debug("reconnecting in ".concat(r,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(Zr.TokenRefreshed,this.token),this.reconnectTimeout=hs.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),r)):i(n)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===Ec.Connected&&e();const i=()=>{this.off(Zr.Disconnected,n),e()},n=()=>{this.off(Zr.Restarted,i),t()};this.once(Zr.Restarted,i),this.once(Zr.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{if(e===Rc.RELIABLE){const t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Zr.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.onRtpMapAvailable=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(Zr.RTPVideoMapUpdate,t)},this.handleBrowserOnLine=()=>Cn(this,void 0,void 0,(function*(){if(!this.url)return;(yield fetch(fa(this.url),{method:"HEAD"}).then((e=>e.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===bo.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===bo.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(nt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>Cn(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(fa(this.url),{method:"HEAD"}),Vs(4e3).then((()=>Promise.reject()))])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=yn(null!==(t=e.loggerName)&&void 0!==t?t:fn.Engine,(()=>this.logContext)),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new To(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new d,this.dataProcessLock=new d,this.dcBufferStatus=new Map([[Rc.RELIABLE,!0],[Rc.LOSSY,!0],[Rc.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(Zr.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Zr.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Zr.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Zr.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Zr.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Zr.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Zr.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Zr.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(Zr.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(Zr.Joined,e),this.on(Zr.Closing,(()=>{var e,t;null===(t=(e=this.bufferStatusLowClosingFuture).reject)||void 0===t||t.call(e,new ss("engine closed"))})),this.bufferStatusLowClosingFuture.promise.catch((()=>{}))}get logContext(){var e,t,i,n,r,s;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===(s=null===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===s?void 0:s.identity,participantID:this.participantSid}}join(e,t,i,n){return Cn(this,arguments,void 0,(function(e,t,i,n){var r=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var a,o,c;r._isNewlyCreated=!1,r.url=e,r.token=t,r.signalOpts=i,r.maxJoinAttempts=i.maxRetries;try{r.joinAttempts+=1,r.setupSignalClientCallbacks();const d=!s&&Ia()&&!zs();let l;if(d){r.pcManager||(yield r.configure(),r.applyInitialPublisherLayout());const e=yield null===(a=r.pcManager)||void 0===a?void 0:a.publisher.createInitialOffer();e&&(l=Co(e.offer,e.offerId))}if(null==n?void 0:n.aborted)throw ts.cancelled("Connection aborted");if(!s&&r.shouldFailOnV1Path)throw r.shouldFailOnV1Path=!1,ts.serviceNotFound("Simulated v1 path failure","v0-rtc");const u=yield r.client.join(e,t,i,n,s,l);r._isClosed=!1,r.latestJoinResponse=u,r.participantSid=null===(o=u.participant)||void 0===o?void 0:o.sid,r.subscriberPrimary=u.subscriberPrimary,d?null===(c=r.pcManager)||void 0===c||c.updateConfiguration(r.makeRTCConfiguration(u)):(r.pcManager||(yield r.configure(u,!s),s||r.applyInitialPublisherLayout()),r.subscriberPrimary&&!u.fastPublish||r.negotiate().catch((e=>{r.log.error(e)}))),r.registerOnLineListener(),r.clientConfiguration=u.clientConfiguration,r.emit(Zr.SignalConnected,u);let h=u.serverInfo;return h||(h={version:u.serverVersion,region:u.serverRegion}),r.log.info("connected to Livekit Server ".concat(Object.entries(h).map((e=>{let t=B(e,2),i=t[0],n=t[1];return"".concat(i,": ").concat(n)})).join(", "))),{joinResponse:u,serverInfo:h}}catch(a){if(a instanceof ts)if(a.reason===Jr.ServerUnreachable){if(r.log.warn("Couldn't connect to server, attempt ".concat(r.joinAttempts," of ").concat(r.maxJoinAttempts)),r.joinAttempts<r.maxJoinAttempts)return r.join(e,t,i,n,s)}else if(a.reason===Jr.ServiceNotFound)return r.log.warn("Initial connection failed: ".concat(a.message," – Retrying")),r.pcManager&&(r.pcManager.onStateChange=void 0,yield r.cleanupPeerConnections()),r.join(e,t,i,n,!0);throw a}}()}))}close(){return Cn(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(Zr.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return Cn(this,void 0,void 0,(function*(){var e;const t=e=>{e&&(e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null,e.close())};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0,this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new wo,this.reliableDataSequence=1,this.reliableReceivedState.clear()}))}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return Cn(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new ns("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(ts.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",{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 Cn(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return Cn(this,void 0,void 0,(function*(){var i;if(!this.pcManager||this.pcManager.currentState===Xo.NEW){if(e){this.participantSid=null===(i=e.participant)||void 0===i?void 0:i.sid;const n=this.makeRTCConfiguration(e);this.pcManager=new Zo(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,n)}else{const e=this.makeRTCConfiguration();this.pcManager=new Zo("publisher-only",this.loggerOptions,e)}this.emit(Zr.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=(e,t,i)=>Cn(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(e)),["closed","disconnected","failed"].includes(t)&&(this.publisherConnectionPromise=void 0),e===Xo.CONNECTED){const e=this.pcState===Ec.New;this.pcState=Ec.Connected,e&&this.emit(Zr.Connected,this.latestJoinResponse)}else e===Xo.FAILED&&(this.pcState!==Ec.Connected&&this.pcState!==Ec.Reconnecting||(this.pcState=Ec.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?nt.RR_SUBSCRIBER_FAILED:nt.RR_PUBLISHER_FAILED)));const n=this.client.isDisconnected||this.client.currentState===bo.RECONNECTING,r=[Xo.FAILED,Xo.CLOSING,Xo.CLOSED].includes(e);n&&r&&!this._isClosed&&this.emit(Zr.Offline)})),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(Zr.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}}))}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>Cn(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i}),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>Cn(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{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),{cid:e.cid});const i=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Zr.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Zr.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(Zr.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Zr.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Zr.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(Zr.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(Zr.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(Zr.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(Zr.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",nt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(null==e?void 0:e.action,")"),{reason:null==e?void 0:e.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(Zr.ServerRegionsReported,e.regions)),e.action){case Pi.DISCONNECT:this.emit(Zr.Disconnected,null==e?void 0:e.reason),this.close();break;case Pi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wc);break;case Pi.RESUME:this.handleDisconnect(wc)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!Va())&&Ba()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(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===tt.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(){this.createDataChannels(),Xs()||this.addMediaSections(3,3)}addMediaSections(e,t){var i,n;const r={direction:"recvonly"};for(let t=0;t<e;t++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("audio",r);for(let e=0;e<t;e++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("video",r)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null,this.lossyDC.onclose=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null,this.reliableDC.onclose=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null,this.dataTrackDC.onclose=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Tc,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Sc,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(Cc,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.onclose=this.handleDataChannelClose(Rc.LOSSY),this.reliableDC.onclose=this.handleDataChannelClose(Rc.RELIABLE),this.dataTrackDC.onclose=this.handleDataChannelClose(Rc.DATA_TRACK_LOSSY),this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Rc.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Rc.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Rc.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval((()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Rc.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,8192),262144)}}),1e3))}createSender(e,t,i){return Cn(this,void 0,void 0,(function*(){let n;if(qs())n=yield this.createTransceiverRTCRtpSender(e,t,i);else{if(!Ks())throw new ss("Required webRTC APIs not supported on this device");this.log.warn("using add-track fallback"),n=yield this.createRTCRtpSender(e.mediaStreamTrack)}return this.setupFrameMetadataSender(n,t),n}))}createSimulcastSender(e,t,i,n){return Cn(this,void 0,void 0,(function*(){let r;if(qs())r=yield this.createSimulcastTransceiverSender(e,t,i,n);else{if(!Ks())throw new ss("Cannot stream on this device");this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack)}return r&&this.setupFrameMetadataSender(r,i),r}))}get frameMetadataWorker(){var e,t;return null===(t=null!==(e=this.options.frameMetadata)&&void 0!==e?e:this.options.packetTrailer)||void 0===t?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n,r;const s=this.frameMetadataWorker;if(!s||(null===(i=this.signalOpts)||void 0===i?void 0:i.e2eeEnabled))return;const a=null!==(n=t.frameMetadata)&&void 0!==n?n:t.packetTrailer,o=Ka(a);if(Va())return void(o&&(e.transform=new RTCRtpScriptTransform(s,{kind:"encode",packetTrailer:a})));if(!qa(null!==(r=this.options.frameMetadata)&&void 0!==r?r:this.options.packetTrailer)||!("createEncodedStreams"in e))return void(o&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext));const c=e.createEncodedStreams(),d=c.readable,l=c.writable;o?s.postMessage({kind:"encode",data:{readableStream:d,writableStream:l,packetTrailer:a}},[d,l]):d.pipeTo(l)}createTransceiverRTCRtpSender(e,t,i){return Cn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ss("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Sa(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:n};i&&(r.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return Cn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ss("publisher is closed");const r={direction:"sendonly"};n&&(r.sendEncodings=n);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,s.sender),s.sender}))}createRTCRtpSender(e){return Cn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ss("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return Cn(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)this.log.warn("already attempting reconnect, returning early");else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==tt.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:Xo.NEW)!==Xo.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 ss?(this.log.debug("received unrecoverable error",{error:e}),t=!1):e instanceof us||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",nt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(Zr.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",{error:e})}return null}restartConnection(e){return Cn(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new ss("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(Zr.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"),new us;i=(yield this.join(null!=e?e:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(e){if(e instanceof ts&&e.reason===Jr.NotAllowed)throw new ss("could not reconnect, token might be expired");throw new us}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Zr.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==bo.CONNECTED)throw new us("Signal connection got severed during reconnect");null===(t=this.regionStrategy)||void 0===t||t.resetAttempts(),this.emit(Zr.Restarted)}catch(e){const t=yield null===(i=this.regionStrategy)||void 0===i?void 0:i.getNextUrl();if(t)return void(yield this.restartConnection(t));throw null===(n=this.regionStrategy)||void 0===n||n.resetAttempts(),e}}))}resumeConnection(e){return Cn(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new ss("could not reconnect, url or token not saved");if(!this.pcManager)throw new ss("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(Zr.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,{error:e})),e instanceof ts&&e.reason===Jr.NotAllowed)throw new ss("could not reconnect, token might be expired");if(e instanceof ts&&e.reason===Jr.LeaveRequest)throw e;throw new us(t)}if(this.emit(Zr.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");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==bo.CONNECTED)throw new us("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(Zr.Resumed)}))}waitForPCInitialConnection(e,t){return Cn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ss("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Cn(this,void 0,void 0,(function*(){this.pcState=Ec.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Vs(2e3),!this.pcManager)throw new ss("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ec.Connected}catch(e){throw this.pcState=Ec.Disconnected,ts.internal("could not establish PC connection, ".concat(e.message))}}))}publishRpcAck(e,t){return Cn(this,void 0,void 0,(function*(){const i=new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcAck",value:new Lt({requestId:t})}});yield this.sendDataPacket(i,Rc.RELIABLE)}))}sendDataPacket(e,t){return Cn(this,void 0,void 0,(function*(){var i,n;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=function(e){var t,i,n,r,s;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"speaker"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"transcription"!==(null===(r=e.value)||void 0===r?void 0:r.case)&&"encryptedPacket"!==(null===(s=e.value)||void 0===s?void 0:s.case))return new wt({value:e.value})}(e);if(t){const i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Ct({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===Rc.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const r=e.toBinary(),s=Math.min(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.getMaxPublisherMessageSize())&&void 0!==n?n:64e3,64e3);if(void 0!==s&&0!==s&&r.byteLength>s)throw new os("cannot publish data packet larger than ".concat(s," bytes (got ").concat(r.byteLength,")"));switch(t){case Rc.LOSSY:case Rc.DATA_TRACK_LOSSY:return this.sendLossyBytes(r,t);case Rc.RELIABLE:const i=this.dataChannelForKind(t);if(i){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:r,sequence:e.sequence}),this.attemptingReconnect)return;i.send(r)}this.updateAndEmitDCBufferStatus(t)}}))}sendLossyBytes(e,t){return Cn(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"drop";return function*(){yield i.ensurePublisherConnected(t);const r=i.dataChannelForKind(t);if(r){if(!i.isBufferStatusLow(t))switch(n){case"wait":yield i.waitForBufferStatusLow(t);break;case"drop":return i.lossyDataDropCount+=1,void(i.lossyDataDropCount%100==0&&i.log.warn("dropping lossy data channel messages, total dropped: ".concat(i.lossyDataDropCount)))}if(i.lossyDataStatCurrentBytes+=e.byteLength,i.attemptingReconnect)return;r.send(e)}i.updateAndEmitDCBufferStatus(t)}()}))}resendReliableMessagesForResume(e){return Cn(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(Rc.RELIABLE);const t=this.dataChannelForKind(Rc.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach((e=>{t.send(e.data)}))),this.updateAndEmitDCBufferStatus(Rc.RELIABLE)}))}waitForBufferStatusLow(e){return Cn(this,void 0,void 0,(function*(){return new jr(((t,i)=>Cn(this,void 0,void 0,(function*(){if(this.isClosed&&i(new ss("engine closed")),this.isBufferStatusLow(e))t();else{const n=this.dataChannelForKind(e);if(!n)return void i(new ss("DataChannel not found, kind: ".concat(e)));this.bufferStatusLowClosingFuture.promise.catch((e=>i(e))),n.addEventListener("bufferedamountlow",(()=>t()),{once:!0})}}))))}))}ensureDataTransportConnected(e){return Cn(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 ss("PC manager is closed");const r=i?t.pcManager.subscriber:t.pcManager.publisher,s=i?"Subscriber":"Publisher";if(!r)throw ts.internal("".concat(s," connection not set"));let a=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),a=!0),a||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(a=!0),a&&t.negotiate().catch((e=>{t.log.error(e)}));const o=t.dataChannelForKind(e,i);if("open"===(null==o?void 0:o.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(r.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield Vs(50)}throw ts.internal("could not establish ".concat(s," connection, state: ").concat(r.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return Cn(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){if(!this.pcManager)return!1;return!![Xo.CONNECTING,Xo.CONNECTED].includes(this.pcManager.currentState)&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Cn(this,void 0,void 0,(function*(){return new jr(((e,t)=>Cn(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new as("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.dataTrackDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new as("cannot negotiate on closed engine")),this.on(Zr.Closing,n),this.on(Zr.Restarting,n),this.pcManager.publisher.off(Vo,this.onRtpMapAvailable),this.pcManager.publisher.once(Vo,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),e()}catch(n){if(i.signal.aborted)return void e();n instanceof as&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",nt.RR_UNKNOWN),n instanceof Error?t(n):t(new Error(String(n)))}finally{this.off(Zr.Closing,n),this.off(Zr.Restarting,n)}}))))}))}dataChannelForKind(e,t){switch(e){case Rc.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case Rc.LOSSY:return t?this.lossyDCSub:this.lossyDC;case Rc.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,i){var n,r,s,a;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup");const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getRemoteDescription(),l=null===(r=this.pcManager.subscriber)||void 0===r?void 0:r.getLocalDescription(),u=null===(a=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===a||a,h=new Array,p=new Array;e.forEach((e=>{e.isDesired!==u&&h.push(e.trackSid),e.isEnabled||p.push(e.trackSid)})),this.client.sendSyncState(new Wi({answer:"publisher-only"===this.pcManager.mode?c?Co({sdp:c.sdp,type:c.type}):void 0:l?Co({sdp:l.sdp,type:l.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?Co({sdp:o.sdp,type:o.type}):void 0:d?Co({sdp:d.sdp,type:d.type}):void 0,subscription:new bi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:As(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new zi({publisherSid:t,lastSeq:e}))),publishDataTracks:i.map((e=>new oi({info:go.toProtobuf(e)})))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Gi({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(Rc.LOSSY),Zt.PUBLISHER),t(this.dataChannelForKind(Rc.RELIABLE),Zt.PUBLISHER),t(this.dataChannelForKind(Rc.LOSSY,!0),Zt.SUBSCRIBER),t(this.dataChannelForKind(Rc.RELIABLE,!0),Zt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&hs.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){$s()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){$s()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(i){const e=Object.entries(this.midToTrackId).find((e=>B(e,1)[0]===i));if(e)return e[1]}}}function Ic(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}const Mc=5e3;class Dc{static fetchRegionSettings(e,t,i){return Cn(this,void 0,void 0,(function*(){const n=yield Dc.fetchLock.lock();try{const n=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){const e=function(e){var t;const i=e.get("Cache-Control");if(i){const e=null===(t=i.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers),t=e?1e3*e:Mc;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===n.status?ts.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):ts.internal("Could not fetch region settings: ".concat(n.statusText))}catch(e){throw e instanceof ts?e:(null==i?void 0:i.aborted)?ts.cancelled("Region fetching was aborted"):ts.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{n()}}))}static scheduleRefetch(e,t,i){return Cn(this,void 0,void 0,(function*(){const n=Dc.settingsTimeouts.get(e.hostname);clearTimeout(n),Dc.settingsTimeouts.set(e.hostname,setTimeout((()=>Cn(this,void 0,void 0,(function*(){try{const i=yield Dc.fetchRegionSettings(e,t);Dc.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof ts&&n.reason===Jr.NotAllowed)return void kn.debug("token is not valid, cancelling auto region refresh");kn.debug("auto refetching of region settings failed",{error:n}),Dc.scheduleRefetch(e,t,i)}}))),i))}))}static updateCachedRegionSettings(e,t,i){Dc.cache.set(e.hostname,i),Dc.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=Dc.settingsTimeouts.get(e);t&&(clearTimeout(t),Dc.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Dc.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout((()=>{const t=Dc.connectionTrackers.get(e);t&&0===t.connectionCount&&(kn.debug("stopping region refetch after disconnect delay",{hostname:e}),Dc.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(e){const t=Dc.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Dc.connectionTrackers.get(e);t||(t={connectionCount:0},Dc.connectionTrackers.set(e,t)),t.connectionCount++,Dc.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Dc.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&Dc.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const i=this.getServerUrl(),n=Dc.cache.get(i.hostname);Dc.scheduleRefetch(this.serverUrl,this.token,null!==(t=null==n?void 0:n.maxAgeInMs)&&void 0!==t?t:Mc)}isCloud(){return Zs(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Cn(this,void 0,void 0,(function*(){return Dc.fetchRegionSettings(this.serverUrl,this.token,e)}))}getNextBestRegionUrl(e){return Cn(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Dc.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Dc.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(i.length>0){const e=i[0];return this.attemptedRegions.push(e),kn.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Dc.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Dc.cache=new Map,Dc.settingsTimeouts=new Map,Dc.connectionTrackers=new Map,Dc.fetchLock=new d;class Ac{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new ls("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Qr.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new ls("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Qr.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class _c extends Ac{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();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();e.closed.catch((()=>{}));const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>Cn(this,void 0,void 0,(function*(){try{const t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;const i=yield new Promise(((i,n)=>{if(t){const r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),e.read().then(i,n).finally((()=>{t.removeEventListener("abort",r)}))}else e.read().then(i,n)}));return i.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(i.value),{done:!1,value:i.value.content})}catch(e){throw t(),e}})),return(){return Cn(this,void 0,void 0,(function*(){return t(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Cn(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,s;let a=new Set;const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Pn(o);!(i=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;a.add(e)}}catch(e){n={error:e}}finally{try{d||i||!(r=l.return)||(yield r.call(l))}finally{if(n)throw n.error}}return Array.from(a)}()}))}}class Lc extends Ac{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=ka(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch((()=>{}));const t=new TextDecoder("utf-8",{fatal:!0}),i=this.signal,n=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>Cn(this,void 0,void 0,(function*(){try{if(null==i?void 0:i.aborted)throw i.reason;const n=yield new Promise(((t,n)=>{if(i){const r=()=>n(i.reason);i.addEventListener("abort",r,{once:!0}),e.read().then(t,n).finally((()=>{i.removeEventListener("abort",r)}))}else e.read().then(t,n)}));if(n.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(n.value);try{e=t.decode(n.value.content)}catch(e){throw new ls("Cannot decode datastream chunk ".concat(n.value.chunkIndex," as text: ").concat(e),Qr.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw n(),e}})),return(){return Cn(this,void 0,void 0,(function*(){return n(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Cn(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,s;let a="";const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Pn(o);!(i=(c=yield l.next()).done);d=!0){s=c.value,d=!1;a+=s}}catch(e){n={error:e}}finally{try{d||i||!(r=l.return)||(yield r.call(l))}finally{if(n)throw n.error}}return a}()}))}}class Oc{constructor(){this.log=kn,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const e=t.packet,i=t.encryptionType;this.handleDataStreamPacket(e,i)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new ls('A text stream handler for topic "'.concat(e,'" has already been set.'),Qr.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new ls('A byte stream handler for topic "'.concat(e,'" has already been set.'),Qr.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.entries()).filter((t=>t[1].sendingParticipantIdentity===e)),i=Array.from(this.byteStreamControllers.entries()).filter((t=>t[1].sendingParticipantIdentity===e));if(t.length>0||i.length>0){const s=new ls("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Qr.AbnormalEnd);for(const e of i){var n=B(e,2);const t=n[0];n[1].controller.error(s),this.byteStreamControllers.delete(t)}for(const e of t){var r=B(e,2);const t=r[0];r[1].controller.error(s),this.textStreamControllers.delete(t)}}}handleDataStreamPacket(e,t){if(this.isConnected)switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}else this.bufferedPackets.push({packet:e,encryptionType:t})}handleStreamHeader(e,t,i){var n;if("byteHeader"===e.contentHeader.case){const r=this.byteStreamHandlers.get(e.topic);if(!r)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const a={id:e.streamId,name:null!==(n=e.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ka(e.timestamp),attributes:e.attributes,encryptionType:i},o=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(e.streamId))throw new ls("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Qr.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new _c(a,o,ka(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const n=this.textStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let r;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,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},a=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(e.streamId))throw new ls("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Qr.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now(),sendingParticipantIdentity:t})}});n(new Lc(s,a,ka(e.totalLength)),{identity:t})}}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new ls("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Qr.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new ls("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),Qr.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new ls("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Qr.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new ls("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),Qr.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class xc{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 Cn(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 Nc extends xc{}class Uc extends xc{}class Fc{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Cn(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),r=(new TextEncoder).encode(e).byteLength,s=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),a=new Array(s?s.length+1:1).fill(0),o=(e,i)=>{var n;a[i]=e;const r=a.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,r)},c=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:s,attributes:null==t?void 0:t.attributes});return yield c.write(e),o(1,0),yield c.close(),(null==t?void 0:t.attachments)&&s&&(yield Promise.all(t.attachments.map(((e,i)=>Cn(this,void 0,void 0,(function*(){return this._sendFile(s[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,i+1)}})})))))),c.info}))}streamText(e){return Cn(this,void 0,void 0,(function*(){var t,i,n;const r=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:r,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,encryptionType:(null===(n=this.engine.e2eeManager)||void 0===n?void 0:n.isDataChannelEncryptionEnabled)?mt.GCM:mt.NONE,attachedStreamIds:null==e?void 0:e.attachedStreamIds},a=new Qt({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:ya(s.timestamp),totalLength:ya(s.size),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Gt({version:null==e?void 0:e.version,attachedStreamIds:s.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?zt.UPDATE:zt.CREATE})}}),o=null==e?void 0:e.destinationIdentities,c=new Tt({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,Rc.RELIABLE);let d=0;const l=this.engine,u=new WritableStream({write(e){return Cn(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)){const e=new Yt({content:t,streamId:r,chunkIndex:ya(d)}),i=new Tt({destinationIdentities:o,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(i,Rc.RELIABLE),d+=1}}))},close(){return Cn(this,void 0,void 0,(function*(){const e=new $t({streamId:r}),t=new Tt({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield l.sendDataPacket(t,Rc.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let h=()=>Cn(this,void 0,void 0,(function*(){yield p.close()}));l.once(Zr.Closing,h);const p=new Nc(u,s,(()=>this.engine.off(Zr.Closing,h)));return p}))}sendFile(e,t){return Cn(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return Cn(this,void 0,void 0,(function*(){var n;const r=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}),s=t.stream().getReader();for(;;){const e=yield s.read(),t=e.done,i=e.value;if(t)break;yield r.write(i)}return yield r.close(),r.info}))}streamBytes(e){return Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),o=null==e?void 0:e.destinationIdentities,c={id:a,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(r=null==e?void 0:e.name)&&void 0!==r?r:"unknown",encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?mt.GCM:mt.NONE},l=new Qt({totalLength:ya(c.size),mimeType:c.mimeType,streamId:a,topic:c.topic,timestamp:ya(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Jt({name:c.name})}}),u=new Tt({destinationIdentities:o,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,Rc.RELIABLE);let h=0;const p=new d,m=this.engine,g=this.log,f=new WritableStream({write(e){return Cn(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),n=new Tt({destinationIdentities:o,value:{case:"streamChunk",value:new Yt({content:t,streamId:a,chunkIndex:ya(h)})}});yield m.sendDataPacket(n,Rc.RELIABLE),h+=1,i+=t.byteLength}}finally{t()}}))},close(){return Cn(this,void 0,void 0,(function*(){const e=new $t({streamId:a}),t=new Tt({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,Rc.RELIABLE)}))},abort(e){g.error("Sink error:",e)}});return new Uc(f,c)}))}}function jc(e){if(0===e.length){return(new AbortController).signal}if(1===e.length)return e[0];for(const t of e)if(t.aborted)return t;const t=new AbortController,i=Array(e.length);return e.forEach(((e,n)=>{const r=()=>{t.abort(e.reason),(()=>{for(const e of i)e()})()};e.addEventListener("abort",r),i[n]=()=>e.removeEventListener("abort",r)})),t.signal}function Bc(e){const t=new AbortController;return setTimeout((()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))}),e),t.signal}var Vc,qc,Kc;!function(e){e[e.TooShort=0]="TooShort",e[e.HeaderOverrun=1]="HeaderOverrun",e[e.MissingExtWords=2]="MissingExtWords",e[e.UnsupportedVersion=3]="UnsupportedVersion",e[e.InvalidHandle=4]="InvalidHandle",e[e.MalformedExt=5]="MalformedExt"}(Vc||(Vc={}));class Hc extends Gr{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Vc[t]}static tooShort(){return new Hc("Too short to contain a valid header",Vc.TooShort)}static headerOverrun(){return new Hc("Header exceeds total packet length",Vc.HeaderOverrun)}static missingExtWords(){return new Hc("Extension word indicator is missing",Vc.MissingExtWords)}static unsupportedVersion(e){return new Hc("Unsupported version ".concat(e),Vc.UnsupportedVersion)}static invalidHandle(e){return new Hc("invalid track handle: ".concat(e.message),Vc.InvalidHandle,{cause:e})}static malformedExt(e){return new Hc("Extension with tag ".concat(e," is malformed"),Vc.MalformedExt)}}!function(e){e[e.TooSmallForHeader=0]="TooSmallForHeader",e[e.TooSmallForPayload=1]="TooSmallForPayload"}(qc||(qc={}));class Wc extends Gr{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=qc[t]}static tooSmallForHeader(){return new Wc("Buffer cannot fit header",qc.TooSmallForHeader)}static tooSmallForPayload(){return new Wc("Buffer cannot fit payload",qc.TooSmallForPayload)}}class zc{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),n=this.toBinaryInto(i);if(e!==n)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(n," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}!function(e){e[e.UserTimestamp=2]="UserTimestamp",e[e.E2ee=1]="E2ee"}(Kc||(Kc={}));class Gc extends zc{}class Jc extends Gc{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+Jc.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Jc.tag),t+=1,e.setUint8(t,Jc.lengthBytes),t+=1,e.setBigUint64(t,this.timestamp),t+=8;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:Jc.tag,lengthBytes:Jc.lengthBytes,timestamp:this.timestamp}}}Jc.tag=Kc.UserTimestamp,Jc.lengthBytes=8;class Qc extends Gc{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+Qc.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Qc.tag),t+=1,e.setUint8(t,Qc.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let i=0;i<this.iv.length;i+=1)e.setUint8(t,this.iv[i]),t+=1;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:Qc.tag,lengthBytes:Qc.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}Qc.tag=Kc.E2ee,Qc.lengthBytes=13;class Yc extends zc{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){t+=this.e2ee.toBinaryInto(e)}if(this.userTimestamp){t+=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t))}const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){const t=lo(e);let i,n,r=0;for(;t.byteLength-r>=2;){const e=t.getUint8(r);r+=1;const s=t.getUint8(r);if(r+=1,0!==e)switch(e){case Kc.UserTimestamp:if(t.byteLength-r<Jc.lengthBytes)throw Hc.malformedExt(e);i=new Jc(t.getBigUint64(r)),r+=s;break;case Kc.E2ee:if(t.byteLength-r<Qc.lengthBytes)throw Hc.malformedExt(e);const a=t.getUint8(r),o=new Uint8Array(12);for(let e=0;e<o.length;e+=1){let i=r;i+=1,i+=1*e,o[e]=t.getUint8(i)}n=new Qc(a,o),r+=s;break;default:if(t.byteLength-r<s)throw Hc.malformedExt(e);r+=s}}return[new Yc({userTimestamp:i,e2ee:n}),t.byteLength]}toJSON(){var e,t,i,n;return{userTimestamp:null!==(t=null===(e=this.userTimestamp)||void 0===e?void 0:e.toJSON())&&void 0!==t?t:null,e2ee:null!==(n=null===(i=this.e2ee)||void 0===i?void 0:i.toJSON())&&void 0!==n?n:null}}}const $c={from:e=>({payload:e.payload,extensions:new Yc({userTimestamp:e.userTimestamp?new Jc(e.userTimestamp):void 0})}),lossyIntoFrame(e){var t;return{payload:e.payload,userTimestamp:null===(t=e.extensions.userTimestamp)||void 0===t?void 0:t.timestamp}}},Xc=Symbol.for("lk.track"),Zc=Symbol.for("lk.data-track");class ed{constructor(e,t,i){this.trackSymbol=Xc,this.isLocal=!1,this.typeSymbol=Zc,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{const t=B(this.manager.openSubscriptionStream(this.info.sid,null==e?void 0:e.signal,null==e?void 0:e.bufferSize),2),i=t[0];return t[1].catch((()=>{})),i}catch(e){throw e}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class td extends zc{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=null!==(t=e.extensions)&&void 0!==t?t:new Yc}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((2+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-2-e}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,i=e.paddingLengthBytes;let n=12;return t>0&&(n+=2+t+i),n}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Wc.tooSmallForHeader();let t,i=0;switch(this.marker){case id.Inter:t=0;break;case id.Final:t=1;break;case id.Start:t=2;break;case id.Single:t=3}i|=t<<3;const n=this.extensionsMetrics(),r=n.lengthBytes,s=n.lengthWords,a=n.paddingLengthBytes;r>0&&(i|=4);let o=0;if(e.setUint8(o,i),o+=1,e.setUint8(o,0),o+=1,e.setUint16(o,this.trackHandle),o+=2,e.setUint16(o,this.sequence.value),o+=2,e.setUint16(o,this.frameNumber.value),o+=2,e.setUint32(o,this.timestamp.asTicks()),o+=4,r>0){const t=s-1;e.setUint16(o,t),o+=2;o+=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));for(let t=0;t<a;t+=1)e.setUint8(o,0),o+=1}const c=this.toBinaryLengthBytes();if(o!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(o," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){const t=lo(e);if(t.byteLength<12)throw Hc.tooShort();let i=0;const n=t.getUint8(i);i+=1;const r=n>>5&7;if(r>0)throw Hc.unsupportedVersion(r);let s;switch(n>>3&3){case 2:s=id.Start;break;case 1:s=id.Final;break;case 3:s=id.Single;break;default:s=id.Inter}const a=(n>>2&1)>0;let o;i+=1;try{o=po.fromNumber(t.getUint16(i))}catch(e){throw e instanceof ho&&(e.isReason(uo.Reserved)||e.isReason(uo.TooLarge))?Hc.invalidHandle(e):e}i+=2;const c=ao.u16(t.getUint16(i));i+=2;const d=ao.u16(t.getUint16(i));i+=2;const l=oo.fromRtpTicks(t.getUint32(i));i+=4;let u=new Yc;if(a){if(t.byteLength-i<2)throw Hc.missingExtWords();let e=t.getUint16(i);i+=2;let n=4*(e+1)-2;if(i+n>t.byteLength)throw Hc.headerOverrun();let r=new DataView(t.buffer,t.byteOffset+i,n);const s=B(Yc.fromBinary(r),2);u=s[0],i+=s[1]}return[new td({marker:s,trackHandle:o,sequence:c,frameNumber:d,timestamp:l,extensions:u}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var id;!function(e){e[e.Start=0]="Start",e[e.Inter=1]="Inter",e[e.Final=2]="Final",e[e.Single=3]="Single"}(id||(id={}));class nd extends zc{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;if(t+=this.header.toBinaryInto(e),e.byteLength-t<this.payload.byteLength)throw Wc.tooSmallForPayload();for(let i=0;i<this.payload.length;i+=1)e.setUint8(t,this.payload[i]),t+=1;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return i}static fromBinary(e){const t=lo(e),i=B(td.fromBinary(t),2),n=i[0],r=i[1],s=t.buffer.slice(t.byteOffset+r,t.byteOffset+t.byteLength);return[new nd(n,new Uint8Array(s)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const rd=yn(fn.DataTracks);class sd extends Gr{constructor(e,t,i,n){super(19,"Frame ".concat(i," dropped: ").concat(e),n),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=ad[t],this.frameNumber=i}static interrupted(e,t){return new sd("Interrupted by the start of a new frame ".concat(t),ad.Interrupted,e)}static unknownFrame(e){return new sd("Initial packet was never received.",ad.UnknownFrame,e)}static bufferFull(e){return new sd("Reorder buffer is full.",ad.BufferFull,e)}static incomplete(e,t,i){return new sd("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),ad.Incomplete,e)}}var ad,od;!function(e){e[e.Interrupted=0]="Interrupted",e[e.UnknownFrame=1]="UnknownFrame",e[e.BufferFull=2]="BufferFull",e[e.Incomplete=3]="Incomplete"}(ad||(ad={}));class cd{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case id.Single:return this.frameFromSingle(e,t);case id.Start:return this.beginPartial(e,t);case id.Inter:case id.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==id.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const n=null!==(i=null==t?void 0:t.maxPartialFrames)&&void 0!==i?i:1;if(this.partials.size>=n){const i=this.peekOldestPartialFrameNumber();if("number"!=typeof i)throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(i),null==t?void 0:t.throwOnInterruption)throw sd.interrupted(i,e.header.frameNumber.value);rd.warn("Data track frame ".concat(i," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var i;if(e.header.marker!==id.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const n=e.header.sequence,r=e.header.frameNumber.value,s={startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},a=null!==(i=null==t?void 0:t.maxPartialFrames)&&void 0!==i?i:1;for(;this.partials.size>=a;){const e=this.peekOldestPartialFrameNumber();if("number"!=typeof e)break;if(this.partials.delete(e),null==t?void 0:t.throwOnInterruption)throw sd.interrupted(e,r);rd.warn("Data track partials full (max ".concat(a,"), evicted oldest frame ").concat(e," to make room for new frame ").concat(r,"."))}return this.partials.set(r,s),null}pushToPartial(e){if(e.header.marker!==id.Inter&&e.header.marker!==id.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),sd.unknownFrame(t);if(i.payloads.size>=cd.MAX_BUFFER_PACKETS)throw this.partials.delete(t),sd.bufferFull(t);return i.payloads.has(e.header.sequence.value)&&rd.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),i.payloads.set(e.header.sequence.value,e.payload),e.header.marker===id.Final?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){const n=t.payloads.size;let r=0;for(const e of t.payloads.values())r+=e.length;const s=new Uint8Array(r);let a=t.startSequence.clone(),o=0;for(;;){const n=t.payloads.get(a.value);if(!n)break;t.payloads.delete(a.value);const r=s.length-o;if(n.length>r)throw new Error("Depacketizer.finalize: Expected at least ".concat(n.length," more bytes left in the payload buffer, only got ").concat(r," bytes."));if(s.set(n,o),o+=n.length,a.value==i)return this.partials.delete(e),{payload:s,extensions:t.extensions};a.increment()}throw this.partials.delete(e),sd.incomplete(e,n,i-t.startSequence.value+1)}}cd.MAX_BUFFER_PACKETS=128,function(e){e[e.Unpublished=0]="Unpublished",e[e.Timeout=1]="Timeout",e[e.Disconnected=2]="Disconnected",e[e.Cancelled=4]="Cancelled"}(od||(od={}));class dd extends Gr{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=od[t]}static unpublished(){return new dd("The track has been unpublished and is no longer available",od.Unpublished)}static timeout(){return new dd("Request to subscribe to data track timed-out",od.Timeout)}static disconnected(){return new dd("Cannot subscribe to data track when disconnected",od.Disconnected)}static cancelled(){return new dd("Subscription to data track cancelled by caller",od.Cancelled)}}const ld=yn(fn.DataTracks);class ud{constructor(e){var t,i;const n=null!==e.e2eeManager;if(e.info.usesE2ee!==n)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const r=new cd;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=null!==(t=e.e2eeManager)&&void 0!==t?t:null,this.depacketizer=r,this.options=null!==(i=e.pipelineOptions)&&void 0!==i?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return Cn(this,void 0,void 0,(function*(){const t=this.depacketize(e);if(!t)return null;const i=yield this.decryptIfNeeded(t);return i||null}))}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(e){return ld.warn("Data frame depacketize error: ".concat(e)),null}return t}decryptIfNeeded(e){return Cn(this,void 0,void 0,(function*(){var t,i;const n=this.e2eeManager;if(!n)return e;const r=null!==(i=null===(t=e.extensions)||void 0===t?void 0:t.e2ee)&&void 0!==i?i:null;if(!r)return ld.error("Missing E2EE meta"),null;let s;try{s=yield n.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(e){return ld.error("Error decrypting packet: ".concat(e)),null}return e.payload=s.payload,e}))}}const hd=yn(fn.DataTracks);class pd extends Dn.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.subscription.type&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const i=this.descriptors.get(e);i?(i.pipelineOptions=t,"active"===i.subscription.type&&i.subscription.pipeline.setOptions(t)):hd.warn("Unknown track ".concat(e,", cannot set pipeline options."))}openSubscriptionStream(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16,n=null;const r=new ma,s=()=>{null==t||t.removeEventListener("abort",o)},a=()=>{if(s(),!n)return void hd.warn("ReadableStream subscribed to ".concat(e," was not started."));const t=this.descriptors.get(e);t?"active"===t.subscription.type?(t.subscription.streamControllers.delete(n),0===t.subscription.streamControllers.size&&this.unSubscribeRequest(t.info.sid)):hd.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):hd.warn("Unknown track ".concat(e,", skipping cancel..."))},o=()=>{var t;if(!n)return;const i=this.descriptors.get(e);"active"===(null==i?void 0:i.subscription.type)&&i.subscription.streamControllers.delete(n),n.error(dd.cancelled()),null===(t=r.reject)||void 0===t||t.call(r,dd.cancelled()),a()},c=new ReadableStream({start:i=>{n=i,this.subscribeRequest(e,t).then((()=>Cn(this,void 0,void 0,(function*(){var n,a,c;const d=this.descriptors.get(e);if(!d){hd.error("Unknown track ".concat(e));const t=dd.disconnected();return i.error(t),void(null===(n=r.reject)||void 0===n||n.call(r,t))}if("active"!==d.subscription.type){hd.error("Subscription for track ".concat(e," is not active"));const t=dd.disconnected();return i.error(t),void(null===(a=r.reject)||void 0===a||a.call(r,t))}(null==t?void 0:t.aborted)?o():(null==t||t.addEventListener("abort",o),d.subscription.streamControllers.set(i,s),null===(c=r.resolve)||void 0===c||c.call(r))})))).catch((e=>{var t;i.error(e),null===(t=r.reject)||void 0===t||t.call(r,e)}))},cancel:()=>{a()}},new CountQueuingStrategy({highWaterMark:i}));return[c,r.promise]}subscribeRequest(e,t){return Cn(this,void 0,void 0,(function*(){const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");const n=(t,i,n)=>Cn(this,void 0,void 0,(function*(){if("active"===t.subscription.type)return;if("pending"!==t.subscription.type)throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(t.subscription.type));const r=jc([i,n].filter((e=>void 0!==e))),s=new ma;t.subscription.completionFuture.promise.then((()=>{var e;return null===(e=s.resolve)||void 0===e?void 0:e.call(s)})).catch((e=>{var t;return null===(t=s.reject)||void 0===t?void 0:t.call(s,e)}));const a=()=>{var e;"pending"===t.subscription.type&&(t.subscription.pendingRequestCount-=1,(null==n?void 0:n.aborted)||t.subscription.pendingRequestCount<=0?t.subscription.cancel():null===(e=s.reject)||void 0===e||e.call(s,dd.cancelled()))};r.aborted&&a(),r.addEventListener("abort",a),yield s.promise,r.removeEventListener("abort",a)}));switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new ma,pendingRequestCount:1,cancel:()=>{var t,n;const s=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),"pending"===s.type&&(null===(n=(t=s.completionFuture).reject)||void 0===n||n.call(t,r.aborted?dd.timeout():dd.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=Bc(1e4);return void(yield n(i,t,r))}case"pending":return i.subscription.pendingRequestCount+=1,void(yield n(i,t));case"active":return}}))}querySubscribed(){return Cn(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.subscription.type)).map((e=>[e.info,e.publisherIdentity]))}))}unSubscribeRequest(e){var t;const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");if("active"!==i.subscription.type)return void hd.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat(null===(t=i.subscription)||void 0===t?void 0:t.type));this.closeStreamControllers(i.subscription.streamControllers,e);const n=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const n of e){var i=B(n,2);const e=i[0];(0,i[1])();try{e.close()}catch(e){hd.warn("Failed to close readable stream for track ".concat(t,": ").concat(e))}}}receiveSfuPublicationUpdates(e){return Cn(this,void 0,void 0,(function*(){if(0===e.size)return;const t=new Map;for(const n of e.entries()){var i=B(n,2);const e=i[0],r=i[1],s=new Set;for(const t of r)s.add(t.sid),this.descriptors.has(t.sid)||(yield this.handleTrackPublished(e,t));t.set(e,s)}for(const e of t.entries()){var n=B(e,2);const t=n[0],i=n[1];let r=Array.from(this.descriptors.entries()).filter((e=>{let i=B(e,2);return i[0],i[1].publisherIdentity===t})).map((e=>B(e,1)[0])).filter((e=>!i.has(e)));for(const e of r)this.handleTrackUnpublished(e)}}))}queryPublications(){return Cn(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).map((e=>e.info))}))}handleTrackPublished(e,t){return Cn(this,void 0,void 0,(function*(){if(this.descriptors.has(t.sid))return void hd.error("Existing descriptor for track ".concat(t.sid));let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);const n=new ed(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:n})}))}handleTrackUnpublished(e){const t=this.descriptors.get(e);t?(this.descriptors.delete(e),"active"===t.subscription.type&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})):hd.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(const i of e.entries()){var t=B(i,2);const e=t[0],n=t[1];this.registerSubscriberHandle(e,n)}}registerSubscriberHandle(e,t){var i,n;const r=this.descriptors.get(t);if(r)switch(r.subscription.type){case"none":return void hd.warn("No subscription for ".concat(t));case"active":return r.subscription.subcriptionHandle=e,void this.subscriptionHandles.set(e,t);case"pending":{const s=new ud({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:r.pipelineOptions}),a=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:s,streamControllers:new Map},this.subscriptionHandles.set(e,t),null===(n=(i=a.completionFuture).resolve)||void 0===n||n.call(i)}}else hd.error("Unknown track ".concat(t))}packetReceived(e){return Cn(this,void 0,void 0,(function*(){let t;try{t=B(nd.fromBinary(e),1)[0]}catch(e){return void hd.error("Failed to deserialize packet: ".concat(e))}const i=this.subscriptionHandles.get(t.header.trackHandle);if(!i)return void hd.warn("Unknown subscriber handle ".concat(t.header.trackHandle));const n=this.descriptors.get(i);if(!n)return void hd.error("Missing descriptor for track ".concat(i));if("active"!==n.subscription.type)return void hd.warn("Received packet for track ".concat(i," without active subscription"));const r=yield n.subscription.pipeline.processPacket(t);if(r)for(const e of n.subscription.streamControllers.keys()){if(null!==e.desiredSize&&e.desiredSize<=0){hd.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(e.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const t=$c.lossyIntoFrame(r);e.enqueue(t)}}))}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=B(t,2);const i=e[0];"none"!==e[1].subscription.type&&this.emit("sfuUpdateSubscription",{sid:i,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,i;for(const n of this.descriptors.values())if(n.publisherIdentity===e)switch(n.subscription.type){case"none":break;case"pending":null===(i=(t=n.subscription.completionFuture).reject)||void 0===i||i.call(t,dd.disconnected());break;case"active":this.unSubscribeRequest(n.info.sid)}}reset(){var e,t;for(const i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),"pending"===i.subscription.type&&(null===(t=(e=i.subscription.completionFuture).reject)||void 0===t||t.call(e,dd.disconnected())),"active"===i.subscription.type&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class md extends Gr{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=gd[t]}static mtuTooShort(){return new md("MTU is too short to send frame",gd.MtuTooShort)}}var gd,fd,vd,kd;!function(e){e[e.MtuTooShort=0]="MtuTooShort"}(gd||(gd={}));class yd{constructor(e,t){this.sequence=ao.u16(0),this.frameNumber=ao.u16(0),this.clock=co.rtpStartingNow(oo.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?id.Single:0===e?id.Start:e===t-1?id.Final:id.Inter}*packetize(e,t){var i;const n=this.frameNumber.getThenIncrement(),r={marker:id.Inter,trackHandle:this.handle,sequence:ao.u16(0),frameNumber:n,timestamp:null!==(i=null==t?void 0:t.now)&&void 0!==i?i:this.clock.now(),extensions:e.extensions},s=new td(r).toBinaryLengthBytes();if(s>=this.mtuSizeBytes)throw md.mtuTooShort();const a=this.mtuSizeBytes-s,o=Math.ceil(e.payload.byteLength/a);for(let t=0,i=0;i<e.payload.byteLength;t=(c=[t+1,i+a])[0],i=c[1],c){var c;const n=this.sequence.getThenIncrement(),s=new td(Object.assign(Object.assign({},r),{marker:yd.computeFrameMarker(t,o),sequence:n})),d=Math.min(a,e.payload.byteLength-i),l=new Uint8Array(e.payload.buffer,e.payload.byteOffset+i,d);yield new nd(s,l)}}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.DuplicateName=1]="DuplicateName",e[e.Timeout=2]="Timeout",e[e.LimitReached=3]="LimitReached",e[e.Disconnected=4]="Disconnected",e[e.Cancelled=5]="Cancelled",e[e.InvalidName=6]="InvalidName",e[e.Unknown=7]="Unknown"}(fd||(fd={}));class bd extends Gr{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=fd[t],this.rawMessage=null==i?void 0:i.rawMessage}static notAllowed(e){return new bd("Data track publishing unauthorized",fd.NotAllowed,{rawMessage:e})}static duplicateName(e){return new bd("Track name already taken",fd.DuplicateName,{rawMessage:e})}static invalidName(e){return new bd("Track name is invalid",fd.InvalidName,{rawMessage:e})}static timeout(){return new bd("Publish data track timed-out. Does the LiveKit server support data tracks?",fd.Timeout)}static limitReached(e){return new bd("Data track publication limit reached",fd.LimitReached,{rawMessage:e})}static unknown(e,t){return new bd("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),fd.Unknown)}static disconnected(){return new bd("Room disconnected",fd.Disconnected)}static cancelled(){return new bd("Publish data track cancelled by caller",fd.Cancelled)}}!function(e){e[e.TrackUnpublished=0]="TrackUnpublished",e[e.Dropped=1]="Dropped"}(vd||(vd={}));class Td extends Gr{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=vd[t]}static trackUnpublished(){return new Td("Track is no longer published",vd.TrackUnpublished)}static dropped(e){return new Td("Frame was dropped",vd.Dropped,{cause:e})}}!function(e){e[e.Packetizer=0]="Packetizer",e[e.Encryption=1]="Encryption"}(kd||(kd={}));class Sd extends Gr{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=kd[t]}static packetizer(e){return new Sd("Error packetizing frame",kd.Packetizer,{cause:e})}static encryption(e){return new Sd("Error encrypting frame",kd.Encryption,{cause:e})}}class Cd{constructor(e,t){this.trackSymbol=Xc,this.isLocal=!0,this.typeSymbol=Zc,this.handle=null,this.log=kn,this.flushedFuture=new ma,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;null===(t=(e=this.flushedFuture).resolve)||void 0===t||t.call(e),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,i;this.isFlushed=e.isFlushed,e.isFlushed&&(null===(i=(t=this.flushedFuture).resolve)||void 0===i||i.call(t),this.flushedFuture=new ma)},this.options=e,this.manager=t,this.log=yn(fn.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){const n=new Cd(e,t);return n.handle=i,n}get info(){const e=this.descriptor;return"active"===(null==e?void 0:e.type)?e.info:void 0}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return Cn(this,void 0,void 0,(function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}}))}isPublished(){var e;return"active"===(null===(e=this.descriptor)||void 0===e?void 0:e.type)&&"unpublished"!==this.descriptor.publishState}tryPush(e){if(!this.handle)throw Td.trackUnpublished();const t=$c.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}flush(){return Cn(this,void 0,void 0,(function*(){if(!this.isFlushed)return this.flushedFuture.promise}))}unpublish(){return Cn(this,void 0,void 0,(function*(){if(this.handle)try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}else kn.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'))}))}}class wd{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new yd(e.info.pubHandle,wd.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return Rn(this,arguments,(function*(){const t=yield En(this.encryptIfNeeded(e));try{yield En(yield*function(e){var t,i;return t={},n("next"),n("throw",(function(e){throw e})),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,r){t[n]=e[n]?function(t){return(i=!i)?{value:En(e[n](t)),done:!1}:r?r(t):t}:r}}(Pn(this.packetizer.packetize(t))))}catch(e){if(e instanceof md)throw Sd.packetizer(e);throw e}}))}encryptIfNeeded(e){return Cn(this,void 0,void 0,(function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw Sd.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new Qc(t.keyIndex,t.iv),e}))}}wd.TRANSPORT_MTU_BYTES=16e3;const Ed=yn(fn.DataTracks),Rd={pending:()=>({type:"pending",completionFuture:new ma}),active:(e,t)=>({type:"active",info:e,publishState:"published",pipeline:new wd({info:e,e2eeManager:t}),unpublishingFuture:new ma})};class Pd extends Dn.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new mo,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}static withDescriptors(e){const t=new Pd;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.type&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return null!==(t=this.descriptors.get(e))&&void 0!==t?t:null}tryProcessAndSend(e,t){return Cn(this,void 0,void 0,(function*(){var i,n,r,s,a;const o=this.getDescriptor(e);if("active"!==(null==o?void 0:o.type))throw Td.trackUnpublished();if("unpublished"===o.publishState)throw Td.trackUnpublished();if("republishing"===o.publishState)throw Td.dropped("Data track republishing");try{try{for(var c,d=!0,l=Pn(o.pipeline.processFrame(t));!(i=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const t=s,i=null!==(a=this.inFlightPacketCounter.get(e))&&void 0!==a?a:0;this.inFlightPacketCounter.set(e,i+1),0===i&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:t.toBinary()})}}catch(e){n={error:e}}finally{try{d||i||!(r=l.return)||(yield r.call(l))}finally{if(n)throw n.error}}}catch(e){throw Td.dropped(e)}}))}handlePacketSendComplete(e){var t;let i=(null!==(t=this.inFlightPacketCounter.get(e))&&void 0!==t?t:0)-1;i<0&&(Ed.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),i=0),this.inFlightPacketCounter.set(e,i),0===i&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return Cn(this,void 0,void 0,(function*(){const i=this.handleAllocator.get();if(!i)throw bd.limitReached();const n=Bc(1e4),r=t?jc([t,n]):n;if(this.descriptors.has(i))throw new Error("Descriptor for handle already exists");const s=Rd.pending();this.descriptors.set(i,s);const a=()=>{var e,t;const r=this.descriptors.get(i);r?(this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),"pending"===r.type&&(null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,n.aborted?bd.timeout():bd.cancelled()))):Ed.warn("No descriptor for ".concat(i))};return r.aborted?(a(),s.completionFuture.promise.then((()=>i))):(r.addEventListener("abort",a),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:null!==this.e2eeManager}),yield s.completionFuture.promise,r.removeEventListener("abort",a),this.emit("trackPublished",{track:Cd.withExplicitHandle(e,this,i)}),i)}))}queryPublished(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.type)).map((e=>e.info))}unpublishRequest(e){return Cn(this,void 0,void 0,(function*(){const t=this.descriptors.get(e);t?"active"===t.type?(this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})):Ed.warn("Track ".concat(e," not active")):Ed.warn("No descriptor for ".concat(e))}))}receivedSfuPublishResponse(e,t){var i,n,r,s;const a=this.descriptors.get(e);if(a)switch(this.descriptors.delete(e),a.type){case"pending":if("ok"===t.type){const e=t.data,r=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,Rd.active(e,r)),null===(n=(i=a.completionFuture).resolve)||void 0===n||n.call(i)}else null===(s=(r=a.completionFuture).reject)||void 0===s||s.call(r,t.error);return;case"active":if("republishing"!==a.publishState)return void Ed.warn("Track ".concat(e," already active"));if("error"===t.type)return void Ed.warn("Republish failed for track ".concat(e));Ed.debug("Track ".concat(e," republished")),a.info.sid=t.data.sid,a.publishState="published",this.descriptors.set(a.info.pubHandle,a)}else Ed.warn("No descriptor for ".concat(e))}receivedSfuUnpublishResponse(e){var t,i;const n=this.descriptors.get(e);n?(this.descriptors.delete(e),"active"===n.type?(n.publishState="unpublished",null===(i=(t=n.unpublishingFuture).resolve)||void 0===i||i.call(t)):Ed.warn("Track ".concat(e," not active"))):Ed.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(const n of this.descriptors.entries()){var i=B(n,2);const r=i[0],s=i[1];switch(s.type){case"pending":this.descriptors.delete(r),null===(t=(e=s.completionFuture).reject)||void 0===t||t.call(e,bd.disconnected());break;case"active":s.publishState="republishing",this.emit("sfuPublishRequest",{handle:s.info.pubHandle,name:s.info.name,usesE2ee:s.info.usesE2ee})}}}reset(){return Cn(this,void 0,void 0,(function*(){var e,t,i,n;this.handleAllocator.reset();for(const r of this.descriptors.values())switch(r.type){case"pending":null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,bd.disconnected());break;case"active":null===(n=(i=r.unpublishingFuture).resolve)||void 0===n||n.call(i),yield this.unpublishRequest(r.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")}))}}class Id extends Error{constructor(e,t,i,n){super(t),this.code=e,this.message=Ld(t,Id.MAX_MESSAGE_BYTES),this.data=i?Ld(i,Id.MAX_DATA_BYTES):void 0,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}static fromProto(e){return new Id(e.code,e.message,e.data)}toProto(){return new xt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new Id(Id.ErrorCode[e],Id.ErrorMessage[e],t,i)}}Id.MAX_MESSAGE_BYTES=256,Id.MAX_DATA_BYTES=15360,Id.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},Id.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const Md="lk.rpc_request",Dd="lk.rpc_response";var Ad;!function(e){e.RPC_REQUEST_ID="lk.rpc_request_id",e.RPC_REQUEST_METHOD="lk.rpc_request_method",e.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",e.RPC_REQUEST_VERSION="lk.rpc_request_version"}(Ad||(Ad={}));function _d(e){return(new TextEncoder).encode(e).length}function Ld(e,t){if(_d(e)<=t)return e;let i=0,n=e.length;const r=new TextEncoder;for(;i<n;){const s=Math.floor((i+n+1)/2);r.encode(e.slice(0,s)).length<=t?i=s:n=s-1}return e.slice(0,i)}class Od extends Dn.EventEmitter{constructor(e,t,i,n){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=n}performRpc(e){return Cn(this,arguments,void 0,(function(e){var t=this;let i=e.destinationIdentity,n=e.method,r=e.payload,s=e.responseTimeout,a=void 0===s?15e3:s;return function*(){const e=t.getRemoteParticipantClientProtocol(i);if(_d(r)>15360&&e<1)throw Id.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const s=t.getServerVersion();if(s&&ra(s,"1.8.0")<0)throw Id.builtIn("UNSUPPORTED_SERVER");const o=Math.max(a,8e3),c=crypto.randomUUID(),d=new ma;let l=null;const u=setTimeout((()=>{var e;t.pendingAcks.delete(c),null===(e=d.reject)||void 0===e||e.call(d,Id.builtIn("CONNECTION_TIMEOUT")),t.pendingResponses.delete(c),null!==l&&clearTimeout(l)}),7e3);t.pendingAcks.set(c,{resolve:()=>{clearTimeout(u)},participantIdentity:i}),t.pendingResponses.set(c,{completionFuture:d,participantIdentity:i}),yield t.publishRpcRequest(i,c,n,r,o,e),l=setTimeout((()=>{var e;t.pendingResponses.delete(c),null===(e=d.reject)||void 0===e||e.call(d,Id.builtIn("RESPONSE_TIMEOUT"))}),a);const h=d.promise.finally((()=>{clearTimeout(l),t.pendingAcks.has(c)&&(t.log.warn("RPC response received before ack",c),t.pendingAcks.delete(c),clearTimeout(u))}));return[c,h]}()}))}publishRpcRequest(e,t,i,n,r,s){return Cn(this,void 0,void 0,(function*(){if(s>=1){const s=yield this.outgoingDataStreamManager.streamText({topic:Md,destinationIdentities:[e],attributes:{[Ad.RPC_REQUEST_ID]:t,[Ad.RPC_REQUEST_METHOD]:i,[Ad.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[Ad.RPC_REQUEST_VERSION]:"".concat(2)}});return yield s.write(n),void(yield s.close())}this.emit("sendDataPacket",{packet:new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcRequest",value:new _t({id:t,method:i,payload:n,responseTimeoutMs:r,version:1})}})})}))}handleIncomingDataStream(e,t,i){return Cn(this,void 0,void 0,(function*(){const n=i[Ad.RPC_REQUEST_ID];if(!n)return void this.log.warn("RPC data stream malformed: ".concat(Ad.RPC_REQUEST_ID," not set."));const r=this.pendingResponses.get(n);if(r&&r.participantIdentity!==t)return void this.log.warn("RPC response stream for ".concat(n," arrived from unexpected sender ").concat(t,", expected ").concat(r.participantIdentity,". Ignoring."));let s;try{s=yield e.readAll()}catch(e){return this.log.warn("Error reading RPC response payload: ".concat(e)),void this.handleIncomingRpcResponseFailure(n,Id.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:e}))}this.handleIncomingRpcResponseSuccess(n,s)}))}handleIncomingRpcResponseSuccess(e,t){var i,n;const r=this.pendingResponses.get(e);r?(null===(n=(i=r.completionFuture).resolve)||void 0===n||n.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,n;const r=this.pendingResponses.get(e);r?(null===(n=(i=r.completionFuture).reject)||void 0===n||n.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const t of this.pendingAcks){var i=B(t,2);const n=i[0];i[1].participantIdentity===e&&this.pendingAcks.delete(n)}for(const i of this.pendingResponses){var n=B(i,2);const s=n[0];var r=n[1];const a=r.participantIdentity,o=r.completionFuture;a===e&&(null===(t=o.reject)||void 0===t||t.call(o,Id.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(s))}}}class xd extends Dn.EventEmitter{constructor(e,t,i){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i}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){return Cn(this,void 0,void 0,(function*(){var i;if(this.publishRpcAck(e,t.id),1!==t.version)return void this.publishRpcResponsePacket(e,t.id,null,Id.builtIn("UNSUPPORTED_VERSION"));const n=this.rpcHandlers.get(t.method);if(!n)return void this.publishRpcResponsePacket(e,t.id,null,Id.builtIn("UNSUPPORTED_METHOD"));let r;try{r=yield n({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(n){let r;return n instanceof Id?r=n:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),n),r=Id.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!==(i=null==n?void 0:n.message)&&void 0!==i?i:n),{cause:n})),void this.publishRpcResponsePacket(e,t.id,null,r)}yield this.publishRpcResponse(e,t.id,null!=r?r:"")}))}handleIncomingDataStream(e,t,i){return Cn(this,void 0,void 0,(function*(){const n=i[Ad.RPC_REQUEST_ID],r=i[Ad.RPC_REQUEST_METHOD],s=parseInt(i[Ad.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),a=parseInt(i[Ad.RPC_REQUEST_VERSION],10);if(!n||!r||Number.isNaN(s)||Number.isNaN(a))return this.log.warn("RPC data stream malformed: ".concat(Ad.RPC_REQUEST_ID," / ").concat(Ad.RPC_REQUEST_METHOD," / ").concat(Ad.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(Ad.RPC_REQUEST_VERSION," not set.")),void this.publishRpcResponsePacket(t,n,null,Id.builtIn("APPLICATION_ERROR","RPC data stream malformed"));if(this.publishRpcAck(t,n),2!==a)return void this.publishRpcResponsePacket(t,n,null,Id.builtIn("UNSUPPORTED_VERSION"));let o;try{o=yield e.readAll()}catch(e){return this.log.warn("Error reading RPC request payload: ".concat(e)),void this.publishRpcResponsePacket(t,n,null,Id.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:e}))}const c=this.rpcHandlers.get(r);if(!c)return void this.publishRpcResponsePacket(t,n,null,Id.builtIn("UNSUPPORTED_METHOD"));let d;try{d=yield c({requestId:n,callerIdentity:t,payload:o,responseTimeout:s})}catch(e){let i;return e instanceof Id?i=e:(this.log.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),e),i=Id.builtIn("APPLICATION_ERROR")),void this.publishRpcResponsePacket(t,n,null,i)}yield this.publishRpcResponse(t,n,null!=d?d:"")}))}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcAck",value:new Lt({requestId:t})}})})}publishRpcResponsePacket(e,t,i,n){this.emit("sendDataPacket",{packet:new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcResponse",value:new Ot({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}})})}publishRpcResponse(e,t,i){return Cn(this,void 0,void 0,(function*(){if(this.getRemoteParticipantClientProtocol(e)>=1){const n=yield this.outgoingDataStreamManager.streamText({topic:Dd,destinationIdentities:[e],attributes:{[Ad.RPC_REQUEST_ID]:t}});return yield n.write(i),void(yield n.close())}if(_d(i)>15360)return this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),void this.publishRpcResponsePacket(e,t,null,Id.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));this.publishRpcResponsePacket(e,t,i,null)}))}}class Nd extends Ga{constructor(e,t,i,n,r,s){super(e,t,Us.Kind.Audio,i,s),this.monitorReceiver=()=>Cn(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=za(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Xs()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Xs())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Cn(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Ws(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Ws(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(es.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(es.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 Cn(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 Ud extends Dn.EventEmitter{constructor(e,t,i,n){var r;super(),this.metadataMuted=!1,this.encryption=mt.NONE,this.log=kn,this.handleMuted=()=>{this.emit(es.Muted)},this.handleUnmuted=()=>{this.emit(es.Unmuted)},this.log=yn(null!==(r=null==n?void 0:n.loggerName)&&void 0!==r?r:fn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=Us.Source.Unknown}setTrack(e){this.track&&(this.track.off(es.Muted,this.handleMuted),this.track.off(es.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(es.Muted,this.handleMuted),e.on(es.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),_s(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==mt.NONE}get audioTrack(){if(Ta(this.track))return this.track}get videoTrack(){if(Sa(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Us.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Us.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"}(Ud||(Ud={}));class Fd extends Ud{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(es.Ended)},this.handleCpuConstrained=()=>{this.track&&Sa(this.track)&&this.emit(es.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(es.Ended,this.handleTrackEnded),this.track.off(es.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(es.Ended,this.handleTrackEnded),e.on(es.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 Cn(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Cn(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Cn(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Cn(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(Ta(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(st.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(st.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(st.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(st.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(st.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(st.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function jd(e,t){return Cn(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const n=Ls(e),r=n.audioProcessor,s=n.videoProcessor,a=n.optionsWithoutProcessor;let o=a.audio,c=a.video;if(r&&"object"==typeof a.audio&&(a.audio.processor=r),s&&"object"==typeof a.video&&(a.video.processor=s),e.audio&&"object"==typeof a.audio&&"string"==typeof a.audio.deviceId){const e=a.audio.deviceId;a.audio.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&"object"==typeof a.video&&"string"==typeof a.video.deviceId){const e=a.video.deviceId;a.video.deviceId={exact:e},i=!0,c=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}!0===a.audio?a.audio={deviceId:"default"}:"object"==typeof a.audio&&null!==a.audio&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),!0===a.video?a.video={deviceId:"default"}:"object"!=typeof a.video||a.video.deviceId||(a.video.deviceId="default");const d=Es(Cs(a,Jo,Qo)),l=navigator.mediaDevices.getUserMedia(d);a.audio&&(no.userMediaPromiseMap.set("audioinput",l),l.catch((()=>no.userMediaPromiseMap.delete("audioinput")))),a.video&&(no.userMediaPromiseMap.set("videoinput",l),l.catch((()=>no.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>Cn(this,void 0,void 0,(function*(){let n;const a="audio"===i.kind?d.audio:d.video;"boolean"!=typeof a&&(n=a);const o=i.getSettings().deviceId;(null==n?void 0:n.deviceId)&&ga(n.deviceId)!==o?n.deviceId=o:n||(n={deviceId:o});const c=function(e,t,i){switch(e.kind){case"audio":return new rc(e,t,!1,void 0,i);case"video":return new vc(e,t,!1,i);default:throw new ns("unsupported track type: ".concat(e.kind))}}(i,n,t);return c.kind===Us.Kind.Video?c.source=Us.Source.Camera:c.kind===Us.Kind.Audio&&(c.source=Us.Source.Microphone),c.mediaStream=e,Ta(c)&&r?yield c.setProcessor(r):Sa(c)&&s&&(yield c.setProcessor(s)),c})))))}catch(n){if(!i)throw n;return jd(Object.assign(Object.assign({},e),{audio:o,video:c}),t)}}))}var Bd,Vd;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(Bd||(Bd={}));class qd extends Dn.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===ht.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===ut.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,r,s){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ht.STANDARD;var o;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Bd.Unknown,this.log=kn,this.loggerOptions=s,this.log=yn(null!==(o=null==s?void 0:s.loggerName)&&void 0!==o?o:fn.Participant,(()=>this.logContext)),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const t of this.trackPublications){const i=B(t,2)[1];if(i.source===e)return i}}getTrackPublicationByName(e){for(const t of this.trackPublications){const i=B(t,2)[1];if(i.trackName===e)return i}}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new ma,this.once(Xr.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(Us.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Us.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Us.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===ut.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==ut.ACTIVE&&this.emit(Xr.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(Xr.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(Xr.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)],r={};for(const s of n)e[s]!==t[s]&&(r[s]=null!==(i=t[s])&&void 0!==i?i:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(Xr.AttributesChanged,t)}setPermissions(e){var t,i,n,r,s,a;const o=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||e.recorder!==(null===(s=this.permissions)||void 0===s?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(a=this.permissions)||void 0===a?void 0:a.canSubscribeMetrics);return this.permissions=e,c&&this.emit(Xr.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Xr.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case et.EXCELLENT:return Bd.Excellent;case et.GOOD:return Bd.Good;case et.POOR:return Bd.Poor;case et.LOST:return Bd.Lost;default:return Bd.Unknown}}(e),t!==this._connectionQuality&&this.emit(Xr.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=>Ta(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on(es.Muted,(()=>{this.emit(Xr.TrackMuted,e)})),e.on(es.Unmuted,(()=>{this.emit(Xr.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Us.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Us.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class Kd extends qd{constructor(e,t,i,n,r,s,a,o){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=mt.NONE,this.e2eeStateMutex=new d,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ma)},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,r,s;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(s=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===s||s.call(r,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new ma),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{const t=e.requestId,i=e.reason,n=e.message,r=this.pendingSignalRequests.get(t);switch(r&&(i!==tn.OK&&r.reject(new ds(n,i)),this.pendingSignalRequests.delete(t)),e.request.case){case"publishDataTrack":{let t;switch(e.reason){case tn.NOT_ALLOWED:t=bd.notAllowed(e.message);break;case tn.DUPLICATE_NAME:t=bd.duplicateName(e.message);break;case tn.INVALID_NAME:t=bd.invalidName(e.message);break;case tn.LIMIT_EXCEEDED:t=bd.limitReached(e.message);break;default:t=bd.unknown(e.reason,e.message)}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:"error",error:t});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Vi({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",_s(e))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",_s(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",_s(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.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",_s(t)),this.emit(Xr.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const a=this.videoTrackPublications.get(e.trackSid);if(!a)return void this.log.warn("received subscribed quality update for unknown track",{trackSid:e.trackSid});if(!a.videoTrack)return;const o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Pn(o);!(t=(c=yield l.next()).done);d=!0){r=c.value,d=!1;const e=r;vs(e)&&(this.log.debug("publish ".concat(e," for ").concat(a.videoTrack.sid),_s(a)),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.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",{trackSid:e.trackSid})},this.handleTrackEnded=e=>Cn(this,void 0,void 0,(function*(){if(e.source===Us.Source.ScreenShare||e.source===Us.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",_s(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(wa(e)||Ca(e))try{if($s())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Us.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),_s(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",_s(e)),wa(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",_s(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.roomOutgoingDataStreamManager=r,this.roomOutgoingDataTrackManager=s,this.rpcClientManager=a,this.rpcServerManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==mt.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(Zr.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(Zr.Connected,this.handleReconnected).on(Zr.SignalConnected,this.handleSignalConnected).on(Zr.SignalRestarted,this.handleReconnected).on(Zr.SignalResumed,this.handleReconnected).on(Zr.Restarting,this.handleReconnecting).on(Zr.Resuming,this.handleReconnecting).on(Zr.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Zr.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Zr.Closing,this.handleClosing).on(Zr.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return Cn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Cn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Cn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Cn(this,arguments,void 0,(function(e){var t=this;let i=e.metadata,n=e.name,r=e.attributes;return function*(){return new jr(((e,s)=>Cn(t,void 0,void 0,(function*(){var t,a;try{let o=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(a=null!=n?n:this.name)&&void 0!==a?a:"",r),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{s(e),o=!0},values:{name:n,metadata:i,attributes:r}});performance.now()-d<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!r||Object.entries(r).every((e=>{let t=B(e,2),i=t[0],n=t[1];return this.attributes[i]===n||""===n&&!this.attributes[i]}))))return this.pendingSignalRequests.delete(c),void e();yield Vs(50)}s(new ds("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error?s(e):s(new Error(String(e)))}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(Us.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Us.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Us.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return Cn(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?mt.GCM:mt.NONE,yield Promise.all(this.pendingPublishPromises.values()),0===this.trackPublications.size||Array.from(this.trackPublications.values()).every((t=>t.isEncrypted===e)))return;yield this.republishAllTracks(void 0,!1)}finally{t()}}))}setTrackEnabled(e,t,i,n){return Cn(this,void 0,void 0,(function*(){var r,s;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",{source:e}),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case Us.Source.Camera:t=yield this.createTracks({video:null===(r=i)||void 0===r||r});break;case Us.Source.Microphone:t=yield this.createTracks({audio:null===(s=i)||void 0===s||s});break;case Us.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new ns(e)}}catch(i){throw null==t||t.forEach((e=>{e.stop()})),i instanceof Error&&this.emit(Xr.MediaDevicesError,i,Ms(e)),this.pendingPublishing.delete(e),i}for(const n of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===Us.Source.Microphone&&Ta(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),n.startPreConnectBuffer())}try{const e=[];for(const i of t)this.log.info("publishing track",_s(i)),e.push(this.publishTrack(i,n));a=B(yield Promise.all(e),1)[0]}catch(e){throw null==t||t.forEach((e=>{e.stop()})),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==a?void 0:a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",{source:e})),a&&a.track)if(e===Us.Source.ScreenShare){const e=[this.unpublishTrack(a.track)],t=this.getTrackPublication(Us.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),a=B(yield Promise.all(e),1)[0]}else yield a.mute();return a}))}enableCameraAndMicrophone(){return Cn(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Us.Source.Camera)&&!this.pendingPublishing.has(Us.Source.Microphone)){this.pendingPublishing.add(Us.Source.Camera),this.pendingPublishing.add(Us.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(Us.Source.Camera),this.pendingPublishing.delete(Us.Source.Microphone)}}}))}createTracks(e){return Cn(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=Cs(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 jd(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return e.map((e=>(Ta(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=Us.Source.Microphone,this.emit(Xr.AudioStreamAcquired)),Sa(e)&&(this.cameraError=void 0,e.source=Us.Source.Camera),e)))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}}))}createScreenTracks(e){return Cn(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new is("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=qr();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)&&ra(e.osVersion,"17")>=0}()||(e.resolution=Ss.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=Js()?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 ns("no video track found");const r=new vc(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Us.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(i.getAudioTracks().length>0){this.emit(Xr.AudioStreamAcquired);const e=new rc(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=Us.Source.ScreenShareAudio,s.push(e)}return s}))}publishTrack(e,t){return Cn(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}waitForNextEngineRestart(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;return new Promise(((t,i)=>{const n=()=>{clearTimeout(a),this.engine.off(Zr.Restarted,r),this.engine.off(Zr.Closing,s)},r=()=>{n(),t()},s=()=>{n(),i(new Error("engine closed before restart completed"))},a=setTimeout((()=>{n(),i(new Error("timed out waiting for engine restart"))}),e);this.engine.once(Zr.Restarted,r),this.engine.once(Zr.Closing,s)}))}publishOrRepublishTrack(e,t){return Cn(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return function*(){var s,a,o,c;let d,l;if(wa(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),ba(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)d=e.getConstraints();else{let t;switch(d=e.constraints,e.source){case Us.Source.Microphone:t="audioinput";break;case Us.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(d=Object.assign(Object.assign({},d),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new rc(e,d,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new vc(e,d,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new ns("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&&(l=t)})),l)return i.log.warn("track has already been published, skipping",_s(l)),l;const u=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),h="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,p=null!==(a=u.forceStereo)&&void 0!==a?a:h;p&&(void 0===u.dtx&&i.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",_s(e)),void 0===u.red&&i.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=u.dtx)&&void 0!==o||(u.dtx=!1),null!==(c=u.red)&&void 0!==c||(u.red=!1)),!function(){const e=qr(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&ra(e.osVersion,t)>=0)||"Safari"===e.name&&ra(e.version,t)>=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"),u.simulcast=!1),u.source&&(e.source=u.source);const m=new Promise(((t,n)=>Cn(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==bo.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:_s(e)});let i=!1;const r=setTimeout((()=>{i=!0,e.stop(),n(new cs("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),i)return;const s=yield this.publish(e,u,p);t(s)}else try{const i=yield this.publish(e,u,p);t(i)}catch(e){n(e)}}catch(e){n(e)}}))));i.pendingPublishPromises.set(e,m);try{return yield m}catch(s){if(!r&&s instanceof as)return i.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:s}),i.pendingPublishPromises.delete(e),yield i.waitForNextEngineRestart(),yield i.publishOrRepublishTrack(e,t,n,!0);throw s}finally{i.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new ma),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",_s(e)),!1;const t=this.permissions,i=t.canPublish,n=t.canPublishSources;return!(!i||0!==n.length&&!n.map((e=>function(e){switch(e){case Xe.CAMERA:return Us.Source.Camera;case Xe.MICROPHONE:return Us.Source.Microphone;case Xe.SCREEN_SHARE:return Us.Source.ScreenShare;case Xe.SCREEN_SHARE_AUDIO:return Us.Source.ScreenShareAudio;default:return Us.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",_s(e)),!1)}publish(e,t,i){return Cn(this,void 0,void 0,(function*(){var n,r,s,a,o,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new cs("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>ba(e)&&t.source===e.source))&&e.source!==Us.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),_s(e)),t.stopMicTrackOnMute&&Ta(e)&&(e.stopOnMute=!0),e.source===Us.Source.ScreenShare&&zs()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Js()||zs())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(zs())return!1;if(Js()){const e=qr();if((null==e?void 0:e.version)&&ra(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&ra(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.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=zo),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===Ds(e.mime)))||(t.videoCodec=Ds(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(es.Muted,this.onTrackMuted),e.on(es.Unmuted,this.onTrackUnmuted),e.on(es.Ended,this.handleTrackEnded),e.on(es.UpstreamPaused,this.onTrackUpstreamPaused),e.on(es.UpstreamResumed,this.onTrackUpstreamResumed),e.on(es.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(n=t.dtx)||void 0===n||n),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(st.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(st.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(st.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(st.TF_STEREO),g&&m.push(st.TF_NO_DTX),wa(e)&&e.hasPreConnectBuffer&&m.push(st.TF_PRECONNECT_BUFFER);const v=this.normalizeRequestedFrameMetadataOptions(e,t),k=new si({cid:e.mediaStreamTrack.id,name:t.name,type:Us.kindToProto(e.kind),muted:e.isMuted,source:Us.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(r=t.red)||void 0===r||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m,packetTrailerFeatures:v});let y;if(e.kind===Us.Kind.Video){let i;try{i=yield e.waitForDimensions()}catch(t){const n=null!==(a=null===(s=this.roomOptions.videoCaptureDefaults)||void 0===s?void 0:s.resolution)&&void 0!==a?a:bs.h720.resolution;i={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},_s(e)),{dims:i}))}k.width=i.width,k.height=i.height,Ca(e)&&(Hs(p)&&(e.source===Us.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",_s(e)))),t.scalabilityMode=null!==(o=t.scalabilityMode)&&void 0!==o?o:"L3T3_KEY"),k.simulcastCodecs=[new ri({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:zo}),t.backupCodec&&p!==t.backupCodec.codec&&k.encryption===mt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),k.simulcastCodecs.push(new ri({codec:t.backupCodec.codec,cid:""})))),y=uc(e.source===Us.Source.ScreenShare,k.width,k.height,t),k.layers=bc(k.width,k.height,y,Hs(t.videoCodec))}else e.kind===Us.Kind.Audio&&(y=[{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 ss("cannot publish track when not connected");const b=()=>Cn(this,void 0,void 0,(function*(){var i,n,r;if(!this.engine.pcManager)throw new ss("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),Ca(e)&&(e.publishOptions=t),this.emit(Xr.LocalSenderCreated,e.sender,e),Ca(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===Us.Source.ScreenShare||e.constraints.height&&ga(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),y)if(zs()&&e.kind===Us.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=y[0])||void 0===n?void 0:n.maxBitrate)?y[0].maxBitrate/1e3:0})}else e.codec&&Hs(e.codec)&&(null===(r=y[0])||void 0===r?void 0:r.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:k.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()}));let T;const S=new Promise(((t,i)=>Cn(this,void 0,void 0,(function*(){var n;try{T=yield this.engine.addTrack(k),t(T)}catch(t){if(e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(e){this.log.error(e)}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({},_s(e)),{error:t}))}))}i(t)}}))));if(this.enabledPublishVideoCodecs.length>0&&0===v.length){const e=yield Promise.all([S,b()]);T=e[0]}else{let i;if(T=yield S,T.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===Us.Kind.Video){const n=Ds(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},_s(e)),{codec:n})),t.videoCodec=n,y=uc(e.source===Us.Source.ScreenShare,k.width,k.height,t))}yield b()}const C=new Fd(e.kind,T,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(es.CpuConstrained,(e=>this.onTrackCpuConstrained(e,C))),C.options=t,e.sid=T.sid,Ca(e)&&(e.publishOptions=t,k.width&&k.height&&(e.lastEncodedDimensions={width:k.width,height:k.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:y,trackInfo:T}),Ca(e)?e.startMonitor(this.engine.client):wa(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit(Xr.LocalTrackPublished,C),wa(e)&&T.audioFeatures.includes(st.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();if(this.on(Xr.LocalTrackSubscribed,(t=>{if(t.trackSid===T.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed");this.log.debug("finished recording preconnect buffer",_s(e)),e.stopPreConnectBuffer()}})),t){const n=new Promise(((n,r)=>Cn(this,void 0,void 0,(function*(){var s,a,o,c,d,l;try{this.log.debug("waiting for agent",_s(e));const m=setTimeout((()=>{r(new Error("agent not active within 10 seconds"))}),1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",_s(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=Pn(t);!(s=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){a={error:e}}finally{try{h||s||!(o=p.return)||(yield o.call(p))}finally{if(a)throw a.error}}yield v.close(),n()}catch(e){r(e)}}))));n.then((()=>{this.log.debug("preconnect buffer sent successfully",_s(e))})).catch((t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},_s(e)),{error:t}))}))}}return C}))}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||qa(null!==(e=this.roomOptions.frameMetadata)&&void 0!==e?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var i;const n=null!==(i=t.frameMetadata)&&void 0!==i?i:t.packetTrailer;if(e.kind!==Us.Kind.Video||!Ka(n))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),_s(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const r=function(e){const t=[];return(null==e?void 0:e.timestamp)&&t.push(at.PTF_USER_TIMESTAMP),(null==e?void 0:e.frameId)&&t.push(at.PTF_FRAME_ID),t}(n),s=function(e){if(!e||0===e.length)return;const t={};return e.includes(at.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(at.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}(r);return t.frameMetadata=s,t.packetTrailer=s,r}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Cn(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==mt.NONE)return;let r;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(r=t)})),!r)throw new ns("track is not published");if(!Ca(e))throw new ns("track is not a video track");const s=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),a=hc(e,t,s);if(!a)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",_s(e));const o=e.addSimulcastTrack(t,a);if(!o)return;const c=this.normalizeRequestedFrameMetadataOptions(e,s),d=new si({cid:o.mediaStreamTrack.id,type:Us.kindToProto(e.kind),muted:e.isMuted,source:Us.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:s.videoCodec,cid:o.mediaStreamTrack.id}]});if(d.layers=bc(d.width,d.height,a),!this.engine||this.engine.isClosed)throw new ss("cannot publish track when not connected");const l=(yield Promise.all([this.engine.addTrack(d),(()=>Cn(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,o,s,a),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:a,trackInfo:l})}))}unpublishTrack(e,t){return Cn(this,void 0,void 0,(function*(){var i,n;if(ba(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.debug("awaiting publish promise before attempting to unpublish",_s(e)),yield t)}const r=this.getPublicationForTrack(e),s=r?_s(r):void 0;if(this.log.info("unpublishing track",s),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",s);(e=r.track).off(es.Muted,this.onTrackMuted),e.off(es.Unmuted,this.onTrackUnmuted),e.off(es.Ended,this.handleTrackEnded),e.off(es.UpstreamPaused,this.onTrackUpstreamPaused),e.off(es.UpstreamResumed,this.onTrackUpstreamResumed),e.off(es.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let a=!1;const o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Xo.FAILED&&o)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",a=!0);try{a=this.engine.removeTrack(o)}catch(e){this.log.warn(e),a=!0}if(Ca(e)){for(const t of e.simulcastCodecs){const e=B(t,2)[1];if(e.sender){try{a=this.engine.removeTrack(e.sender)}catch(e){this.log.warn(e),a=!0}e.sender=void 0}}e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},s),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Us.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Us.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(Xr.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r}))}unpublishTracks(e){return Cn(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Cn(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 jr(((n,r)=>Cn(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=>Cn(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===Us.Source.ScreenShare||t.source===Us.Source.ScreenShareAudio||!wa(t)&&!Ca(t)||t.isUserProvided||(this.log.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),n()}catch(e){e instanceof Error?r(e):r(new Error(String(e)))}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Cn(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?Rc.RELIABLE:Rc.LOSSY,r=i.reliable?St.RELIABLE:St.LOSSY,s=i.destinationIdentities,a=i.topic;let o=new Pt({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:a});const c=new Tt({kind:r,value:{case:"user",value:o}});yield t.engine.sendDataPacket(c,n)}()}))}publishDtmf(e,t){return Cn(this,void 0,void 0,(function*(){const i=new Tt({kind:St.RELIABLE,value:{case:"sipDtmf",value:new It({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Rc.RELIABLE)}))}sendChatMessage(e,t){return Cn(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 Tt({value:{case:"chatMessage",value:new At(Object.assign(Object.assign({},i),{timestamp:A.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,Rc.RELIABLE),this.emit(Xr.ChatMessage,i),i}))}editChatMessage(e,t){return Cn(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new Tt({value:{case:"chatMessage",value:new At(Object.assign(Object.assign({},i),{timestamp:A.parse(i.timestamp),editTimestamp:A.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,Rc.RELIABLE),this.emit(Xr.ChatMessage,i),i}))}sendText(e,t){return Cn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)}))}streamText(e){return Cn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(e)}))}sendFile(e,t){return Cn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)}))}streamBytes(e){return Cn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)}))}performRpc(e){return this.rpcClientManager.performRpc(e).then((e=>{let t=B(e,2);return t[0],t[1]}))}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(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()}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 r=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},_s(n)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}})),!0)}setActiveAgent(e){var t,i,n,r;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===(r=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new ma),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(wa(n)||Ca(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return Cn(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>B(t,1)[0].source===e));if(t)return t[1];yield Vs(20)}}))}publishDataTrack(e){return Cn(this,void 0,void 0,(function*(){const t=new Cd(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t}))}}class Hd extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class Wd extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,n;super.set(e,t);const r=null===(i=this.pending)||void 0===i?void 0:i.get(e);if(r){for(const e of r)e.isResolved||null===(n=e.resolve)||void 0===n||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return Cn(this,void 0,void 0,(function*(){const i=this.get(e);if(void 0!==i)return i;if(null==t?void 0:t.aborted)throw new Hd("The operation was aborted.",t.reason);const n=new ma(void 0,(()=>{const t=this.pending.get(e);if(!t)return;const i=t.indexOf(n);-1!==i&&t.splice(i,1),0===t.length&&this.pending.delete(e)})),r=this.pending.get(e);if(r?r.push(n):this.pending.set(e,[n]),t){const e=()=>{var e;n.isResolved||null===(e=n.reject)||void 0===e||e.call(n,new Hd("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0}),n.promise.finally((()=>{t.removeEventListener("abort",e)}))}return n.promise}))}}class zd extends Ud{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(es.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 bi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Nt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(es.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Ud.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ud.SubscriptionStatus.Subscribed:Ud.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ud.PermissionStatus.Allowed:Ud.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||(Pa(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Pa(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:Ns.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(es.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(es.VisibilityChanged,this.handleVisibilityChange),n.off(es.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(es.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(es.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(es.VisibilityChanged,this.handleVisibilityChange),e.on(es.Ended,this.handleEnded),this.emit(es.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(es.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?es.Muted:es.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(es.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(es.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Pa(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ci({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Us.Kind.Video){let t=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(t){Os(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=function(e,t){var i;return null===(i=e.layers)||void 0===i?void 0:i.find((e=>e.quality===t))}(this.trackInfo,this.requestedMaxQuality);e&&Os(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.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:Ns.HIGH})),e.quality=Ns.HIGH)}this.emit(es.UpdateSettings,e)}}class Gd extends qd{static fromParticipantInfo(e,t,i,n){return new Gd(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,t.dataTracks.map((e=>{const i=go.from(e);return new ed(i,n,{publisherIdentity:t.identity})})),t.clientProtocol)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,r,s,a){let o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:ht.STANDARD,c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],d=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0;super(t,i||"",n,r,s,a,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new Wd(c.map((e=>[e.info.name,e]))),this.volumeMap=new Map,this.clientProtocol=d}addTrackPublication(e){super.addTrackPublication(e),e.on(es.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),_s(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)})),e.on(es.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(es.SubscriptionPermissionChanged,(t=>{this.emit(Xr.TrackSubscriptionPermissionChanged,e,t)})),e.on(es.SubscriptionStatusChanged,(t=>{this.emit(Xr.TrackSubscriptionStatusChanged,e,t)})),e.on(es.Subscribed,(t=>{this.emit(Xr.TrackSubscribed,t,e)})),e.on(es.Unsubscribed,(t=>{this.emit(Xr.TrackUnsubscribed,t,e)})),e.on(es.SubscriptionFailed,(t=>{this.emit(Xr.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]:Us.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]:Us.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,r,s){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach((t=>{a||e.kind!==t.kind.toString()||(a=t)})),!a)return 0===s?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(Xr.TrackSubscriptionFailed,t)):(void 0===s&&(s=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,r,s-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),_s(a))),void this.emit(Xr.TrackSubscriptionFailed,t);let o;return o="video"===e.kind?new Ja(e,t,n,r):new Nd(e,t,n,this.audioContext,this.audioOutput),o.source=a.source,o.isMuted=a.isMuted,o.setMediaStream(i),o.start(),a.setTrack(o),this.volumeMap.has(a.source)&&Ea(o)&&Ta(o)&&o.setVolume(this.volumeMap.get(a.source)),a}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,r;let s=this.getTrackPublicationBySid(e.sid);if(s)s.updateInfo(e);else{const t=Us.kindFromProto(e.type);if(!t)return;s=new zd(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName}),s.updateInfo(e),i.set(e.sid,s);const a=Array.from(this.trackPublications.values()).find((e=>e.source===(null==s?void 0:s.source)));a&&s.source!==Us.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:_s(a),newTrack:_s(s)})),this.addTrackPublication(s)}t.set(e.sid,s)})),this.trackPublications.forEach((e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),_s(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(Xr.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const n=i.track;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case Us.Kind.Audio:this.audioTrackPublications.delete(e);break;case Us.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(Xr.TrackUnpublished,i)}setAudioOutput(e){return Cn(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;Ta(i.track)&&Ea(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const i of this.dataTracks.entries()){var t=B(i,2);const n=t[0];e===t[1].info.sid&&this.dataTracks.delete(n)}}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)}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(Vd||(Vd={}));class Jd extends Dn.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,r,s,a,o;if(super(),t=this,this.state=Vd.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new d,this.isVideoPlaybackBlocked=!1,this.log=kn,this.bufferedEvents=[],this.isResuming=!1,this.connect=(e,t,i)=>Cn(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!qs()&&!Ks())throw Xs()?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 r=yield this.disconnectLock.lock();if(this.state===Vd.Connected)return this.log.info("already connected to room ".concat(this.name)),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(Vd.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==Da(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Zs(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Dc(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",{error:e})})));const s=(n,a,o)=>Cn(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==r||r();try{if(yield to.getInstance().getBackOffPromise(e),l.signal.aborted)throw ts.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=o?o:e,t,i,l),this.abortController=void 0,n()}catch(t){if(this.regionUrlProvider&&t instanceof ts&&t.reason!==Jr.Cancelled&&t.reason!==Jr.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof ts&&(401===e.status||e.reason===Jr.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void a(e)}[Jr.InternalError,Jr.ServerUnreachable,Jr.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),to.getInstance().addFailedConnectionAttempt(e)),i&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i)),this.recreateEngine(!0),yield s(n,a,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,va(t)),a(t))}else{let e=it.UNKNOWN_REASON;t instanceof ts&&(e=va(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),a(t)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ma(((e,t)=>{s(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,r,s)=>Cn(this,void 0,void 0,(function*(){var a;const o=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,clientInfoCapabilities:qa(null!==(a=r.frameMetadata)&&void 0!==a?a:r.packetTrailer)||this.e2eeManager?[Vt.CAP_PACKET_TRAILER]:void 0,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},s.signal,!r.singlePeerConnection),c=o.joinResponse,d=o.serverInfo;if(this.serverInfo=d,!d.version)throw new rs("unknown server version");return"0.15.1"===d.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),r.dynacast=!1),c})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",{error:e})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>Cn(this,void 0,void 0,(function*(){var r,s;this.state===Vd.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},$o),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($r.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=n.signal.aborted?ts.cancelled("Signal connection aborted"):ts.serverUnreachable("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof ts&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",{error:e}),t}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),ts.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}$s()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),$s()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Vd.Connected),this.emit($r.Connected),to.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return Cn(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,r;const s=yield e.disconnectLock.lock();try{if(e.state===Vd.Disconnected)return void e.log.debug("already disconnected");if(e.log.info("disconnect from room"),e.state===Vd.Connecting||e.state===Vd.Reconnecting||e.isResuming){const t="Abort connection attempt due to user initiated disconnect";e.log.warn(t),null===(i=e.abortController)||void 0===i||i.abort(t),null===(r=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,ts.cancelled("Client initiated disconnect")),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,it.CLIENT_INITIATED),e.engine=void 0}finally{s()}}()}))},this.onPageLeave=()=>Cn(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()})),this.startAudio=()=>Cn(this,void 0,void 0,(function*(){const e=[],t=qr();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=pa();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.startAudio()))})),document.body.append(i),this.once($r.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=()=>Cn(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.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Vd.Reconnecting)&&this.emit($r.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>Cn(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),{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",{error:e})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:e.serverRegion})}catch(e){return}this.setAndEmitConnectionState(Vd.Connected),this.emit($r.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{var t;for(const i of e){if(i.identity===this.localParticipant.identity){this.localParticipant.updateInfo(i);continue}""===i.identity&&(i.identity=null!==(t=this.sidToIdentity.get(i.sid))&&void 0!==t?t:"");let e=this.remoteParticipants.get(i.identity);i.state===ut.DISCONNECTED?this.handleParticipantDisconnected(i.identity,e):this.getOrCreateParticipant(i.identity,i)}const i=new Map(e.filter((e=>e.identity!==this.localParticipant.identity)).map((e=>[e.identity,e.dataTracks.map((e=>go.from(e)))])));this.incomingDataTrackManager.receiveSfuPublicationUpdates(i)},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($r.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($r.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=Us.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(Xr.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected($r.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,t)=>{const i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.rpcServerManager.handleIncomingRpcRequest(e.participantIdentity,t)}else if("rpcResponse"===e.value.case){const t=e.value.value;switch(t.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(t.requestId,t.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(t.requestId,Id.fromProto(t.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(t.value.case),this.logContext)}}else"rpcAck"===e.value.case&&this.rpcClientManager.handleIncomingRpcAck(e.value.value.requestId)},this.handleUserPacket=(e,t,i,n)=>{this.emit($r.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(Xr.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit($r.SipDTMFReceived,t,e),null==e||e.emit(Xr.SipDTMFReceived,t)},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),r=function(e,t){return e.segments.map((e=>{let i=e.id,n=e.text,r=e.language,s=e.startTime,a=e.endTime,o=e.final;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return o?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(a.toString()),final:o,language:r,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit(es.TranscriptionReceived,r),null==i||i.emit(Xr.TranscriptionReceived,r,n),this.emit($r.TranscriptionReceived,r,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const t=e.id,i=e.timestamp,n=e.message,r=e.editTimestamp;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}(t);this.emit($r.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit($r.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit($r.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",{error:e}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit($r.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit($r.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit($r.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Cn(this,void 0,void 0,(function*(){var e;"iOS"!==(null===(e=qr())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit($r.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected($r.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected($r.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.getRemoteParticipantClientProtocol=e=>{var t,i;return null!==(i=null===(t=this.remoteParticipants.get(e))||void 0===t?void 0:t.clientProtocol)&&void 0!==i?i:0},this.onLocalParticipantMetadataChanged=e=>{this.emit($r.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit($r.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit($r.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit($r.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit($r.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=>Cn(this,void 0,void 0,(function*(){var t,i,n,r,s,a;if(null===(t=e.track)||void 0===t||t.on(es.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(es.Restarted,this.onLocalTrackRestarted),null===(s=null===(r=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===r?void 0:r.onPublish)||void 0===s||s.call(r,this),this.emit($r.LocalTrackPublished,e,this.localParticipant),wa(e.track)){(yield e.track.checkForSilence())&&this.emit($r.LocalAudioSilenceDetected,e)}const o=yield null===(a=e.track)||void 0===a?void 0:a.getDeviceId(!1),c=Ms(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit($r.ActiveDeviceChanged,c,o))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(es.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(es.Restarted,this.onLocalTrackRestarted),this.emit($r.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>Cn(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=Ms(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active")),this.localParticipant.activeDeviceMap.set(i,t),this.emit($r.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit($r.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit($r.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit($r.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit($r.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Yo),e),this.log=yn(null!==(i=this.options.loggerName)&&void 0!==i?i:fn.Room,(()=>this.logContext)),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Jo),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Qo),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Go),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Oc,this.outgoingDataStreamManager=new Fc(this.engine,this.log),this.incomingDataTrackManager=new pd({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",(e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)})).on("trackPublished",(e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit($r.DataTrackPublished,e.track),null===(t=this.remoteParticipants.get(e.track.publisherIdentity))||void 0===t||t.addRemoteDataTrack(e.track))})).on("trackUnpublished",(e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit($r.DataTrackUnpublished,e.sid),null===(t=this.remoteParticipants.get(e.publisherIdentity))||void 0===t||t.removeRemoteDataTrack(e.sid))})),this.outgoingDataTrackManager=new Pd({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",(e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)})).on("sfuUnpublishRequest",(e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)})).on("trackPublished",(e=>{this.emit($r.LocalDataTrackPublished,e.track)})).on("trackUnpublished",(e=>{this.emit($r.LocalDataTrackUnpublished,e.sid)})).on("packetAvailable",(e=>{let t=e.handle,i=e.bytes;this.engine.sendLossyBytes(i,Rc.DATA_TRACK_LOSSY,"wait").finally((()=>this.outgoingDataTrackManager.handlePacketSendComplete(t)))})),this.registerRpcDataStreamHandler(),this.rpcClientManager=new Od(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,(()=>{var e,t;return null===(t=null===(e=this.engine.latestJoinResponse)||void 0===e?void 0:e.serverInfo)||void 0===t?void 0:t.version})),this.rpcClientManager.on("sendDataPacket",(e=>{let t=e.packet;var i;null===(i=this.engine)||void 0===i||i.sendDataPacket(t,Rc.RELIABLE)})),this.rpcServerManager=new xd(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",(e=>{let t=e.packet;var i;null===(i=this.engine)||void 0===i||i.sendDataPacket(t,Rc.RELIABLE)})),this.disconnectLock=new d,this.localParticipant=new Kd("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(null!==(n=this.e2eeManager)&&void 0!==n?n:null),this.outgoingDataTrackManager.updateE2eeManager(null!==(r=this.e2eeManager)&&void 0!==r?r:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",ga(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",ga(this.options.audioCaptureDefaults.deviceId)),(null===(s=this.options.audioOutput)||void 0===s?void 0:s.deviceId)&&this.switchActiveDevice("audiooutput",ga(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),$s()){const e=new AbortController;let t;if(Jd.cleanupRegistry){const i=new WeakRef(this);t=()=>{const e=i.deref();e&&e.handleDeviceChange()},Jd.cleanupRegistry.register(this,(()=>{e.abort()}))}else t=this.handleDeviceChange;null===(o=null===(a=navigator.mediaDevices)||void 0===a?void 0:a.addEventListener)||void 0===o||o.call(a,"devicechange",t,{signal:e.signal})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return Cn(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity))}finally{t()}}))}setupE2EE(){var e,t;const i=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new Xa(n,i),this.e2eeManager.on(Na.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit($r.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(Na.EncryptionError,((e,t)=>{const i=t?this.getParticipantByIdentity(t):void 0;this.emit($r.EncryptionError,e,i)})),null===(e=this.e2eeManager)||void 0===e||e.setup(this),null===(t=this.e2eeManager)||void 0===t||t.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=null!==(e=this.options.frameMetadata)&&void 0!==e?e:this.options.packetTrailer;this.frameMetadataManager=new eo(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,i;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:null===(t=this.localParticipant)||void 0===t?void 0:t.identity,participantID:null===(i=this.localParticipant)||void 0===i?void 0:i.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 this.state===Vd.Disconnected?jr.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?jr.resolve(this.roomInfo.sid):new jr(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(Zr.RoomUpdate,i),e(t.sid))};this.engine.on(Zr.RoomUpdate,i),this.once($r.Disconnected,(()=>{this.engine.off(Zr.RoomUpdate,i),t(new ss("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.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new Pc(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Zr.ParticipantUpdate,this.handleParticipantUpdates).on(Zr.RoomUpdate,this.handleRoomUpdate).on(Zr.SpeakersChanged,this.handleSpeakersChanged).on(Zr.StreamStateChanged,this.handleStreamStateUpdate).on(Zr.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Zr.SubscriptionError,this.handleSubscriptionError).on(Zr.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Zr.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Zr.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(Zr.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Zr.DataPacketReceived,this.handleDataPacket).on(Zr.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(Vd.SignalReconnecting)&&this.emit($r.SignalReconnecting)})).on(Zr.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Vd.Connected)&&this.emit($r.Reconnected)})).on(Zr.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Vd.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Zr.Restarting,this.handleRestarting).on(Zr.Restarted,this.handleRestarted).on(Zr.SignalRestarted,this.handleSignalRestarted).on(Zr.Offline,(()=>{this.setAndEmitConnectionState(Vd.Reconnecting)&&this.emit($r.Reconnecting)})).on(Zr.DCBufferStatusChanged,((e,t)=>{this.emit($r.DCBufferStatusChanged,e,t)})).on(Zr.LocalTrackSubscribed,(e=>{this.handleLocalTrackSubscribed(e)})).on(Zr.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($r.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)})).on(Zr.PublishDataTrackResponse,(e=>{e.info?this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==mt.NONE}}):this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(Zr.UnPublishDataTrackResponse,(e=>{e.info?this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle):this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(Zr.DataTrackSubscriberHandles,(e=>{const t=new Map(Object.entries(e.subHandles).map((e=>{let t=B(e,2),i=t[0],n=t[1];return[parseInt(i,10),n.trackSid]})));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)})).on(Zr.DataTrackPacketReceived,(e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}})).on(Zr.Joined,(e=>{const t=new Map(e.otherParticipants.map((e=>[e.identity,e.dataTracks.map((e=>go.from(e)))])));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)})).on(Zr.TokenRefreshed,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)})).on(Zr.ServerRegionsReported,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Mc})})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>Cn(this,void 0,void 0,(function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null})),resetAttempts:()=>{var e;return null===(e=this.regionUrlProvider)||void 0===e?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return no.getInstance().getDevices(e,t)}prepareConnection(e,t){return Cn(this,void 0,void 0,(function*(){if(this.state===Vd.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(Zs(new URL(e))&&t){this.regionUrlProvider=new Dc(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Vd.Disconnected&&(this.regionUrl=i,yield fetch(fa(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(fa(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",{error:e})}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Cn(this,void 0,void 0,(function*(){let i,n=()=>Cn(this,void 0,void 0,(function*(){}));switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":i=new Ji({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Ji({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Ji({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Ji({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=()=>Cn(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ji({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Cn(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ji({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 Ji({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Cn(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Ri({reason:it.CLIENT_INITIATED,action:Pi.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Ji({scenario:{case:"subscriberBandwidth",value:ya(t)}});break;case"leave-full-reconnect":i=new Ji({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 Cn(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var r,s,a,o,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!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===Us.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 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("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Us.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 r=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&&r&&(h=!0)}else if("audiooutput"===e){if(h=!0,!Ws()&&!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!==(a=yield no.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==a?a:""),null!==(o=(l=i.options).audioOutput)&&void 0!==o||(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($r.ActiveDeviceChanged,e,t)),u}()}))}setupLocalParticipantEvents(){this.localParticipant.on(Xr.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Xr.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Xr.AttributesChanged,this.onLocalAttributesChanged).on(Xr.TrackMuted,this.onLocalTrackMuted).on(Xr.TrackUnmuted,this.onLocalTrackUnmuted).on(Xr.LocalTrackPublished,this.onLocalTrackPublished).on(Xr.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Xr.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Xr.MediaDevicesError,this.onMediaDevicesError).on(Xr.AudioStreamAcquired,this.startAudio).on(Xr.ChatMessage,this.onLocalChatMessageSent).on(Xr.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally((()=>t.close())):null==t||t.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===Vd.Connecting||this.state===Vd.Reconnecting){const n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map((e=>e.id))}),this.onTrackAdded(e,t,i),r()},r=()=>{this.off($r.Reconnected,n),this.off($r.Connected,n),this.off($r.Disconnected,r)};return this.once($r.Reconnected,n),this.once($r.Connected,n),void this.once($r.Disconnected,r)}if(this.state===Vd.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected");if("ended"===e.readyState)return void this.log.debug("skipping incoming track as it already ended");const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),r=n[0];let s=n[1],a=e.id;if(s&&s.startsWith("TR")&&(a=s),r===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant");const o=Array.from(this.remoteParticipants.values()).find((e=>e.sid===r));if(!o)return void(r.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r)));if(!a.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r));a=e}let c;a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(s,", trackId: ").concat(a),{remoteParticipantID:r,streamId:s,trackId:a}),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=o.addSubscribedMediaTrack(e,a,t,i,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit($r.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(o.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){const t=()=>this.localParticipant.getTrackPublications().find((t=>t.trackSid===e)),i=t();if(i)return void this.emitLocalTrackSubscribed(i);this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});let n;const r=t=>{t.trackSid===e&&(s(),this.emitLocalTrackSubscribed(t))},s=()=>{clearTimeout(n),this.localParticipant.off(Xr.LocalTrackPublished,r),this.off($r.Disconnected,s)};this.localParticipant.on(Xr.LocalTrackPublished,r),this.once($r.Disconnected,s),n=setTimeout((()=>{s();const i=t();i?this.emitLocalTrackSubscribed(i):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})}),1e4)}emitLocalTrackSubscribed(e){this.localParticipant.emit(Xr.LocalTrackSubscribed,e),this.emitWhenConnected($r.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i,n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==Vd.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,r;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===(r=t.track)||void 0===r||r.stopMonitor()})),this.localParticipant.off(Xr.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Xr.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Xr.AttributesChanged,this.onLocalAttributesChanged).off(Xr.TrackMuted,this.onLocalTrackMuted).off(Xr.TrackUnmuted,this.onLocalTrackUnmuted).off(Xr.LocalTrackPublished,this.onLocalTrackPublished).off(Xr.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Xr.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Xr.MediaDevicesError,this.onMediaDevicesError).off(Xr.AudioStreamAcquired,this.startAudio).off(Xr.ChatMessage,this.onLocalChatMessageSent).off(Xr.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),$s()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=null===(i=navigator.mediaDevices)||void 0===i?void 0:i.removeEventListener)||void 0===n||n.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Vd.Disconnected),this.emit($r.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit($r.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return Cn(this,void 0,void 0,(function*(){var e,t,i;const n=no.getInstance().previousDevices,r=yield no.getInstance().getDevices(void 0,!1),s=qr();if("Chrome"===(null==s?void 0:s.name)&&"iOS"!==s.os)for(let e of r){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($r.ActiveDeviceChanged,e.kind,e.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let s of a){const a=Is(s),o=this.localParticipant.getTrackPublication(a);if(o&&(null===(e=o.track)||void 0===e?void 0:e.isUserProvided))continue;const c=r.filter((e=>e.kind===s)),d=this.getActiveDevice(s);d===(null===(t=n.filter((e=>e.kind===s))[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(s,c[0].deviceId):"audioinput"===s&&!Qs()||"videoinput"===s||!(c.length>0)||c.find((e=>e.deviceId===this.getActiveDevice(s)))||"audiooutput"===s&&Qs()||(yield this.switchActiveDevice(s,c[0].deviceId))}}))}acquireAudioContext(){return Cn(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=Ps())&&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(),Vs(200)])}catch(e){this.log.warn("Could not resume audio context",{error:e})}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit($r.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?Gd.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new Gd(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)))),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($r.ParticipantConnected,i),i.on(Xr.TrackPublished,(e=>{this.emitWhenConnected($r.TrackPublished,e,i)})).on(Xr.TrackSubscribed,((e,t)=>{e.kind===Us.Kind.Audio?(e.on(es.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(es.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===Us.Kind.Video&&(e.on(es.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(es.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected($r.TrackSubscribed,e,t,i)})).on(Xr.TrackUnpublished,(e=>{this.emit($r.TrackUnpublished,e,i)})).on(Xr.TrackUnsubscribed,((e,t)=>{this.emit($r.TrackUnsubscribed,e,t,i)})).on(Xr.TrackMuted,(e=>{this.emitWhenConnected($r.TrackMuted,e,i)})).on(Xr.TrackUnmuted,(e=>{this.emitWhenConnected($r.TrackUnmuted,e,i)})).on(Xr.ParticipantMetadataChanged,(e=>{this.emitWhenConnected($r.ParticipantMetadataChanged,e,i)})).on(Xr.ParticipantNameChanged,(e=>{this.emitWhenConnected($r.ParticipantNameChanged,e,i)})).on(Xr.AttributesChanged,(e=>{this.emitWhenConnected($r.ParticipantAttributesChanged,e,i)})).on(Xr.ConnectionQualityChanged,(e=>{this.emitWhenConnected($r.ConnectionQualityChanged,e,i)})).on(Xr.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected($r.ParticipantPermissionsChanged,e,i)})).on(Xr.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected($r.TrackSubscriptionStatusChanged,e,t,i)})).on(Xr.TrackSubscriptionFailed,((e,t)=>{this.emit($r.TrackSubscriptionFailed,e,i,t)})).on(Xr.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected($r.TrackSubscriptionPermissionChanged,e,t,i)})).on(Xr.Active,(()=>{this.emitWhenConnected($r.ParticipantActive,i),i.kind===ht.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(),i=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ra(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(Md,((e,t)=>Cn(this,[e,t],void 0,(function(e,t){var i=this;let n=t.identity;return function*(){var t;const r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield i.rpcServerManager.handleIncomingDataStream(e,n,r)}()})))),this.incomingDataStreamManager.registerTextStreamHandler(Dd,((e,t)=>Cn(this,[e,t],void 0,(function(e,t){var i=this;let n=t.identity;return function*(){var t;const r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield i.rpcClientManager.handleIncomingDataStream(e,n,r)}()}))))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=hs.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,it.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&hs.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===Vd.Connected),this.emit($r.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let t=B(e,2),i=t[0],n=t[1];this.emit(i,...n)})),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===Vd.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Vd.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return Cn(this,void 0,void 0,(function*(){var t,i,n,r;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ot({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:A.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new lt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit($r.SignalConnected),this.emit($r.Connected),this.setAndEmitConnectionState(Vd.Connected),s.video){const e=new Fd(Us.Kind.Video,new ft({source:Xe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:$e.AUDIO,name:"video-dummy"}),new vc(s.useRealTracks&&(null===(t=window.navigator.mediaDevices)||void 0===t?void 0:t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:ua(160*(null!==(i=a.aspectRatios[0])&&void 0!==i?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(Xr.LocalTrackPublished,e)}if(s.audio){const e=new Fd(Us.Kind.Audio,new ft({source:Xe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:$e.AUDIO}),new rc(s.useRealTracks&&(null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:pa(),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(Xr.LocalTrackPublished,e)}for(let e=0;e<a.count-1;e+=1){let t=new lt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:ut.ACTIVE,tracks:[],joinedAt:A.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(a.video){const n=ua(160*(null!==(r=a.aspectRatios[e%a.aspectRatios.length])&&void 0!==r?r:1),160,!1,!0),s=new ft({source:Xe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:$e.AUDIO});i.addSubscribedMediaTrack(n,s.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,s]}if(a.audio){const e=pa(),n=new ft({source:Xe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:$e.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==$r.ActiveSpeakersChanged&&e!==$r.TranscriptionReceived){const t=Qd(i).filter((e=>void 0!==e));e!==$r.TrackSubscribed&&e!==$r.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(e),{event:e,args:t}),this.log.debug("room event ".concat(e),{event:e,args:t})}return super.emit(e,...i)}}function Qd(e){return e.map((e=>{if(e)return Array.isArray(e)?Qd(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}var Yd;Jd.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef&&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"}(Yd||(Yd={}));Dn.EventEmitter;Dn.EventEmitter;new TextEncoder,new TextDecoder;class $d extends Error{constructor(e,t){var i;super(e,t),j(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}j($d,"code","ERR_JOSE_GENERIC");j(class extends $d{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),j(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");j(class extends $d{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),j(this,"code","ERR_JWT_EXPIRED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_EXPIRED");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),j(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),j(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),j(this,Symbol.asyncIterator,void 0),j(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),j(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),j(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const Xd=(e,t)=>"error"===e||t,Zd=(e,t)=>{const i=(new Date).toISOString(),n=t?.source?`[${t.source}]`:"";return`${i} ${t?.level?`[${t.level.toUpperCase()}]`:""} ${n}`},el=e=>({log:(t,i)=>{if(!Xd(i?.level||"debug",e))return;const n=Zd(0,{...i,level:"debug"});console.log(n,t,i?.error||"")},info:(t,i)=>{if(!Xd(i?.level||"info",e))return;const n=Zd(0,{...i,level:"info"});console.info(n,t,i?.error||"")},warn:(t,i)=>{if(!Xd(i?.level||"warn",e))return;const n=Zd(0,{...i,level:"warn"});console.warn(n,t,i?.error||"")},error:(t,i)=>{if(!Xd(i?.level||"error",e))return;const n=Zd(0,{...i,level:"error"});console.error(n,t,i?.error||"")}});var tl,il,nl,rl,sl,al,ol,cl,dl,ll,ul,hl,pl,ml,gl,fl,vl,kl,yl,bl,Tl,Sl;const Cl=.02,wl=.001;class El extends n.EventEmitter{constructor(t=!1){super(),tl.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",this.logger=el(t),this.logger.log("Initializing LiveKitAnalytics",{source:"LiveKitAnalytics"}),e(this,tl,"m",il).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((()=>{e(this,tl,"m",nl).call(this)}),5e3)}stopAnalyticsCollection(){this.analyticsInterval&&(clearInterval(this.analyticsInterval),this.analyticsInterval=null)}handleConnectionQualityChanged(t,i){const n=e(this,tl,"m",rl).call(this,t);this.connectionMetrics.quality=n,this.callStats.connectionQuality=n,e(this,tl,"m",sl).call(this),e(this,tl,"m",Tl).call(this,n);const r={quality:t,participant:i.identity||"unknown",metrics:{quality:n}};this.emit("connectionQualityChanged",r)}handleAudioPlaybackChanged(t){this.emit("audioPlaybackChanged",t),e(this,tl,"m",cl).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:Cl,minSpeakingDuration:100,dropoutThreshold:wl,dropoutDetectionDuration:500}}getCallAnalytics(e,t,i,n){const r=this.getPerformanceMetrics(),s=this.getAudioLevels();return{connectionStats:this.getConnectionStats(),audioMetrics:{...s,isPaused:n,volume:i},performanceMetrics:r,participants:e,trackStats:t,callStats:this.callStats,metadata:{callStartTime:this.callStartTime,isConnected:this.isConnected,isPaused:n,volume:i},callDuration:r.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(),e(this,tl,"m",il).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 Rl,Pl,Il,Ml,Dl,Al,_l,Ll,Ol,xl,Nl,Ul,Fl,jl,Bl,Vl,ql,Kl,Hl,Wl,zl,Gl,Jl,Ql,Yl;tl=new WeakSet,il=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}},nl=function(){if(this.room&&this.isConnected)try{if(e(this,tl,"m",sl).call(this),this.room?.localParticipant){const t=this.room.localParticipant.connectionQuality;if(t){const i=e(this,tl,"m",rl).call(this,t);this.connectionMetrics.quality=i,this.callStats.connectionQuality=i}}e(this,tl,"m",cl).call(this),e(this,tl,"m",ul).call(this),e(this,tl,"m",Sl).call(this);const t=this.getPerformanceMetrics();this.emit("analyticsUpdated",{connectionStats:this.getConnectionStats(),audioMetrics:this.getAudioLevels(),performanceMetrics:t,callDuration:t.callDuration})}catch(e){}},rl=function(e){switch(e){case Bd.Excellent:return"excellent";case Bd.Good:return"good";case Bd.Poor:return"poor";default:return"lost"}},sl=function(){e(this,tl,"m",al).call(this)},al=function(){const t=this.room?.localParticipant?.connectionQuality;if(!t)return;const i=e(this,tl,"m",ol).call(this,t);0===this.connectionMetrics.latency&&(this.connectionMetrics.latency=i.latency,this.connectionMetrics.packetLoss=i.packetLoss,this.connectionMetrics.bandwidth=i.bandwidth)},ol=function(e){switch(e){case Bd.Excellent:return{latency:10,packetLoss:0,bandwidth:1e6};case Bd.Good:return{latency:50,packetLoss:.1,bandwidth:5e5};case Bd.Poor:return{latency:200,packetLoss:1,bandwidth:1e5};default:return{latency:1e3,packetLoss:10,bandwidth:0}}},cl=function(){if(!this.room)return;const t=Date.now(),i=this.room.activeSpeakers;let n=0,r=0;for(const s of i)s===this.room.localParticipant?n=e(this,tl,"m",dl).call(this,s,t):r=Math.max(r,e(this,tl,"m",ll).call(this,s,t));this.audioMetrics.userAudioLevel=n,this.audioMetrics.agentAudioLevel=r},dl=function(t,i){const n=t.audioLevel||0,r=t.isSpeaking;return r&&!this.lastUserSpeakStart?(this.lastUserSpeakStart=i,this.lastUserInputTime=i):!r&&this.lastUserSpeakStart&&(this.audioMetrics.userSpeakingTime+=i-this.lastUserSpeakStart,this.lastUserSpeakStart=null),e(this,tl,"m",pl).call(this,"user",n,i),e(this,tl,"m",vl).call(this,"user",n,i),n},ll=function(t,i){const n=t.audioLevel||0,r=t.isSpeaking;if(r&&!this.lastAgentSpeakStart){if(this.lastAgentSpeakStart=i,this.lastUserInputTime){const e=i-this.lastUserInputTime;this.performanceMetrics.responseTime=e,this.lastUserInputTime=null}}else!r&&this.lastAgentSpeakStart&&(this.audioMetrics.agentSpeakingTime+=i-this.lastAgentSpeakStart,this.lastAgentSpeakStart=null);return e(this,tl,"m",pl).call(this,"agent",n,i),e(this,tl,"m",vl).call(this,"agent",n,i),n},ul=function(){this.room&&(this.callStats.participantCount=1+this.room.remoteParticipants.size,this.callStats.trackCount=e(this,tl,"m",hl).call(this))},hl=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},pl=function(t,i,n){"user"===t?e(this,tl,"m",ml).call(this,i,n):e(this,tl,"m",gl).call(this,i,n)},ml=function(t,i){const n=t>Cl;n&&!this.vadUserSpeakStart?this.vadUserSpeakStart=i:!n&&this.vadUserSpeakStart&&e(this,tl,"m",fl).call(this,"user",t,i)},gl=function(t,i){const n=t>Cl;n&&!this.vadAgentSpeakStart?this.vadAgentSpeakStart=i:!n&&this.vadAgentSpeakStart&&e(this,tl,"m",fl).call(this,"agent",t,i)},fl=function(e,t,i){const n="user"===e?this.vadUserSpeakStart:this.vadAgentSpeakStart;if(!n)return;const r=i-n;r>=100&&this.emit("voiceActivityDetected",{participant:e,duration:r,audioLevel:t,timestamp:i}),"user"===e?this.vadUserSpeakStart=null:this.vadAgentSpeakStart=null},vl=function(t,i,n){"user"===t?e(this,tl,"m",kl).call(this,i,n):e(this,tl,"m",yl).call(this,i,n)},kl=function(t,i){this.lastUserAudioLevel>Cl&&t<wl?this.userDropoutStartTime||(this.userDropoutStartTime=i):t>=wl&&this.userDropoutStartTime&&e(this,tl,"m",bl).call(this,"user",i),this.lastUserAudioLevel=t},yl=function(t,i){this.lastAgentAudioLevel>Cl&&t<wl?this.agentDropoutStartTime||(this.agentDropoutStartTime=i):t>=wl&&this.agentDropoutStartTime&&e(this,tl,"m",bl).call(this,"agent",i),this.lastAgentAudioLevel=t},bl=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},Tl=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()})}},Sl=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 $l extends n.EventEmitter{constructor(e=!1){super(),Rl.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.sourceNodes=new Map,this.clonedTracks=new Map,this.trackCaptureMap=new Map,this.workletReady=null,this.logger=el(e)}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||e(this,Rl,"m",Fl).call(this),!this.inputAnalyser)return 0;const t=this.inputAnalyser.frequencyBinCount,i=new Uint8Array(t);if(this.inputAnalyser.getByteFrequencyData(i),0===i.length)return 0;let n=0;for(const e of i)n+=e;const r=n/(255*i.length);return Math.max(0,Math.min(1,r))}catch{return 0}}setMicMuted(t){try{if(this.room?.localParticipant){const i=!t,n=this.room.localParticipant.setMicrophoneEnabled(i);return n&&"function"==typeof n.then?void n.then((()=>{e(this,Rl,"m",Pl).call(this,t?"micMuted":"micUnmuted",t)})).catch((i=>{e(this,Rl,"m",Il).call(this,t,i)})):void e(this,Rl,"m",Pl).call(this,t?"micMuted":"micUnmuted",t)}e(this,Rl,"m",Pl).call(this,t?"micMuted":"micUnmuted",t)}catch(i){e(this,Rl,"m",Il).call(this,t,i)}}isMicMuted(){try{let e;const t=this.room?.localParticipant?.getTrackPublication;if(t)try{e=t(Us.Source.Microphone)}catch{e=t("microphone")}if(e&&"boolean"==typeof e.isMuted)return e.isMuted}catch{}return!1}getInputByteFrequencyData(){try{if(this.inputAnalyser||e(this,Rl,"m",Fl).call(this),!this.inputAnalyser)return new Uint8Array(0);const t=this.inputAnalyser.frequencyBinCount,i=new Uint8Array(t);return this.inputAnalyser.getByteFrequencyData(i),i}catch{return new Uint8Array(0)}}getOutputByteFrequencyData(){try{if(this.outputAnalyser||e(this,Rl,"m",jl).call(this),!this.outputAnalyser)return new Uint8Array(0);const t=this.outputAnalyser.frequencyBinCount,i=new Uint8Array(t);return this.outputAnalyser.getByteFrequencyData(i),i}catch{return new Uint8Array(0)}}handleTrackSubscribed(t,i,n){t.kind===Us.Kind.Audio&&(e(this,Rl,"m",Ml).call(this,t,i,n),e(this,Rl,"m",Dl).call(this,t,i,n),e(this,Rl,"m",Ll).call(this,t,n))}handleLocalTrackPublished(t,i,n){t.kind===Us.Kind.Audio&&(e(this,Rl,"m",Ml).call(this,t,i,n),e(this,Rl,"m",Ll).call(this,t,n))}handleTrackUnsubscribed(t,i,n){t.kind===Us.Kind.Audio&&(e(this,Rl,"m",xl).call(this,t),"detach"in t&&"function"==typeof t.detach&&e(this,Rl,"m",Ol).call(this,t),this.emit("trackUnsubscribed",{track:t,publication:i,participant:n.identity||"unknown"}))}handleLocalTrackUnsubscribed(e,t,i){this.handleTrackUnsubscribed(e,t,i)}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(t){const i=t.callback||t.onData;if(!i)throw new Error('Audio capture requires either "callback" or "onData" option');this.audioCaptureEnabled=!0,this.audioCaptureOptions={source:t.source||"agent",trackSourceFilter:t.trackSourceFilter||"microphone",format:t.format||"opus-webm",chunkSize:t.chunkSize||100,bufferSize:t.bufferSize||2048,callback:i},e(this,Rl,"m",Vl).call(this)}disableAudioCapture(){this.audioCaptureEnabled=!1,e(this,Rl,"m",Jl).call(this),this.audioCaptureOptions=null,this.workletReady=null}cleanup(){e(this,Rl,"m",Jl).call(this);for(const e of this.audioElements)try{e?.parentNode?.removeChild&&e.parentNode.removeChild(e)}catch{}this.audioElements.clear(),this.trackStats.clear()}}var Xl,Zl,eu,tu,iu,nu,ru,su,au,ou,cu,du,lu,uu,hu,pu;Rl=new WeakSet,Pl=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)}`))}},Il=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)}`))},Ml=function(t,i,n){this.trackStats.set(t.sid||t.mediaStreamTrack?.id||"unknown",{trackId:t.sid||t.mediaStreamTrack?.id||"unknown",kind:t.kind,participant:n.identity||"unknown",subscriptionTime:Date.now(),publication:i,source:e(this,Rl,"m",Bl).call(this,i.source),muted:i.isMuted,enabled:i.isEnabled,dimensions:i.dimensions,simulcasted:i.simulcasted})},Dl=function(t,i,n){const r=t.attach();r&&(r.volume=this.volume,r.autoplay=!0,e(this,Rl,"m",Nl).call(this,r),this.audioElements.add(r),e(this,Rl,"m",Al).call(this,t,i,n),e(this,Rl,"m",_l).call(this,r),e(this,Rl,"m",Ll).call(this,t,n))},Al=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)},_l=function(e){e.style.display="none";try{document.body.appendChild(e)}catch{}},Ll=function(t,i){if(!this.audioCaptureEnabled||!this.audioCaptureOptions)return;const n=t.sid||t.mediaStreamTrack?.id||"unknown",r=(i.identity||"").toLowerCase().includes("agent")?"agent":"user",{source:s,format:a,trackSourceFilter:o}=this.audioCaptureOptions;if("both"!==s&&s!==r)return;const c=e(this,Rl,"m",Bl).call(this,t.source);"all"!==o&&o!==c||a&&e(this,Rl,"m",ql).call(this,n,i.identity||"unknown",r,a)},Ol=function(e){for(const t of e.detach()){try{t?.parentNode?.removeChild&&t.parentNode.removeChild(t)}catch{}this.audioElements.delete(t)}},xl=function(e){this.trackStats.delete(e.sid||e.mediaStreamTrack?.id||"unknown")},Nl=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")}))},Ul=function(){if(this.audioContext)return;const e=globalThis.AudioContext||globalThis.webkitAudioContext;if("function"==typeof e)try{const t=new e({sampleRate:16e3});this.audioContext=t,"suspended"===t.state&&t.resume().catch((e=>{this.logger.warn("Failed to auto-resume AudioContext:",{source:"LiveKitAudioManager",error:e})}))}catch{try{this.audioContext=new e}catch{this.audioContext=null}}},Fl=function(){try{if(e(this,Rl,"m",Ul).call(this),!this.audioContext)return;let t=null;const i=this.room?.localParticipant?.getTrackPublication;if(i)try{t=i(Us.Source.Microphone)}catch{t=i("microphone")}const n=t?.track?.mediaStreamTrack;if(!n)return;const r=new MediaStream([n]),s=this.audioContext.createMediaStreamSource(r),a=this.audioContext.createAnalyser();a.fftSize=256;{const e=s;e&&"function"==typeof e.connect&&e.connect(a)}this.inputAnalyser=a}catch{this.inputAnalyser=null}},jl=function(){try{if(e(this,Rl,"m",Ul).call(this),!this.audioContext)return;const t=this.audioElements.values().next().value;if(!t)return;const i=this.audioContext.createMediaElementSource(t),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}},Bl=function(e){switch(e){case Us.Source.Microphone:return"microphone";case Us.Source.Camera:return"camera";case Us.Source.ScreenShare:return"screen_share";case Us.Source.ScreenShareAudio:return"screen_share_audio";default:return"unknown"}},Vl=function(){if(!this.audioCaptureOptions)return;const{source:t,format:i,trackSourceFilter:n}=this.audioCaptureOptions;if(i)for(const[r,s]of this.trackStats.entries()){const a=s.participant.toLowerCase().includes("agent")?"agent":"user";if("both"!==t&&t!==a)continue;const o=s.source;"all"!==n&&n!==o||e(this,Rl,"m",ql).call(this,r,s.participant,a,i)}},ql=function(t,i,n,r){if(!this.audioCaptureOptions)return;const s=e(this,Rl,"m",Gl).call(this,t);if(!s?.mediaStreamTrack)return;if(this.trackCaptureMap.has(t))return void this.logger.log(`Skipping duplicate setup for ${n} (${t})`,{source:"LiveKitAudioManager"});const a=e(this,Rl,"m",Bl).call(this,s.source);this.trackCaptureMap.set(t,{participant:i,source:n});const o=s.mediaStreamTrack.clone(),c=new MediaStream([o]);this.clonedTracks.set(t,o),"opus-webm"===r?e(this,Rl,"m",Kl).call(this,{stream:c,trackId:t,participant:i,source:n,trackSource:a}):e(this,Rl,"m",Hl).call(this,{stream:c,trackId:t,participant:i,source:n,format:r,trackSource:a})},Kl=function(t){const{stream:i,trackId:n,participant:r,source:s,trackSource:a}=t;if(!this.audioCaptureOptions?.callback)return;const{chunkSize:o,callback:c}=this.audioCaptureOptions;try{const t=e(this,Rl,"m",Ql).call(this),d=new MediaRecorder(i,t?{mimeType:t}:{});d.ondataavailable=e=>{e.data.size>0&&e.data.arrayBuffer().then((e=>{const t={participant:r,source:s,timestamp:Date.now(),trackId:n,trackSource:a,format:"opus-webm"};c(e,t)}))},d.start(o),this.recorders.set(n,d)}catch(e){this.emit("error",new Error(`Failed to setup encoded audio capture: ${e instanceof Error?e.message:String(e)}`))}},Hl=function(t){const{stream:i,trackId:n,participant:r,source:s,format:a,trackSource:o}=t;if(!this.audioCaptureOptions?.callback)return;const{callback:c}=this.audioCaptureOptions,d=this.audioCaptureOptions.bufferSize||4096;try{if(e(this,Rl,"m",Ul).call(this),!this.audioContext)throw new Error("WebAudio is not supported in this environment");const t=this.audioContext;if("suspended"===t.state&&t.resume().catch((()=>{})),t.audioWorklet&&"function"==typeof t.audioWorklet.addModule)return void e(this,Rl,"m",Wl).call(this,{audioContext:t,stream:i,trackId:n,participant:r,source:s,trackSource:o,format:a,bufferSize:d,callback:c});e(this,Rl,"m",zl).call(this,{audioContext:t,stream:i,trackId:n,participant:r,source:s,trackSource:o,format:a,bufferSize:d,callback:c})}catch(e){this.emit("error",new Error(`Failed to setup PCM audio capture: ${e instanceof Error?e.message:String(e)}`))}},Wl=async function(t){const{audioContext:i,stream:n,trackId:r,participant:s,source:a,trackSource:o,format:c,bufferSize:d,callback:l}=t;try{this.workletReady||(this.workletReady=(async()=>{const e=new Blob(["\n class PCMProcessor extends AudioWorkletProcessor {\n constructor(options) {\n super();\n this.bufferSize = options.processorOptions.bufferSize || 4096;\n this.buffer = new Float32Array(this.bufferSize);\n this.index = 0;\n }\n\n process(inputs, outputs, parameters) {\n const input = inputs[0];\n if (!input || !input.length) return true;\n\n const channelData = input[0];\n if (!channelData) return true;\n\n for (let i = 0; i < channelData.length; i++) {\n this.buffer[this.index++] = channelData[i];\n\n if (this.index >= this.bufferSize) {\n const bufferToSend = this.buffer.slice(0, this.bufferSize);\n this.index = 0;\n this.port.postMessage(bufferToSend, [bufferToSend.buffer]);\n }\n }\n \n return true;\n }\n }\n registerProcessor('pcm-processor', PCMProcessor);\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);await i.audioWorklet.addModule(t),URL.revokeObjectURL(t)})()),await this.workletReady;const t=i.createMediaStreamSource(n),u=new AudioWorkletNode(i,"pcm-processor",{processorOptions:{bufferSize:d}});u.port.onmessage=t=>{const n=t.data,d="pcm-i16"===c?e(this,Rl,"m",Yl).call(this,n):n,u={participant:s,source:a,timestamp:Date.now(),trackId:r,trackSource:o,format:c,sampleRate:i.sampleRate,channels:1};try{l(d,u)}catch(e){this.logger.error(`Callback error for ${a}:`,{source:"LiveKitAudioManager",error:e})}},u.onprocessorerror=e=>{this.logger.error(`Worklet processor error for ${a} (${r}):`,{source:"LiveKitAudioManager",error:e})},t.connect(u),this.sourceNodes.set(r,t),this.processors.set(r,u);const h=i.createGain();h.gain.value=0,u.connect(h),h.connect(i.destination),this.processors.set(`${r}_gain`,h)}catch(i){this.logger.error(`AudioWorklet setup failed for ${a}:`,{source:"LiveKitAudioManager",error:i}),this.workletReady=null,e(this,Rl,"m",zl).call(this,t)}},zl=function(t){const{audioContext:i,stream:n,trackId:r,participant:s,source:a,trackSource:o,format:c,bufferSize:d,callback:l}=t;try{const t=i.createMediaStreamSource(n),u=i.createScriptProcessor(d,1,1);u.onaudioprocess=t=>{const i=t.inputBuffer,n=i.getChannelData(0),d="pcm-i16"===c?e(this,Rl,"m",Yl).call(this,n):new Float32Array(n),u={participant:s,source:a,timestamp:Date.now(),trackId:r,trackSource:o,format:c,sampleRate:i.sampleRate,channels:i.numberOfChannels};l(d,u)},t.connect(u),this.sourceNodes.set(r,t),this.processors.set(r,u);const h=i.createGain();h.gain.value=0,u.connect(h),h.connect(i.destination),this.processors.set(`${r}_gain`,h)}catch(e){this.logger.error(`ScriptProcessor setup failed for ${a}:`,{source:"LiveKitAudioManager",error:e})}},Gl=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},Jl=function(){this.workletReady=null;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{}this.processors.clear();for(const e of this.sourceNodes.values())try{e.disconnect()}catch{}this.sourceNodes.clear();for(const e of this.clonedTracks.values())try{e.stop()}catch{}if(this.clonedTracks.clear(),this.trackCaptureMap.clear(),this.audioContext){const e=this.audioContext;"closed"!==e.state&&e.close().catch((()=>{})),this.audioContext=null}},Ql=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""},Yl=function(e){const t=e.length,i=new Int16Array(t);for(let n=0;n<t;n++)i[n]=32767*Math.max(-1,Math.min(1,e[n]));return i};const mu=/iP(hone|ad|od)|iPhone/i;class gu extends n.EventEmitter{constructor(t,i,n=!1,r=!1){super(),Xl.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=t,this.accessToken=i,this.logger=el(n),this.isChatOnly=r,this.room=new Jd({adaptiveStream:!0,dynacast:!0,videoCaptureDefaults:{resolution:bs.h720.resolution},audioCaptureDefaults:{echoCancellation:!0,noiseSuppression:!0}}),e(this,Xl,"m",Zl).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++;"undefined"!=typeof navigator&&mu.test(navigator.userAgent)||this.room?.prepareConnection(this.lkUrl,this.accessToken);const e=Date.now();await(this.room?.connect(this.lkUrl,this.accessToken,{maxRetries:3})),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"),e(this,Xl,"m",pu).call(this)}async disconnect(){const t=Date.now();try{if(this.logger.log("LiveKitConnection.disconnect() - START",{source:"LiveKitConnection",error:{timestamp:t,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();e(this,Xl,"m",pu).call(this);const n=Date.now();this.logger.log("LiveKitConnection.disconnect() - COMPLETE",{source:"LiveKitConnection",error:{timestamp:n,cleanupDuration:n-i,totalDisconnectDuration:n-t}})}catch(e){const i=Date.now();this.logger.error("LiveKitConnection.disconnect() - FAILED",{source:"LiveKitConnection",error:{timestamp:i,timeSinceStart:i-t,error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}}),this.emit("connectionError",new Error(`LiveKit disconnection failed: ${e instanceof Error?e.message:String(e)}`))}}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(){e(this,Xl,"m",pu).call(this)}}Xl=new WeakSet,Zl=function(){this.room&&this.room.on($r.Connected,e(this,Xl,"m",eu).bind(this)).on($r.Disconnected,e(this,Xl,"m",tu).bind(this)).on($r.Reconnecting,e(this,Xl,"m",iu).bind(this)).on($r.Reconnected,e(this,Xl,"m",nu).bind(this)).on($r.ParticipantConnected,e(this,Xl,"m",ru).bind(this)).on($r.ParticipantDisconnected,e(this,Xl,"m",su).bind(this)).on($r.ParticipantAttributesChanged,e(this,Xl,"m",au).bind(this)).on($r.ConnectionStateChanged,e(this,Xl,"m",ou).bind(this)).on($r.SignalConnected,e(this,Xl,"m",cu).bind(this)).on($r.SignalReconnecting,e(this,Xl,"m",du).bind(this)).on($r.MediaDevicesError,e(this,Xl,"m",lu).bind(this)).on($r.ConnectionQualityChanged,e(this,Xl,"m",uu).bind(this)).on($r.DCBufferStatusChanged,e(this,Xl,"m",hu).bind(this))},eu=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}}),this.isChatOnly?this.logger.log("Chat-only session: skipping microphone enable",{source:"LiveKitConnection"}):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)}`))}},tu=function(){const t=Date.now();this.logger.log("Room Disconnected event fired (from LiveKit SDK) - TIMING",{source:"LiveKitConnection",error:{timestamp:t,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 r=Date.now();e(this,Xl,"m",pu).call(this);const s=Date.now();this.logger.log("Room Disconnected handler complete - TIMING",{source:"LiveKitConnection",error:{timestamp:s,cleanupDuration:s-r,totalHandlerDuration:s-t}})},iu=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")},nu=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")},ru=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)},su=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)},au=function(e,t){if("lk.agent.state"in e){const t=e["lk.agent.state"];void 0!==t&&this.emit("agentStateChanged",t)}},ou=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)},cu=function(){this.logger.log("Signal connection established",{source:"LiveKitConnection",error:{roomName:this.room?.name,state:this.room?.state}})},du=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}})},lu=function(e){this.logger.error("Media devices error",{source:"LiveKitConnection",error:{error:e.message,stack:e.stack,roomName:this.room?.name}})},uu=function(e,t){this.logger.log("Connection quality changed",{source:"LiveKitConnection",error:{participant:t.identity,quality:e,roomName:this.room?.name}})},hu=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}})},pu=function(){this.participants.clear(),this.isConnected=!1,this.isPaused=!1,this.hasEmittedConnected=!1};const fu="lk.chat";class vu extends n.EventEmitter{constructor(e=[],t=!1){super(),this.room=null,this.tools=[],this.registeredMethods=new Set,this.fallbackMessageIdCounter=0,this.chatStreamRegistered=!1,this.tools=e,this.logger=el(t)}setRoom(e){this.room=e,e&&this.tools.length>0&&this.registerTools(),e&&this.registerChatStreamHandler(e)}registerChatStreamHandler(e){if(!this.chatStreamRegistered)try{e.registerTextStreamHandler(fu,(async(t,i)=>{const n=e.localParticipant?.identity,r=i.identity===n?"user":"agent",s=t.info.id;let a="";for await(const e of t)a+=e,this.emitChatMessage({id:s,role:r,text:a,isFinal:!1});this.emitChatMessage({id:s,role:r,text:a,isFinal:!0})})),this.chatStreamRegistered=!0,this.logger.log("Registered chat text-stream handler",{source:"LiveKitToolRegistry",error:{topic:fu}})}catch(e){this.logger.error("Failed to register chat text-stream handler",{source:"LiveKitToolRegistry",error:e})}}setTools(e){this.tools=Array.isArray(e)?e:[],this.room&&this.registerTools()}registerTools(){if(this.room&&0!==this.tools.length){this.unregisterAllTools();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),t));return JSON.stringify(n)}catch(t){return this.emit("rpcError",e.function_name,t),JSON.stringify({error:t instanceof Error?t.message:String(t)})}})),this.registeredMethods.add(e.function_name));this.emit("toolsRegistered",this.tools)}}unregisterAllTools(){if(this.room){for(const e of this.registeredMethods)try{this.room.unregisterRpcMethod(e)}catch{}this.registeredMethods.clear()}}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,vu.PAYLOAD_PREVIEW_LENGTH)}});const n=JSON.parse(i),r=n.event,s=n.content||n.data||n;switch(this.logger.log("📨 Parsed message structure",{source:"LiveKitToolRegistry",error:{eventType:r,hasContent:!!n.content,hasData:!!n.data,contentType:typeof s,contentPreview:"string"==typeof s?s.substring(0,vu.TEXT_PREVIEW_LENGTH):JSON.stringify(s).substring(0,vu.TEXT_PREVIEW_LENGTH)}}),r){case"answer":this.logger.log("✅ Emitting answerReceived event",{source:"LiveKitToolRegistry",error:{eventData:s.substring(0,vu.TEXT_PREVIEW_LENGTH),participant:t}}),this.emit("answerReceived",s);break;case"transcription":this.logger.log("✅ Emitting transcriptionReceived event (from data)",{source:"LiveKitToolRegistry",error:{eventData:s.substring(0,vu.TEXT_PREVIEW_LENGTH),participant:t}}),this.emit("transcriptionReceived",s);break;default:this.logger.log("⚡ Emitting customEvent",{source:"LiveKitToolRegistry",error:{eventType:r,eventData:"string"==typeof s?s.substring(0,vu.TEXT_PREVIEW_LENGTH):JSON.stringify(s).substring(0,vu.TEXT_PREVIEW_LENGTH),participant:t}}),this.emit("customEvent",r,s,{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,vu.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"}});const n=i?"agent":"user";for(const r of e)r.text&&(i?(this.logger.log("✅ Emitting answerReceived event (from LiveKit)",{source:"LiveKitToolRegistry",error:{text:r.text.substring(0,vu.TEXT_PREVIEW_LENGTH),final:r.final,textLength:r.text.length,participant:t}}),this.emit("answerReceived",r.text)):(this.logger.log("✅ Emitting transcriptionReceived event (from LiveKit)",{source:"LiveKitToolRegistry",error:{text:r.text.substring(0,vu.TEXT_PREVIEW_LENGTH),final:r.final,textLength:r.text.length,participant:t}}),this.emit("transcriptionReceived",r.text)),this.emitMessageReceived({id:r.id,role:n,text:r.text,isFinal:r.final??!1}))}catch(i){this.logger.error("❌ Error processing transcription",{source:"LiveKitToolRegistry",error:{message:i instanceof Error?i.message:String(i),transcriptionsCount:e.length,participant:t}})}}buildReceivedMessage(e){let t=e.id;return t||(this.fallbackMessageIdCounter+=1,t=`msg-${this.fallbackMessageIdCounter}`),{id:t,role:e.role,text:e.text,isFinal:e.isFinal,timestamp:Date.now()}}emitMessageReceived(e){const t=this.buildReceivedMessage(e);this.logger.log("✅ Emitting messageReceived event",{source:"LiveKitToolRegistry",error:{id:t.id,role:t.role,isFinal:t.isFinal,textLength:t.text.length}}),this.emit("messageReceived",t)}emitChatMessage(e){const t=this.buildReceivedMessage(e);this.logger.log("✅ Emitting chatMessageReceived event",{source:"LiveKitToolRegistry",error:{id:t.id,role:t.role,isFinal:t.isFinal,textLength:t.text.length}}),this.emit("chatMessageReceived",t),this.emit("messageReceived",t)}getToolCount(){return this.tools.length}getTools(){return this.tools}cleanup(){if(this.chatStreamRegistered){try{this.room?.unregisterTextStreamHandler(fu)}catch(e){this.logger.error("Failed to unregister chat text-stream handler",{source:"LiveKitToolRegistry",error:e})}this.chatStreamRegistered=!1}}}var ku,yu,bu,Tu,Su,Cu,wu,Eu,Ru,Pu,Iu,Mu,Du,Au,_u,Lu,Ou,xu;vu.TEXT_PREVIEW_LENGTH=100,vu.PAYLOAD_PREVIEW_LENGTH=200;class Nu extends n.EventEmitter{constructor(t,i,n=[],{debug:r=!1,avatarContainerSelector:s,isChatOnly:a=!1}={}){super(),ku.add(this),this.lkUrl=t,this.accessToken=i,this.logger=el(r),this.avatarContainerSelector=s,this.videoElements=new Set,this.logger.log("Initializing LiveKitManager",{source:"LiveKitManager",error:{lkUrl:t,toolsCount:n.length,debug:r}}),this.logger.log("Creating LiveKitConnection module",{source:"LiveKitManager"}),this.connection=new gu(t,i,r,a),this.logger.log("Creating LiveKitAnalytics module",{source:"LiveKitManager"}),this.analytics=new El(r),this.logger.log("Creating LiveKitAudioManager module",{source:"LiveKitManager"}),this.audioManager=new $l(r),this.logger.log("Creating LiveKitToolRegistry module",{source:"LiveKitManager",error:{toolsCount:n.length}}),this.toolRegistry=new vu(n,r),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"}),e(this,ku,"m",yu).call(this),this.logger.log("Setting up event forwarding",{source:"LiveKitManager"}),e(this,ku,"m",bu).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 r=Date.now();this.logger.log("LiveKitManager.disconnect() - COMPLETE",{source:"LiveKitManager",error:{timestamp:r,cleanupDuration:r-n,totalDisconnectDuration:r-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();for(const e of this.videoElements)e.remove();this.videoElements.clear()}}ku=new WeakSet,yu=function(){this.connection.on("connected",(()=>{const t=this.connection.room;this.analytics.setRoom(t),this.toolRegistry.setRoom(t),this.audioManager.setRoom(t),this.analytics.setConnectionState(!0,this.connection.callStartTime),this.toolRegistry.registerTools(),this.analytics.startAnalyticsCollection(),e(this,ku,"m",Tu).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",(()=>{e(this,ku,"m",wu).call(this)})),this.connection.on("participantDisconnected",(()=>{e(this,ku,"m",wu).call(this)})),this.audioManager.on("trackSubscribed",(()=>{e(this,ku,"m",wu).call(this)})),this.audioManager.on("trackUnsubscribed",(()=>{e(this,ku,"m",wu).call(this)}))},bu=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("messageReceived",(e=>this.emit("messageReceived",e))),this.toolRegistry.on("chatMessageReceived",(e=>this.emit("chatMessageReceived",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))),this.toolRegistry.on("rpcError",((e,t)=>this.emit("rpcError",e,t)))},Tu=function(){const t=this.connection.room;if(!t)return;const i=[[$r.TrackSubscribed,(t,i,n)=>{this.logger.log("Track subscribed",{source:"LiveKitManager",error:{trackSid:t.sid,trackKind:t.kind,participantIdentity:n.identity,isMuted:i.isMuted}}),this.audioManager.handleTrackSubscribed(t,i,n),t.kind===Us.Kind.Video&&e(this,ku,"m",Su).call(this,t)}],[$r.TrackUnsubscribed,(t,i,n)=>{this.logger.log("Track unsubscribed",{source:"LiveKitManager",error:{trackSid:t.sid,trackKind:t.kind,participantIdentity:n.identity}}),this.audioManager.handleTrackUnsubscribed(t,i,n),t.kind===Us.Kind.Video&&e(this,ku,"m",Cu).call(this,t)}],[$r.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)}],[$r.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)}],[$r.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)}],[$r.AudioPlaybackStatusChanged,e=>{this.logger.log("Audio playback status changed",{source:"LiveKitManager",error:{playing:e,state:e?"started":"stopped"}}),this.analytics.handleAudioPlaybackChanged(e)}],[$r.MediaDevicesError,e=>{this.logger.error("Media devices error",{source:"LiveKitManager",error:{message:e.message,name:e.name}}),this.emit("mediaDevicesError",e)}],[$r.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}),e.kind===Us.Kind.Audio&&e.track instanceof Us&&this.audioManager.handleLocalTrackPublished(e.track,e,t.localParticipant)}],[$r.LocalTrackUnpublished,e=>{this.logger.log("Local track unpublished",{source:"LiveKitManager",error:{trackSid:e.trackSid,trackKind:e.kind}}),e.kind===Us.Kind.Audio&&e.track&&this.audioManager.handleLocalTrackUnsubscribed(e.track,e,t.localParticipant)}]];for(const[e,n]of i)t.on(e,n)},Su=function(e){if(!this.avatarContainerSelector)return;const t=document.querySelector(this.avatarContainerSelector);if(!t)return void this.logger.warn("Avatar container element not found",{source:"LiveKitManager",error:{selector:this.avatarContainerSelector}});const i=e.attach();i instanceof HTMLVideoElement&&(i.autoplay=!0,i.playsInline=!0,i.style.width="100%",i.style.height="100%",i.style.objectFit="cover",t.appendChild(i),this.videoElements.add(i),this.logger.log("Avatar video attached to container",{source:"LiveKitManager",error:{selector:this.avatarContainerSelector,trackSid:e.sid}}))},Cu=function(e){for(const t of e.detach())t instanceof HTMLVideoElement&&(t.remove(),this.videoElements.delete(t))},wu=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 Uu{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 Fu extends Error{constructor(e,t){super(e),this.name="HamsaApiError",this.messageKey=t}}const ju={eu:{API_URL:"https://api.tryhamsa.com",LIVEKIT_URL:"wss://rtc.eu.tryhamsa.com"},uae:{API_URL:"https://api.uae.tryhamsa.com",LIVEKIT_URL:"wss://rtc.uae.tryhamsa.com"}};class Bu extends n.EventEmitter{constructor(e,{region:t="eu",API_URL:i,LIVEKIT_URL:n,debug:r=!1}={}){super(),Eu.add(this),this.liveKitManager=null,this.jobId=null,this.userInitiatedEnd=!1;const s=ju[t];this.liveKitManager=null,this.apiKey=e,this.API_URL=i??s.API_URL,this.LIVEKIT_URL=n??s.LIVEKIT_URL,this.debug=r,this.logger=el(r),this.jobId=null,this.wakeLockManager=new Uu}setVolume(e){this.liveKitManager&&this.liveKitManager.setVolume(e)}getOutputVolume(){return this.liveKitManager?.audioManager.getOutputVolume()??Bu.DEFAULT_OUTPUT_VOLUME}getJobId(){return this.jobId}getInputVolume(){return this.liveKitManager?.audioManager.getInputVolume()??Bu.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}})}sendDTMF(e){const t={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,"*":10,"#":11};if(!(e in t))throw new Error(`Invalid DTMF digit: "${e}". Valid digits are 0-9, *, and #.`);const i=this.liveKitManager?.connection?.room;if(!this.liveKitManager?.isConnected||!i?.localParticipant)throw new Error("Cannot send DTMF: not connected to voice agent. Call start() first.");const n=t[e];this.logger.log("Sending DTMF digit",{source:"HamsaVoiceAgent",error:{digit:e,code:n}}),i.localParticipant.publishDtmf(n,e),this.logger.log("DTMF digit sent successfully",{source:"HamsaVoiceAgent",error:{digit:e,code:n}}),this.emit("dtmfSent",e)}async sendMessage(e){if("string"!=typeof e||0===e.trim().length)throw new Error("Cannot send message: text must be a non-empty string.");const t=this.liveKitManager?.connection?.room;if(!this.liveKitManager?.isConnected||!t?.localParticipant)throw new Error("Cannot send message: not connected to agent. Call start() first.");this.logger.log("Sending chat message",{source:"HamsaVoiceAgent",error:{length:e.length,preview:e.substring(0,50),topic:fu}});try{await t.localParticipant.sendText(e,{topic:fu})}catch(e){throw this.logger.error("Failed to send chat message",{source:"HamsaVoiceAgent",error:e}),this.emit("error",e instanceof Error?e:new Error(String(e))),e}this.logger.log("Chat message sent successfully",{source:"HamsaVoiceAgent"}),this.emit("messageSent",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:t,params:i={},voiceEnablement:n=!1,isChatOnly:r=!1,tools:s=[],userId:a,preferHeadphonesForIosDevices:o=!1,connectionDelay:c,disableWakeLock:d=!1,onAudioData:l,captureAudio:u,avatarContainerSelector:h}){try{this.logger.log("SDK initialized - disconnect debugging enabled",{source:"HamsaVoiceAgent"}),this.userInitiatedEnd=!1,this.logger.log("Starting conversation initialization",{source:"HamsaVoiceAgent",error:{agentId:t,voiceEnablement:n,toolsCount:s?.length??0,hasParams:Object.keys(i).length>0}});const a=await e(this,Eu,"m",Mu).call(this,{voiceAgentId:t,params:i,voiceEnablement:n,tools:s,isChatOnly:r});this.logger.log("Creating LiveKitManager instance",{source:"HamsaVoiceAgent",error:{livekitUrl:this.LIVEKIT_URL,tokenLength:a.length,debug:this.debug}}),this.liveKitManager=new Nu(this.LIVEKIT_URL,a,s,{debug:this.debug,avatarContainerSelector:h,isChatOnly:r}),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"}),u?(this.logger.log("Enabling audio capture via captureAudio options",{source:"HamsaVoiceAgent",error:{source:u.source,format:u.format}}),this.liveKitManager?.audioManager.enableAudioCapture(u)):l&&(this.logger.log("Enabling audio capture via onAudioData",{source:"HamsaVoiceAgent"}),this.liveKitManager?.audioManager.enableAudioCapture({source:"agent",format:"opus-webm",chunkSize:100,callback:l})),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("messageReceived",(e=>{this.emit("messageReceived",e)})).on("chatMessageReceived",(e=>{this.emit("chatMessageReceived",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))).on("toolsRegistered",(e=>this.emit("toolsRegistered",e))).on("rpcError",((e,t)=>this.emit("rpcError",e,t))),this.logger.log("Connecting to LiveKit room",{source:"HamsaVoiceAgent",error:{livekitUrl:this.LIVEKIT_URL}});const o=Date.now();await this.liveKitManager.connect();const c=Date.now()-o;this.logger.log("Connected to LiveKit room",{source:"HamsaVoiceAgent",error:{duration:`${c}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()-o+"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 Fu}}),this.listenerCount("error")>0)if(e instanceof Fu)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 t=Date.now();this.logger.log("end() called - START DISCONNECT TIMING",{source:"HamsaVoiceAgent",error:{timestamp:t,userInitiatedEnd:this.userInitiatedEnd,isConnected:this.liveKitManager?.isConnected??!1,stack:new Error("Stack trace").stack}}),e(this,Eu,"m",Ru).call(this,t).then((()=>{const e=Date.now();this.logger.log("end() completed - END DISCONNECT TIMING",{source:"HamsaVoiceAgent",error:{timestamp:e,totalDuration:e-t}})})).catch((i=>{e(this,Eu,"m",Iu).call(this,i,t)})),e(this,Eu,"m",Pu).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(t=5,i=1e3,n=2){if(!this.jobId)throw new Error("Cannot fetch job details: jobId is not set. Start a conversation first.");const r=`${this.API_URL}/v1/voice-agents/conversation/${this.jobId}`,s={Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},a=new URLSearchParams({jobId:this.jobId});let o=i;const c=async(i=1)=>{try{const e=await fetch(`${r}?${a.toString()}`,{method:"GET",headers:s});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(r){if(i<t)return await e(this,Eu,"m",xu).call(this,o),o*=n,c(i+1);throw new Error(`Failed to fetch job details after ${t} attempts: ${r instanceof Error?r.message:String(r)}`)}};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}}}Eu=new WeakSet,Ru=async function(e){if(!this.liveKitManager)return;this.userInitiatedEnd=!0;const t=Date.now();this.logger.log("Calling liveKitManager.disconnect()",{source:"HamsaVoiceAgent",error:{timestamp:t,timeSinceEndCalled:t-e}}),await this.liveKitManager.disconnect();const i=Date.now();this.logger.log("liveKitManager.disconnect() completed",{source:"HamsaVoiceAgent",error:{timestamp:i,disconnectCallDuration:i-t}}),this.emit("callEnded");const n=Date.now();this.logger.log("callEnded event emitted",{source:"HamsaVoiceAgent",error:{timestamp:n,totalTimeInEndMethod:n-e}})},Pu=function(){this.wakeLockManager?.isActive()&&this.wakeLockManager.release().catch((e=>{}))},Iu=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 Fu)this.emit("error",e);else{const t=e instanceof Error?e.message:String(e);this.emit("error",new Error(`Failed to end call: ${t}`))}},Mu=async function(t){const{voiceAgentId:i,params:n,voiceEnablement:r,tools:s,isChatOnly:a}=t,o={Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},c=await e(this,Eu,"m",Au).call(this,i,n,o,a),d=c.liveKitAccessToken,l=e(this,Eu,"m",Lu).call(this,d,c.jobId,i);return await e(this,Eu,"m",_u).call(this,{voiceAgentId:i,params:n,voiceEnablement:r,tools:s,headers:o,jobIdFromToken:l,tokenData:c,isChatOnly:a}),this.jobId=l,d},Du=function(e,t,i=!1){try{const e=JSON.parse(t);if(e.message)throw new Fu(e.message,e.messageKey)}catch(e){if(e instanceof Fu)throw e}const n=i?`${e.status} ${e.statusText} - ${t}`:t;throw new Fu(n)},Au=async function(t,i,n,r){this.logger.log("Fetching participant token from API",{source:"HamsaVoiceAgent",error:{voiceAgentId:t,apiUrl:this.API_URL,paramsCount:Object.keys(i).length}});const s=Date.now(),a=await fetch(`${this.API_URL}/v1/voice-agents/room/participant-token`,{method:"POST",headers:n,body:JSON.stringify({voiceAgentId:t,params:i,isChatOnly:r})}),o=Date.now()-s;if(this.logger.log("Received API response for participant token",{source:"HamsaVoiceAgent",error:{status:a.status,ok:a.ok,duration:`${o}ms`}}),!a.ok){const t=await a.text();this.logger.error("API request failed for participant token",{source:"HamsaVoiceAgent",error:{status:a.status,statusText:a.statusText,errorText:t}}),e(this,Eu,"m",Du).call(this,a,t,!0)}const c=await a.json();if(!c?.success||!c?.data?.liveKitAccessToken)throw this.logger.error("Invalid token response structure",{source:"HamsaVoiceAgent",error:{success:c?.success,hasToken:!!c?.data?.liveKitAccessToken}}),new Error("Failed to get LiveKit access token");return this.logger.log("Successfully received LiveKit access token",{source:"HamsaVoiceAgent",error:{tokenLength:c.data.liveKitAccessToken.length,hasJobId:!!c.data.jobId,jobId:c.data.jobId}}),c.data},_u=async function(t){const{voiceAgentId:i,params:n,voiceEnablement:r,tools:s,headers:a,jobIdFromToken:o,tokenData:c,isChatOnly:d}=t,l=s?.length>0?e(this,Eu,"m",Ou).call(this,s):[],u={tools:l,voiceEnablement:r,voiceAgentId:i,params:n,jobId:o??c.jobId??i,channelType:d?"Chat Agent":"Web",isChatOnly:d};this.logger.log("Initializing conversation with API",{source:"HamsaVoiceAgent",error:{voiceAgentId:i,toolsCount:l.length,voiceEnablement:r,jobId:u.jobId,channelType:u.channelType,isChatOnly:d}});const h=Date.now(),p=await fetch(`${this.API_URL}/v1/voice-agents/room/conversation-init`,{method:"POST",headers:a,body:JSON.stringify(u),redirect:"follow"}),m=Date.now()-h;if(this.logger.log("Received conversation init response",{source:"HamsaVoiceAgent",error:{status:p.status,ok:p.ok,duration:`${m}ms`}}),!p.ok){const t=await p.text();this.logger.error("Conversation initialization failed",{source:"HamsaVoiceAgent",error:{status:p.status,statusText:p.statusText,errorText:t}}),e(this,Eu,"m",Du).call(this,p,t,!1)}this.logger.log("Conversation initialized successfully",{source:"HamsaVoiceAgent"})},Lu=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 r("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 r(`Invalid token specified: missing part #${i+1}`);let a;try{a=s(n)}catch(e){throw new r(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(a)}catch(e){throw new r(`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},Ou=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}})))},xu=function(e){return new Promise((t=>setTimeout(t,e)))},Bu.DEFAULT_OUTPUT_VOLUME=0,Bu.DEFAULT_INPUT_VOLUME=0,exports.HamsaApiError=Fu,exports.HamsaVoiceAgent=Bu,exports.RpcError=Id,exports.default=Bu;
1
+ "use strict";function e(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)}Object.defineProperty(exports,"__esModule",{value:!0}),"function"==typeof SuppressedError&&SuppressedError;var t,i={exports:{}};var n=function(){if(t)return i.exports;t=1;var e,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}i.exports=a,i.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}f(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&f(e,"error",t,i)}(e,r,{once:!0})}))},a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=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?a.defaultMaxListeners:e._maxListeners}function l(e,t,i,n){var r,s,a,o;if(c(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),a=s[t]),void 0===a)a=s[t]=i,++e._eventsCount;else if("function"==typeof a?a=s[t]=n?[i,a]:[a,i]:n?a.unshift(i):a.push(i),(r=d(e))>0&&a.length>r&&!a.warned){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=a.length,o=l,console&&console.warn&&console.warn(o)}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},r=u.bind(n);return r.listener=i,n.wrapFn=r,r}function p(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):g(r,r.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 r(s){n.once&&e.removeEventListener(t,r),i(s)}))}}return Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),a.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||s(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},a.prototype.getMaxListeners=function(){return d(this)},a.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,s=this._events;if(void 0!==s)n=n&&void 0===s.error;else if(!n)return!1;if(n){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)r(c,this,t);else{var d=c.length,l=g(c,d);for(i=0;i<d;++i)r(l[i],this,t)}return!0},a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)},a.prototype.once=function(e,t){return c(t),this.on(e,h(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,h(this,e,t)),this},a.prototype.removeListener=function(e,t){var i,n,r,s,a;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(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},a.prototype.listeners=function(e){return p(this,e,!0)},a.prototype.rawListeners=function(e){return p(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},a.prototype.listenerCount=m,a.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},i.exports}();class r extends Error{}function s(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)}r.prototype.name="InvalidTokenError";var o=Object.defineProperty,c=(e,t,i)=>((e,t,i)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class d{constructor(){c(this,"_locking"),c(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 l(e,t){if(!e)throw new Error(t)}function u(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 h(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 p(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 m=Symbol("@bufbuild/protobuf/enum-type");function g(e){const t=e[m];return l(t,"missing enum type on enum object"),t}function f(e,t,i,n){e[m]=v(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function v(e,t,i){const n=Object.create(null),r=Object.create(null),s=[];for(const e of t){const t=y(e);s.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:s,findName:e=>n[e],findNumber:e=>r[e]}}function 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 f(n,e,t),n}function y(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class b{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function T(){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 r=e>>>n,s=!(r>>>7==0&&0==t),a=255&(s?128|r:r);if(i.push(a),!s)return}const n=e>>>28&15|(7&t)<<4,r=!!(t>>3);if(i.push(255&(r?128|n:n)),r){for(let e=3;e<31;e+=7){const n=t>>>e,r=!(n>>>7==0),s=255&(r?128|n:n);if(i.push(s),!r)return}i.push(t>>>31&1)}}const C=4294967296;function w(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,r=0;function s(t,s){const a=Number(e.slice(t,s));r*=i,n=n*i+a,n>=C&&(r+=n/C|0,n%=C)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?P(n,r):R(n,r)}function E(e,t){var i=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=i.lo,(t=i.hi)<=2097151)return String(C*t+e);const n=16777215&(e>>>24|t<<8),r=t>>16&65535;let s=(16777215&e)+6777216*n+6710656*r,a=n+8147497*r,o=2*r;const c=1e7;return s>=c&&(a+=Math.floor(s/c),s%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+I(a)+I(s)}function R(e,t){return{lo:0|e,hi:0|t}}function P(e,t){return t=~t,e?e=1+~e:t+=1,R(e,t)}const I=e=>{const t=String(e);return"0000000".slice(t.length)+t};function M(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 D(){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 A=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>r||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>l(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>l(/^[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),w(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),w(e)),dec:(e,t)=>function(e,t){let i=R(e,t);const n=2147483648&i.hi;n&&(i=P(i.lo,i.hi));const r=E(i.lo,i.hi);return n?"-"+r:r}(e,t),uDec:(e,t)=>E(e,t)}}();var _,L,O;function x(e,t,i){if(t===i)return!0;if(e==_.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case _.UINT64:case _.FIXED64:case _.INT64:case _.SFIXED64:case _.SINT64:return t==i}return!1}function N(e,t){switch(e){case _.BOOL:return!1;case _.UINT64:case _.FIXED64:case _.INT64:case _.SFIXED64:case _.SINT64:return 0==t?A.zero:"0";case _.DOUBLE:case _.FLOAT:return 0;case _.BYTES:return new Uint8Array(0);case _.STRING:return"";default:return 0}}function U(e,t){switch(e){case _.BOOL:return!1===t;case _.STRING:return""===t;case _.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function F(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i<t;i++)n[i]=e[i];return n}function j(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function B(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var n,r,s,a,o=[],c=!0,d=!1;try{if(s=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(n=s.call(i)).done)&&(o.push(n.value),o.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(d)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return F(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?F(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!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"}(_||(_={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(L||(L={})),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"}(O||(O={}));class V{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(h(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return u(e),M(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){p(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){h(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){u(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return u(e),M(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=A.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=A.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=A.enc(e);return S(t.lo,t.hi,this.buf),this}sint64(e){let t=A.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=A.uEnc(e);return S(t.lo,t.hi,this.buf),this}}class q{constructor(e,t){this.varint64=T,this.uint32=D,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 O.Varint:for(;128&this.buf[this.pos++];);break;case O.Bit64:this.pos+=4;case O.Bit32:this.pos+=4;break;case O.LengthDelimited:let i=this.uint32();this.pos+=i;break;case O.StartGroup:for(;;){const e=B(this.tag(),2),i=e[0],n=e[1];if(n===O.EndGroup){if(void 0!==t&&i!==t)throw new Error("invalid end group tag");break}this.skip(n,i)}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 A.dec(...this.varint64())}uint64(){return A.uDec(...this.varint64())}sint64(){let e=B(this.varint64(),2),t=e[0],i=e[1],n=-(1&t);return t=(t>>>1|(1&i)<<31)^n,i=i>>>1^n,A.dec(t,i)}bool(){let e=B(this.varint64(),2),t=e[0],i=e[1];return 0!==t||0!==i}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return A.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return A.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 K(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 N(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 H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),W=[];for(let e=0;e<H.length;e++)W[H[e].charCodeAt(0)]=e;W["-".charCodeAt(0)]=H.indexOf("+"),W["_".charCodeAt(0)]=H.indexOf("/");const z={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),r=0,s=0,a=0;for(let t=0;t<e.length;t++){if(i=W[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=i,s=1;break;case 1:n[r++]=a<<2|(48&i)>>4,a=i,s=2;break;case 2:n[r++]=(15&a)<<4|(60&i)>>2,a=i,s=3;break;case 3:n[r++]=(3&a)<<6|i,s=0}}if(1==s)throw Error("invalid base64 string.");return n.subarray(0,r)},enc(e){let t,i="",n=0,r=0;for(let s=0;s<e.length;s++)switch(t=e[s],n){case 0:i+=H[t>>2],r=(3&t)<<4,n=1;break;case 1:i+=H[r|t>>4],r=(15&t)<<2,n=2;break;case 2:i+=H[r|t>>6],i+=H[63&t],n=0}return n&&(i+=H[r],i+="=",1==n&&(i+="=")),i}};function G(e,t,i){Y(t,e);const n=t.runtime.bin.makeReadOptions(i),r=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),s=B(K(t),2),a=s[0],o=s[1];for(const e of r)t.runtime.bin.readField(a,n.readerFactory(e.data),t.field,e.wireType,n);return o()}function J(e,t,i,n){Y(t,e);const r=t.runtime.bin.makeReadOptions(n),s=t.runtime.bin.makeWriteOptions(n);if(Q(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const a=s.writerFactory();let o=t.field;o.opt||o.repeated||"enum"!=o.kind&&"scalar"!=o.kind||(o=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(o,i,a,s);const c=r.readerFactory(a.finish());for(;c.pos<c.len;){const t=B(c.tag(),2),i=t[0],n=t[1],r=c.skip(n,i);e.getType().runtime.bin.onUnknownField(e,i,n,r)}}function Q(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 Y(e,t){l(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function $(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:!U(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function X(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?N(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Z(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(b.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 ee(e,t){return Z(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}_.DOUBLE,_.FLOAT,_.INT64,_.UINT64,_.INT32,_.UINT32,_.BOOL,_.STRING,_.BYTES;const te={ignoreUnknownFields:!1},ie={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ne(e){return e?Object.assign(Object.assign({},te),e):te}function re(e){return e?Object.assign(Object.assign({},ie),e):ie}const se=Symbol(),ae=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 ce(e,t,i,n,r){let s=i.localName;if(i.repeated){if(l("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const a=e[s];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(oe(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=ue(i.T,e,n.ignoreUnknownFields,!0);t!==ae&&a.push(t);break;case"scalar":try{a.push(le(i.T,e,i.L,!0))}catch(t){let n="cannot decode field ".concat(r.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(r.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const o=e[s];for(const e of Object.entries(t)){var a=B(e,2);const s=a[0],c=a[1];if(null===c)throw new Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: map value null"));let d;try{d=de(i.K,s)}catch(e){let n="cannot decode map key for field ".concat(r.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":o[d]=i.V.T.fromJson(c,n);break;case"enum":const e=ue(i.V.T,c,n.ignoreUnknownFields,!0);e!==ae&&(o[d]=e);break;case"scalar":try{o[d]=le(i.V.T,c,L.BIGINT,!0)}catch(e){let n="cannot decode map value for field ".concat(r.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:s},s="value"),i.kind){case"message":const a=i.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let o=e[s];Z(o)?o.fromJson(t,n):(e[s]=o=a.fromJson(t,n),a.fieldWrapper&&!i.oneof&&(e[s]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=ue(i.T,t,n.ignoreUnknownFields,!1);switch(c){case se:X(i,e);break;case ae:break;default:e[s]=c}break;case"scalar":try{const n=le(i.T,t,i.L,!1);if(n===se)X(i,e);else e[s]=n}catch(e){let n="cannot decode field ".concat(r.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 de(e,t){if(e===_.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return le(e,t,L.BIGINT,!0).toString()}function le(e,t,i,n){if(null===t)return n?N(e,i):se;switch(e){case _.DOUBLE:case _.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==_.FLOAT&&p(n),n;case _.INT32:case _.FIXED32:case _.SFIXED32:case _.SINT32:case _.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==_.UINT32||e==_.FIXED32?h(r):u(r),r;case _.INT64:case _.SFIXED64:case _.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const s=A.parse(t);return i?s.toString():s;case _.FIXED64:case _.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=A.uParse(t);return i?a.toString():a;case _.BOOL:if("boolean"!=typeof t)break;return t;case _.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case _.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return z.dec(t)}throw new Error}function ue(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:se;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 ae}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(oe(t)))}function he(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function pe(e,t,i){if("map"==e.kind){l("object"==typeof t&&null!=t);const a={},o=Object.entries(t);switch(e.V.kind){case"scalar":for(const t of o){var n=B(t,2);const i=n[0],r=n[1];a[i.toString()]=ge(e.V.T,r)}break;case"message":for(const e of o){var r=B(e,2);const t=r[0],n=r[1];a[t.toString()]=n.toJson(i)}break;case"enum":const t=e.V.T;for(const e of o){var s=B(e,2);const n=s[0],r=s[1];a[n.toString()]=me(t,r,i.enumAsInteger)}}return i.emitDefaultValues||o.length>0?a:void 0}if(e.repeated){l(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(ge(e.T,t[i]));break;case"enum":for(let r=0;r<t.length;r++)n.push(me(e.T,t[r],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 ge(e.T,t);case"enum":return me(e.T,t,i.enumAsInteger);case"message":return ee(e.T,t).toJson(i)}}function me(e,t,i){var n;if(l("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const r=e.findNumber(t);return null!==(n=null==r?void 0:r.name)&&void 0!==n?n:t}function ge(e,t){switch(e){case _.INT32:case _.SFIXED32:case _.SINT32:case _.FIXED32:case _.UINT32:return l("number"==typeof t),t;case _.FLOAT:case _.DOUBLE:return l("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case _.STRING:return l("string"==typeof t),t;case _.BOOL:return l("boolean"==typeof t),t;case _.UINT64:case _.FIXED64:case _.INT64:case _.SFIXED64:case _.SINT64:return l("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case _.BYTES:return l(t instanceof Uint8Array),z.enc(t)}}const fe=Symbol("@bufbuild/protobuf/unknown-fields"),ve={readUnknownFields:!0,readerFactory:e=>new q(e)},ke={writeUnknownFields:!0,writerFactory:()=>new V};function ye(e){return e?Object.assign(Object.assign({},ve),e):ve}function be(e){return e?Object.assign(Object.assign({},ke),e):ke}function Te(e,t,i,n,r){let s=i.repeated,a=i.localName;switch(i.oneof&&((e=e[i.oneof.localName]).case!=a&&delete e.value,e.case=a,a="value"),i.kind){case"scalar":case"enum":const o="enum"==i.kind?_.INT32:i.T;let c=we;if("scalar"==i.kind&&i.L>0&&(c=Ce),s){let i=e[a];if(n==O.LengthDelimited&&o!=_.STRING&&o!=_.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,o))}else i.push(c(t,o))}else e[a]=c(t,o);break;case"message":const d=i.T;s?e[a].push(Se(t,new d,r,i)):Z(e[a])?Se(t,e[a],r,i):(e[a]=Se(t,new d,r,i),!d.fieldWrapper||i.oneof||i.repeated||(e[a]=d.fieldWrapper.unwrapField(e[a])));break;case"map":let l=function(e,t,i){const n=t.uint32(),r=t.pos+n;let s,a;for(;t.pos<r;){switch(B(t.tag(),1)[0]){case 1:s=we(t,e.K);break;case 2:switch(e.V.kind){case"scalar":a=we(t,e.V.T);break;case"enum":a=t.int32();break;case"message":a=Se(t,new e.V.T,i,void 0)}}}void 0===s&&(s=N(e.K,L.BIGINT));"string"!=typeof s&&"number"!=typeof s&&(s=s.toString());if(void 0===a)switch(e.V.kind){case"scalar":a=N(e.V.T,L.BIGINT);break;case"enum":a=e.V.T.values[0].no;break;case"message":a=new e.V.T}return[s,a]}(i,t,r),u=B(l,2),h=u[0],p=u[1];e[a][h]=p}}function Se(e,t,i,n){const r=t.getType().runtime.bin,s=null==n?void 0:n.delimited;return r.readMessage(t,e,s?n.no:e.uint32(),i,s),t}function Ce(e,t){const i=we(e,t);return"bigint"==typeof i?i.toString():i}function we(e,t){switch(t){case _.STRING:return e.string();case _.BOOL:return e.bool();case _.DOUBLE:return e.double();case _.FLOAT:return e.float();case _.INT32:return e.int32();case _.INT64:return e.int64();case _.UINT64:return e.uint64();case _.FIXED64:return e.fixed64();case _.BYTES:return e.bytes();case _.FIXED32:return e.fixed32();case _.SFIXED32:return e.sfixed32();case _.SFIXED64:return e.sfixed64();case _.SINT64:return e.sint64();case _.UINT32:return e.uint32();case _.SINT32:return e.sint32()}}function Ee(e,t,i,n){l(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let a="enum"==e.kind?_.INT32:e.T;if(r)if(l(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,O.LengthDelimited).fork();let r=B(Me(t),2)[1];for(let t=0;t<n.length;t++)e[r](n[t]);e.join()}(i,a,e.no,t);else for(const n of t)Ie(i,a,e.no,n);else Ie(i,a,e.no,t);break;case"message":if(r){l(Array.isArray(t));for(const r of t)Pe(i,n,e,r)}else Pe(i,n,e,t);break;case"map":l("object"==typeof t&&null!=t);for(const r of Object.entries(t)){var s=B(r,2);Re(i,n,e,s[0],s[1])}}}function Re(e,t,i,n,r){e.tag(i.no,O.LengthDelimited),e.fork();let s=n;switch(i.K){case _.INT32:case _.FIXED32:case _.UINT32:case _.SFIXED32:case _.SINT32:s=Number.parseInt(n);break;case _.BOOL:l("true"==n||"false"==n),s="true"==n}switch(Ie(e,i.K,1,s),i.V.kind){case"scalar":Ie(e,i.V.T,2,r);break;case"enum":Ie(e,_.INT32,2,r);break;case"message":l(void 0!==r),e.tag(2,O.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Pe(e,t,i,n){const r=ee(i.T,n);i.delimited?e.tag(i.no,O.StartGroup).raw(r.toBinary(t)).tag(i.no,O.EndGroup):e.tag(i.no,O.LengthDelimited).bytes(r.toBinary(t))}function Ie(e,t,i,n){l(void 0!==n);let r=B(Me(t),2),s=r[0],a=r[1];e.tag(i,s)[a](n)}function Me(e){let t=O.Varint;switch(e){case _.BYTES:case _.STRING:t=O.LengthDelimited;break;case _.DOUBLE:case _.FIXED64:case _.SFIXED64:t=O.Bit64;break;case _.FIXED32:case _.SFIXED32:case _.FLOAT:t=O.Bit32}return[t,_[e].toLowerCase()]}function De(e){if(void 0===e)return e;if(Z(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ae(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class _e{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 Le(e,t){const i=xe(e);return t?i:Be(je(i))}const Oe=xe;function xe(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}const Ne=new Set(["constructor","toString","toJSON","valueOf"]),Ue=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Fe=e=>"".concat(e,"$"),je=e=>Ue.has(e)?Fe(e):e,Be=e=>Ne.has(e)?Fe(e):e;class Ve{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=Le(e,!1)}addField(e){l(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 qe=(Ke=e=>new _e(e,(e=>function(e){var t,i,n,r,s,a;const o=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Le(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Oe(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:L.BIGINT),e.delimited=null!==(r=d.delimited)&&void 0!==r&&r,e.req=null!==(s=d.req)&&void 0!==s&&s,e.opt=null!==(a=d.opt)&&void 0!==a&&a,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=_.BYTES&&d.T!=_.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Ve(t)),e.oneof=c,c.addField(e)}o.push(e)}return o}(e))),He=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]=N(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ne,makeWriteOptions:re,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 r=new Map,s=i.typeRegistry;for(const o of Object.entries(t)){var a=B(o,2);const t=a[0],c=a[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const i=r.get(d.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(i,'", "').concat(t,'"'));r.set(d.oneof,t)}ce(n,c,d,i,e)}else{let r=!1;if((null==s?void 0:s.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const a=s.findExtension(t.substring(1,t.length-1));if(a&&a.extendee.typeName==e.typeName){r=!0;const e=B(K(a),2),t=e[0],s=e[1];ce(t,c,a.field,i,a),J(n,a,s(),i)}}if(!r&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let r;try{for(r of i.fields.byNumber()){if(!$(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!he(r))continue}const i=pe(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t);void 0!==i&&(n[t.useProtoFieldName?r.name:r.jsonName]=i)}const s=t.typeRegistry;if(null==s?void 0:s.findExtensionFor)for(const r of i.runtime.bin.listUnknownFields(e)){const a=s.findExtensionFor(i.typeName,r.no);if(a&&Q(e,a)){const i=G(e,a,t),r=pe(a.field,i,t);void 0!==r&&(n[a.field.jsonName]=r)}}}catch(e){const t=r?"cannot encode field ".concat(i.typeName,".").concat(r.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)=>le(e,t,null!=i?i:L.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||U(e,t)?ge(e,t):void 0},debug:oe},bin:{makeReadOptions:ye,makeWriteOptions:be,listUnknownFields(e){var t;return null!==(t=e[fe])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[fe]},writeUnknownFields(e,t){const i=e[fe];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const r=e;Array.isArray(r[fe])||(r[fe]=[]),r[fe].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,r){const s=e.getType(),a=r?t.len:t.pos+i;let o,c;for(;t.pos<a;){var d=B(t.tag(),2);if(o=d[0],c=d[1],!0===r&&c==O.EndGroup)break;const i=s.fields.find(o);if(i)Te(e,t,i,c,n);else{const i=t.skip(c,o);n.readUnknownFields&&this.onUnknownField(e,o,c,i)}}if(r&&(c!=O.EndGroup||o!==i))throw new Error("invalid end group tag")},readField:Te,writeMessage(e,t,i){const n=e.getType();for(const r of n.fields.byNumber())if($(r,e))Ee(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t,i);else if(r.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Ee(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:f,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const r of i.fields.byMember()){const i=r.localName,s=t,a=e;if(null!=a[i])switch(r.kind){case"oneof":const e=a[i].case;if(void 0===e)continue;const t=r.findField(e);let o=a[i].value;t&&"message"==t.kind&&!Z(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===_.BYTES&&(o=Ae(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let c=a[i];r.T===_.BYTES&&(c=r.repeated?c.map(Ae):Ae(c)),s[i]=c;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===_.BYTES)for(const e of Object.entries(a[i])){var n=B(e,2);const t=n[0],r=n[1];s[i][t]=Ae(r)}else Object.assign(s[i],a[i]);break;case"message":const e=r.V.T;for(const t of Object.keys(a[i])){let n=a[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const d=r.T;if(r.repeated)s[i]=a[i].map((e=>Z(e,d)?e:new d(e)));else{const e=a[i];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?s[i]=Ae(e):s[i]=e:s[i]=Z(e,d)?e:new d(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,r[i])));case"scalar":return n.every(((t,i)=>x(e.T,t,r[i])));case"enum":return n.every(((e,t)=>x(_.INT32,e,r[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=n,i=r;return e.T.fieldWrapper&&(void 0===t||Z(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===i||Z(i)||(i=e.T.fieldWrapper.wrapField(i))),e.T.equals(t,i);case"enum":return x(_.INT32,n,r);case"scalar":return x(e.T,n,r);case"oneof":if(n.case!==r.case)return!1;const s=e.findField(n.case);if(void 0===s)return!0;switch(s.kind){case"message":return s.T.equals(n.value,r.value);case"enum":return x(_.INT32,n.value,r.value);case"scalar":return x(s.T,n.value,r.value)}throw new Error("oneof cannot contain ".concat(s.kind));case"map":const a=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return a.every((e=>t.equals(n[e],r[e])));case"enum":return a.every((e=>x(_.INT32,n[e],r[e])));case"scalar":const i=e.V.T;return a.every((e=>x(i,n[e],r[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const i of t.fields.byMember()){const t=e[i.localName];let s;if(i.repeated)s=t.map(De);else if("map"==i.kind){s=n[i.localName];for(const e of Object.entries(t)){var r=B(e,2);const t=r[0],i=r[1];s[t]=De(i)}}else s="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:De(t.value)}:{case:void 0}:De(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:Ke,initFields:He}),makeMessageType(e,t,i){return function(e,t,i,n){var r;const s=null!==(r=null==n?void 0:n.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),a={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(a.prototype,new b),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new a).fromBinary(e,t),fromJson:(e,t)=>(new a).fromJson(e,t),fromJsonString:(e,t)=>(new a).fromJsonString(e,t),equals:(t,i)=>e.util.equals(a,t,i)}),a}(this,e,t,i)},makeEnum:k,makeEnumType:v,getEnumType:g,makeExtension(e,t,i){return function(e,t,i,n){let r;return{typeName:t,extendee:i,get field(){if(!r){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),r=e.util.newFieldList([i]).list()[0]}return r},runtime:e}}(this,e,t,i)}});var Ke,He;class We extends b{constructor(e){super(),this.seconds=A.zero,this.nanos=0,qe.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(qe.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=A.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 We.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new We({seconds:A.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new We).fromBinary(e,t)}static fromJson(e,t){return(new We).fromJson(e,t)}static fromJsonString(e,t){return(new We).fromJsonString(e,t)}static equals(e,t){return qe.util.equals(We,e,t)}}We.runtime=qe,We.typeName="google.protobuf.Timestamp",We.fields=qe.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const ze=qe.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:We},{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:Qe,repeated:!0}])),Ge=qe.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:Je,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Je=qe.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:We},{no:3,name:"value",kind:"scalar",T:2}])),Qe=qe.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:We},{no:7,name:"normalized_end_timestamp",kind:"message",T:We,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Ye=qe.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),$e=qe.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Xe=qe.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"}]),Ze=qe.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),et=qe.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),tt=qe.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),it=qe.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"},{no:16,name:"AGENT_ERROR"}]),nt=qe.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"}]),rt=qe.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),st=qe.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"}]),at=qe.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"}]),ot=qe.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:ct,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:Wt}])),ct=qe.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),dt=qe.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:qe.getEnumType(Xe),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}])),lt=qe.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:qe.getEnumType(ut)},{no:4,name:"tracks",kind:"message",T:ft,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:dt},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:qe.getEnumType(ht)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:qe.getEnumType(it)},{no:18,name:"kind_details",kind:"enum",T:qe.getEnumType(pt),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:vt,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5}])),ut=qe.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ht=qe.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),pt=qe.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"}]),mt=qe.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),gt=qe.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:yt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:qe.getEnumType(bt)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),ft=qe.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:qe.getEnumType($e)},{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:qe.getEnumType(Xe)},{no:10,name:"layers",kind:"message",T:yt,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:gt,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:qe.getEnumType(mt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Wt},{no:19,name:"audio_features",kind:"enum",T:qe.getEnumType(st),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:qe.getEnumType(Ye)},{no:21,name:"packet_trailer_features",kind:"enum",T:qe.getEnumType(at),repeated:!0}])),vt=qe.makeMessageType("livekit.DataTrackInfo",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:qe.getEnumType(mt)}])),kt=qe.makeMessageType("livekit.DataTrackSubscriptionOptions",(()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}])),yt=qe.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:qe.getEnumType(Ze)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}])),bt=qe.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),Tt=qe.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:qe.getEnumType(St)},{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:Pt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Et,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:It,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Mt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:ze,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:At,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:_t,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Lt,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ot,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Qt,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Yt,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:$t,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Ct,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),St=qe.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Ct=qe.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:qe.getEnumType(mt)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}])),wt=qe.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Pt,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:At,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:_t,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Lt,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Ot,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Qt,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Yt,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:$t,oneof:"value"}])),Et=qe.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Rt,repeated:!0}])),Rt=qe.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}])),Pt=qe.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}])),It=qe.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Mt=qe.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:Dt,repeated:!0}])),Dt=qe.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}])),At=qe.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}])),_t=qe.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},{no:6,name:"compressed_payload",kind:"scalar",T:12}])),Lt=qe.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Ot=qe.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:xt,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}])),xt=qe.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}])),Nt=qe.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Ut=qe.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:qe.getEnumType(Ft)},{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}])),Ft=qe.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),jt=qe.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:qe.getEnumType(Bt)},{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},{no:12,name:"client_protocol",kind:"scalar",T:5},{no:13,name:"capabilities",kind:"enum",T:qe.getEnumType(Vt),repeated:!0}])),Bt=qe.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"}]),Vt=qe.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"}]),qt=qe.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Kt},{no:2,name:"screen",kind:"message",T:Kt},{no:3,name:"resume_connection",kind:"enum",T:qe.getEnumType(tt)},{no:4,name:"disabled_codecs",kind:"message",T:Ht},{no:5,name:"force_relay",kind:"enum",T:qe.getEnumType(tt)}])),Kt=qe.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:qe.getEnumType(tt)}])),Ht=qe.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ct,repeated:!0},{no:2,name:"publish",kind:"message",T:ct,repeated:!0}])),Wt=qe.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),zt=qe.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Gt=qe.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:qe.getEnumType(zt)},{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"}),Jt=qe.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Qt=qe.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:qe.getEnumType(mt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Gt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Jt,oneof:"content_header"}]),{localName:"DataStream_Header"}),Yt=qe.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"}),$t=qe.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"}),Xt=qe.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Zt=qe.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),ei=qe.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),ti=qe.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ii=qe.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:ki,oneof:"message"},{no:2,name:"answer",kind:"message",T:ki,oneof:"message"},{no:3,name:"trickle",kind:"message",T:hi,oneof:"message"},{no:4,name:"add_track",kind:"message",T:si,oneof:"message"},{no:5,name:"mute",kind:"message",T:pi,oneof:"message"},{no:6,name:"subscription",kind:"message",T:bi,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ci,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ri,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Ii,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:qi,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Wi,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ji,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Mi,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Qi,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:wi,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Ei,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:ai,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:ci,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Ti,oneof:"message"}])),ni=qe.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:mi,oneof:"message"},{no:2,name:"answer",kind:"message",T:ki,oneof:"message"},{no:3,name:"offer",kind:"message",T:ki,oneof:"message"},{no:4,name:"trickle",kind:"message",T:hi,oneof:"message"},{no:5,name:"update",kind:"message",T:yi,oneof:"message"},{no:6,name:"track_published",kind:"message",T:fi,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ri,oneof:"message"},{no:9,name:"mute",kind:"message",T:pi,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ai,oneof:"message"},{no:11,name:"room_update",kind:"message",T:_i,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Oi,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Ni,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ji,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Ki,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:vi,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:gi,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Yi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Zi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:en,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:nn,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Hi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:cn,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Bi,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:oi,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:di,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:li,oneof:"message"}])),ri=qe.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:yt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:qe.getEnumType(bt)}])),si=qe.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:qe.getEnumType($e)},{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:qe.getEnumType(Xe)},{no:9,name:"layers",kind:"message",T:yt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ri,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:qe.getEnumType(mt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:qe.getEnumType(Ye)},{no:17,name:"audio_features",kind:"enum",T:qe.getEnumType(st),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:qe.getEnumType(at),repeated:!0}])),ai=qe.makeMessageType("livekit.PublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:qe.getEnumType(mt)}])),oi=qe.makeMessageType("livekit.PublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:vt}])),ci=qe.makeMessageType("livekit.UnpublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}])),di=qe.makeMessageType("livekit.UnpublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:vt}])),li=qe.makeMessageType("livekit.DataTrackSubscriberHandles",(()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:ui}}])),ui=qe.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",(()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}]),{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),hi=qe.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:qe.getEnumType(Zt)},{no:3,name:"final",kind:"scalar",T:8}])),pi=qe.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),mi=qe.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:ot},{no:2,name:"participant",kind:"message",T:lt},{no:3,name:"other_participants",kind:"message",T:lt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Di,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:qt},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Ut},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ct,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),gi=qe.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Di,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:qt},{no:3,name:"server_info",kind:"message",T:Ut},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),fi=qe.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ft}])),vi=qe.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),ki=qe.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}])),yi=qe.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:lt,repeated:!0}])),bi=qe.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:Nt,repeated:!0}])),Ti=qe.makeMessageType("livekit.UpdateDataSubscription",(()=>[{no:1,name:"updates",kind:"message",T:Si,repeated:!0}])),Si=qe.makeMessageType("livekit.UpdateDataSubscription.Update",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:kt}]),{localName:"UpdateDataSubscription_Update"}),Ci=qe.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:qe.getEnumType(Ze)},{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}])),wi=qe.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:qe.getEnumType(st),repeated:!0}])),Ei=qe.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}])),Ri=qe.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:qe.getEnumType(it)},{no:3,name:"action",kind:"enum",T:qe.getEnumType(Pi)},{no:4,name:"regions",kind:"message",T:$i}])),Pi=qe.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Ii=qe.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:yt,repeated:!0}])),Mi=qe.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}])),Di=qe.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}])),Ai=qe.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Rt,repeated:!0}])),_i=qe.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:ot}])),Li=qe.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:qe.getEnumType(et)},{no:3,name:"score",kind:"scalar",T:2}])),Oi=qe.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Li,repeated:!0}])),xi=qe.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:qe.getEnumType(ei)}])),Ni=qe.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:xi,repeated:!0}])),Ui=qe.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:qe.getEnumType(Ze)},{no:2,name:"enabled",kind:"scalar",T:8}])),Fi=qe.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Ui,repeated:!0}])),ji=qe.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Ui,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Fi,repeated:!0}])),Bi=qe.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Xt,repeated:!0}])),Vi=qe.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}])),qi=qe.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Vi,repeated:!0}])),Ki=qe.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}])),Hi=qe.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:ot},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:lt},{no:4,name:"other_participants",kind:"message",T:lt,repeated:!0}])),Wi=qe.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:ki},{no:2,name:"subscription",kind:"message",T:bi},{no:3,name:"publish_tracks",kind:"message",T:fi,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Gi,repeated:!0},{no:5,name:"offer",kind:"message",T:ki},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:zi,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:oi,repeated:!0}])),zi=qe.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Gi=qe.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:qe.getEnumType(Zt)}])),Ji=qe.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:qe.getEnumType(ti),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"}])),Qi=qe.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Yi=qe.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),$i=qe.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Xi,repeated:!0}])),Xi=qe.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}])),Zi=qe.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:qe.getEnumType(rt)}])),en=qe.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:qe.getEnumType(tn)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:hi,oneof:"request"},{no:5,name:"add_track",kind:"message",T:si,oneof:"request"},{no:6,name:"mute",kind:"message",T:pi,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Mi,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:wi,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Ei,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:ai,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:ci,oneof:"request"}])),tn=qe.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),nn=qe.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),rn=qe.makeMessageType("livekit.ConnectionSettings",(()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}])),sn=qe.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:jt},{no:2,name:"connection_settings",kind:"message",T:rn},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:si,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:ki},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:qe.getEnumType(nt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Wi}])),an=qe.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:qe.getEnumType(on)},{no:2,name:"join_request",kind:"scalar",T:12}])),on=qe.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),cn=qe.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]));function dn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ln,un={exports:{}};var hn,pn,mn,gn,fn,vn=(ln||(ln=1,pn=un.exports,mn=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"],r={},s=null;function a(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),r=0;r<n.length;r++){var s=n[r];this[s]=r<i?e:this.methodFactory(s,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,r,s){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?o:void 0!==console[n]?a(console,n):void 0!==console.log?a(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var a,o,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+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!=o?o:a},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(a=m(s.getLevel())),c.call(u),s===u)for(var e in r)r[e].rebuild()},a=m(s?s.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(s=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=r[e];return t||(t=r[e]=new u(e,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return r},s.default=s,s},(hn=un).exports?hn.exports=mn():pn.log=mn()),un.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"}(gn||(gn={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",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",e.DataTracks="livekit-data-tracks"}(fn||(fn={}));let kn=vn.getLogger(fn.Default);function yn(e,t){const i=vn.getLogger(e);return i.setDefaultLevel(kn.getLevel()),t?function(e,t){const i=i=>(n,r)=>{const s=t(),a=s||r?Object.assign(Object.assign({},s),r):void 0;e[i](n,a)},n=Object.create(e);return n.trace=i("trace"),n.debug=i("debug"),n.info=i("info"),n.warn=i("warn"),n.error=i("error"),n}(i,t):i}Object.values(fn).map((e=>vn.getLogger(e))),kn.setDefaultLevel(gn.info);const bn=vn.getLogger(fn.E2EE),Tn=7e3,Sn=[0,300,1200,2700,4800,Tn,Tn,Tn,Tn,Tn];function Cn(e,t,i,n){return new(i||(i=Promise))((function(r,s){function a(e){try{c(n.next(e))}catch(e){s(e)}}function o(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}c((n=n.apply(e,t||[])).next())}))}function wn(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 En(e){return this instanceof En?(this.v=e,this):new En(e)}function Rn(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,r=i.apply(e,t||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",(function(e){return function(t){return Promise.resolve(t).then(e,d)}})),n[Symbol.asyncIterator]=function(){return this},n;function a(e,t){r[e]&&(n[e]=function(t){return new Promise((function(i,n){s.push([e,t,i,n])>1||o(e,t)}))},t&&(n[e]=t(n[e])))}function o(e,t){try{(i=r[e](t)).value instanceof En?Promise.resolve(i.value.v).then(c,d):l(s[0][2],i)}catch(e){l(s[0][3],e)}var i}function c(e){o("next",e)}function d(e){o("throw",e)}function l(e,t){e(t),s.shift(),s.length&&o(s[0][0],s[0][1])}}function Pn(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=wn(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,r){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,r,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var In,Mn={exports:{}};var Dn=function(){if(In)return Mn.exports;In=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 r(){r.init.call(this)}Mn.exports=r,Mn.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}m(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,r,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var r,s,c,d;if(a(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),c=s[t]),void 0===c)c=s[t]=i,++e._eventsCount;else if("function"==typeof c?c=s[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(r=o(e))>0&&c.length>r&&!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},r=d.bind(n);return r.listener=i,n.wrapFn=r,r}function u(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):p(r,r.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 r(s){n.once&&e.removeEventListener(t,r),i(s)}))}}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return s},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+".");s=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||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},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=s[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},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,r,s,o;if(a(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){o=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},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 r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},Mn.exports}();let An=!0,_n=!0;function Ln(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function On(e,t,i){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable)return void Un("Unable to polyfill events");const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function xn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(An=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Nn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(_n=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Un(){if("object"==typeof window){if(An)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Fn(e,t){_n&&console.warn(e+" is deprecated, please use "+t+" instead.")}function jn(e){return"[object Object]"===Object.prototype.toString.call(e)}function Bn(e){return jn(e)?Object.keys(e).reduce((function(t,i){const n=jn(e[i]),r=n?Bn(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function Vn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Vn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Vn(e,e.get(t),i)}))})))}function qn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Vn(e,i,r)}))})),r}const Kn=Un;function Hn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const a=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let a=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=n(e.video),Kn("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return Kn("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function Wn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function zn(e,t){if(!(t.version>102))if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else On(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Gn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Jn(e,t){if(t.version>=67)return;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=>qn(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}),On(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>qn(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const i=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 i.apply(this,arguments)}}function Qn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function Yn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Qn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function $n(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 Xn(e,t){t.version>102||On(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Zn=Object.freeze({__proto__:null,fixNegotiationNeeded:Xn,shimAddTrackRemoveTrack:Yn,shimAddTrackRemoveTrackWithNative:Qn,shimGetSendersWithDtmf:Gn,shimGetUserMedia:Hn,shimMediaStream:Wn,shimOnTrack:zn,shimPeerConnection:$n,shimSenderReceiverGetStats:Jn});function er(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Fn("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 tr(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 ir(e,t){"object"==typeof e&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!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]})))}function nr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;if(t.version>=151)return;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=Array.prototype.slice.call(arguments),r=e[0],s=e[1],a=e[2];return"closed"===this.signalingState?Promise.resolve(new Map):n.apply(this,[r||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,a)}}function rr(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 sr(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}),On(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ar(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Fn("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function or(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function cr(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 t=n.sender,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 dr(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 lr(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 ur(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 hr=Object.freeze({__proto__:null,shimAddTransceiver:cr,shimCreateAnswer:ur,shimCreateOffer:lr,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:dr,shimGetStats:nr,shimGetUserMedia:er,shimOnTrack:tr,shimPeerConnection:ir,shimRTCDataChannel:or,shimReceiverGetStats:sr,shimRemoveStream:ar,shimSenderGetStats:rr});function pr(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function mr(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 gr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,o=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=o,o=function(e,t,i){const n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=o}function fr(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(vr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function vr(e){return e&&void 0!==e.video?Object.assign({},e,{video:Bn(e.video)}):e}function kr(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?(Fn("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 yr(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 br(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 Tr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Sr,Cr=Object.freeze({__proto__:null,shimAudioContext:Tr,shimCallbacksAPI:gr,shimConstraints:vr,shimCreateOfferLegacy:br,shimGetUserMedia:fr,shimLocalStreamsAPI:pr,shimRTCIceServerUrls:kr,shimRemoteStreamsAPI:mr,shimTrackEventTransceiver:yr}),wr={exports:{}};var Er=(Sr||(Sr=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&&void 0!==e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],a=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(a){const n=t.parseRtpMap(a),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=a.length>0&&a[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===o&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&o&&i.push({ssrc:o});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;return r=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(wr)),wr.exports),Rr=dn(Er),Pr=a({__proto__:null,default:Rr},[Er]);function Ir(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=Rr.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,On(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Mr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||On(e,"icecandidate",(e=>{if(e.candidate){const t=Rr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function Dr(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){"plan-b"===this.getConfiguration().sdpSemantics&&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=Rr.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Rr.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Rr.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return i.apply(this,arguments)}}function Ar(e,t){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;if("chrome"===t.browser&&t.version>149)return;if("firefox"===t.browser&&t.version>60)return;function i(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return i(e,this),e},On(e,"datachannel",(e=>(i(e.channel,e.target),e)))}function _r(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 Lr(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 Or(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 xr(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 Nr,Ur,Fr=Object.freeze({__proto__:null,removeExtmapAllowMixed:Lr,shimAddIceCandidateNullOrEmpty:Or,shimConnectionState:_r,shimMaxMessageSize:Dr,shimParameterlessSetLocalDescription:xr,shimRTCIceCandidate:Ir,shimRTCIceCandidateRelayProtocol:Mr,shimSendThrowTypeError:Ar});!function(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=Un,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 i=e.navigator;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(Ln(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(Ln(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(Ln(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=Ln(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:n,commonShim:Fr,extractVersion:Ln,disableLog:xn,disableWarnings:Nn,sdp:Pr};switch(n.browser){case"chrome":if(!Zn||!$n||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=Zn,Or(e,n),xr(e),Hn(e,n),Wn(e),$n(e,n),zn(e,n),Yn(e,n),Gn(e),Jn(e,n),Xn(e,n),Ir(e),Mr(e),_r(e),Dr(e,n),Ar(e,n),Lr(e,n);break;case"firefox":if(!hr||!ir||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=hr,Or(e,n),xr(e),er(e,n),ir(e,n),nr(e,n),tr(e),ar(e),rr(e),sr(e),or(e),cr(e),dr(e),lr(e),ur(e),Ir(e),_r(e),Dr(e,n),Ar(e,n);break;case"safari":if(!Cr||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=Cr,Or(e,n),xr(e),kr(e),br(e),gr(e),pr(e),mr(e),yr(e),fr(e),Tr(e),Ir(e),Mr(e),Dr(e,n),Ar(e,n),Lr(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class jr extends(Ur=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}Nr=jr,jr.resolve=e=>Reflect.get(Ur,"resolve",Nr).call(Nr,e);const Br=/version\/(\d+(\.?_?\d+)+)/i;let Vr;function qr(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===Vr||t){const e=Kr.find((e=>e.test.test(i)));Vr=null==e?void 0:e.describe(i)}return Vr}const Kr=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Hr(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Wr(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Hr(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Wr(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Hr(Br,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Wr(e)})}];function Hr(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 Wr(e){return e.includes("mac os")?Hr(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class zr extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==i?void 0:i.cause)&&(this.cause=null==i?void 0:i.cause)}}class Gr extends zr{}var Jr,Qr,Yr,$r,Xr,Zr,es;!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",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(Jr||(Jr={}));class ts extends Gr{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=Jr[t]}static notAllowed(e,t,i){return new ts(e,Jr.NotAllowed,t,i)}static timeout(e){return new ts(e,Jr.Timeout)}static leaveRequest(e,t){return new ts(e,Jr.LeaveRequest,void 0,t)}static internal(e,t){return new ts(e,Jr.InternalError,void 0,t)}static cancelled(e){return new ts(e,Jr.Cancelled)}static serverUnreachable(e,t){return new ts(e,Jr.ServerUnreachable,t)}static websocket(e,t,i){return new ts(e,Jr.WebSocket,t,i)}static serviceNotFound(e,t){return new ts(e,Jr.ServiceNotFound,void 0,t)}}class is extends zr{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class ns extends zr{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class rs extends zr{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class ss extends zr{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class as extends zr{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class os extends zr{constructor(e){super(14,null!=e?e:"unable to publish data"),this.name="PublishDataError"}}class cs extends zr{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class ds extends Gr{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:tn[t]}}!function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(Qr||(Qr={}));class ls extends Gr{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=Qr[t]}}class us extends zr{constructor(e){super(18,e),this.name="SignalReconnectError"}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(Yr||(Yr={})),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}}(Yr||(Yr={}));class hs{}hs.setTimeout=function(){return setTimeout(...arguments)},hs.setInterval=function(){return setInterval(...arguments)},hs.clearTimeout=function(){return clearTimeout(...arguments)},hs.clearInterval=function(){return clearInterval(...arguments)},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",e.DataTrackPublished="dataTrackPublished",e.DataTrackUnpublished="dataTrackUnpublished",e.LocalDataTrackPublished="localDataTrackPublished",e.LocalDataTrackUnpublished="localDataTrackUnpublished"}($r||($r={})),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"}(Xr||(Xr={})),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",e.PublishDataTrackResponse="publishDataTrackResponse",e.UnPublishDataTrackResponse="unPublishDataTrackResponse",e.DataTrackSubscriberHandles="dataTrackSubscriberHandles",e.DataTrackPacketReceived="dataTrackPacketReceived",e.Joined="joined",e.TokenRefreshed="tokenRefreshed",e.ServerRegionsReported="serverRegionsReported"}(Zr||(Zr={})),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"}(es||(es={}));class ps{constructor(e,t,i,n,r){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:r}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const ms=["vp8","h264"],gs=["vp8","h264","vp9","av1","h265"];function fs(e){return!!ms.find((t=>t===e))}const vs=fs;var ks,ys;!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(ks||(ks={})),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}}(ys||(ys={}));const bs={h90:new ps(160,90,9e4,20),h180:new ps(320,180,16e4,20),h216:new ps(384,216,18e4,20),h360:new ps(640,360,45e4,20),h540:new ps(960,540,8e5,25),h720:new ps(1280,720,17e5,30),h1080:new ps(1920,1080,3e6,30),h1440:new ps(2560,1440,5e6,30),h2160:new ps(3840,2160,8e6,30)},Ts={h120:new ps(160,120,7e4,20),h180:new ps(240,180,125e3,20),h240:new ps(320,240,14e4,20),h360:new ps(480,360,33e4,20),h480:new ps(640,480,5e5,20),h540:new ps(720,540,6e5,25),h720:new ps(960,720,13e5,30),h1080:new ps(1440,1080,23e5,30),h1440:new ps(1920,1440,38e5,30)},Ss={h360fps3:new ps(640,360,2e5,3,"medium"),h360fps15:new ps(640,360,4e5,15,"medium"),h720fps5:new ps(1280,720,8e5,5,"medium"),h720fps15:new ps(1280,720,15e5,15,"medium"),h720fps30:new ps(1280,720,2e6,30,"medium"),h1080fps15:new ps(1920,1080,25e5,15,"medium"),h1080fps30:new ps(1920,1080,5e6,30,"medium"),original:new ps(0,0,7e6,30,"medium")};function Cs(e,t,i){var n,r,s,a;const o=Ls(null!=e?e:{}),c=o.optionsWithoutProcessor,d=o.audioProcessor,l=o.videoProcessor,u=null==t?void 0:t.processor,h=null==i?void 0:i.processor,p=null!=c?c:{};return!0===p.audio&&(p.audio={}),!0===p.video&&(p.video={}),p.audio&&(ws(p.audio,t),null!==(n=(s=p.audio).deviceId)&&void 0!==n||(s.deviceId={ideal:"default"}),(d||u)&&(p.audio.processor=null!=d?d:u)),p.video&&(ws(p.video,i),null!==(r=(a=p.video).deviceId)&&void 0!==r||(a.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=null!=l?l:h)),p}function ws(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function Es(e){var t,i,n,r;const s={};if(e.video)if("object"==typeof e.video){const i={},r=i,a=e.video;Object.keys(a).forEach((e=>{if("resolution"===e)ws(r,a.resolution);else r[e]=a[e]})),s.video=i,null!==(t=(n=s.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else s.video=!!e.video&&{deviceId:{ideal:"default"}};else s.video=!1;return e.audio?"object"==typeof e.audio?(s.audio=e.audio,null!==(i=(r=s.audio).deviceId)&&void 0!==i||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Rs(e){return Cn(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Ps();if(i){const n=i.createAnalyser();n.fftSize=2048;const r=n.frequencyBinCount,s=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield Vs(t),n.getByteTimeDomainData(s);const a=s.some((e=>128!==e&&0!==e));return i.close(),!a}return!1}()}))}function Ps(){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=()=>Cn(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}}));i.addEventListener("statechange",(()=>{var t;"closed"===i.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))})),window.document.body.addEventListener("click",e)}return i}}function Is(e){return"audioinput"===e?Us.Source.Microphone:"videoinput"===e?Us.Source.Camera:Us.Source.Unknown}function Ms(e){return e===Us.Source.Microphone?"audioinput":e===Us.Source.Camera?"videoinput":void 0}function Ds(e){return e.split("/")[1].toLowerCase()}function As(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new fi({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function _s(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?_s(e.track):{})}}function Ls(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:(r=t,void 0===r?r:"function"==typeof structuredClone?"object"==typeof r&&null!==r?structuredClone(Object.assign({},r)):structuredClone(r):JSON.parse(JSON.stringify(r)))};var r}function Os(e,t){return e.width*e.height<t.width*t.height}const xs=[];var Ns;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(Ns||(Ns={}));class Us extends Dn.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Us.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=kn,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=yn(null!==(n=i.loggerName)&&void 0!==n?n:fn.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Us.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),_s(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Us.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===Us.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(xs.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&xs.splice(xs.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Fs(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?es.AudioPlaybackStarted:es.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?es.AudioPlaybackFailed:es.VideoPlaybackFailed,t):"AbortError"===t.name?kn.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):kn.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(es.ElementAttached,e),e}detach(e){try{if(e){js(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(es.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{js(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(es.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=yn(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),xs.forEach((e=>{e.parentElement||(t=!1)})),t&&xs.push(e)}}handleAppVisibilityChanged(){return Cn(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Us.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){$s()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){$s()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Fs(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)),Js()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Js()||zs())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function js(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 $e.AUDIO;case t.Video:return $e.VIDEO;default:return $e.DATA}},e.kindFromProto=function(e){switch(e){case $e.AUDIO:return t.Audio;case $e.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return Xe.CAMERA;case i.Microphone:return Xe.MICROPHONE;case i.ScreenShare:return Xe.SCREEN_SHARE;case i.ScreenShareAudio:return Xe.SCREEN_SHARE_AUDIO;default:return Xe.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case Xe.CAMERA:return i.Camera;case Xe.MICROPHONE:return i.Microphone;case Xe.SCREEN_SHARE:return i.ScreenShare;case Xe.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case ei.ACTIVE:return n.Active;case ei.PAUSED:return n.Paused;default:return n.Unknown}}}(Us||(Us={}));const Bs="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Vs(e){return new jr((t=>hs.setTimeout(t,e)))}function qs(){return"addTransceiver"in RTCPeerConnection.prototype}function Ks(){return"addTrack"in RTCPeerConnection.prototype}function Hs(e){return"av1"===e||"vp9"===e}function Ws(e){return!(!document||Qs())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function zs(){var e;return"Firefox"===(null===(e=qr())||void 0===e?void 0:e.name)}function Gs(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform&&!function(){const e=qr();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}()}function Js(){var e;return"Safari"===(null===(e=qr())||void 0===e?void 0:e.name)}function Qs(){const e=qr();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function Ys(){var e,t;return!!$s()&&(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 $s(){return"undefined"!=typeof document}function Xs(){return"ReactNative"==navigator.product}function Zs(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function ea(e){return Zs(e)?e.hostname.split(".")[0]:null}function ta(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ia(){if(!Xs())return;let e=ta();return e?e.platform:void 0}function na(){if($s())return window.devicePixelRatio;if(Xs()){let e=ta();if(e)return e.devicePixelRatio}return 1}function ra(e,t){const i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){const t=parseInt(i[e],10),s=parseInt(n[e],10);if(t>s)return 1;if(t<s)return-1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function sa(e){for(const t of e)t.target.handleResize(t)}function aa(e){for(const t of e)t.target.handleVisibilityChanged(t)}let oa=null;const ca=()=>(oa||(oa=new ResizeObserver(sa)),oa);let da=null;const la=()=>(da||(da=new IntersectionObserver(aa,{root:null,rootMargin:"0px"})),da);function ua(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const r=document.createElement("canvas");r.width=e,r.height=t;const s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const a=B(r.captureStream().getTracks(),1)[0];if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let ha;function pa(){if(!ha){const t=new AudioContext,i=t.createOscillator(),n=t.createGain();n.gain.setValueAtTime(0,0);const r=t.createMediaStreamDestination();i.connect(n),n.connect(r),i.start();var e=B(r.stream.getAudioTracks(),1);if(ha=e[0],!ha)throw Error("Could not get empty media stream audio track");ha.enabled=!1}return ha.clone()}class ma{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,i)=>Cn(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 ga(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function fa(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function va(e){switch(e.reason){case Jr.LeaveRequest:return e.context;case Jr.Cancelled:return it.CLIENT_INITIATED;case Jr.NotAllowed:return it.USER_REJECTED;case Jr.ServerUnreachable:return it.JOIN_FAILURE;default:return it.UNKNOWN_REASON}}function ka(e){return void 0!==e?Number(e):void 0}function ya(e){return void 0!==e?BigInt(e):void 0}function ba(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Ta(e){return!!e&&e.kind==Us.Kind.Audio}function Sa(e){return!!e&&e.kind==Us.Kind.Video}function Ca(e){return ba(e)&&Sa(e)}function wa(e){return ba(e)&&Ta(e)}function Ea(e){return!!e&&!e.isLocal}function Ra(e){return!!e&&!e.isLocal}function Pa(e){return Ea(e)&&Sa(e)}function Ia(){return"undefined"!=typeof CompressionStream}function Ma(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=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)})),Aa(i,"rtc")}(e,t);return i?n:Aa(n,"v1")}function Da(e){return e.endsWith("/")?e:"".concat(e,"/")}function Aa(e,t){return e.pathname="".concat(Da(e.pathname)).concat(t),e}function _a(e){if("string"==typeof e)return ni.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return ni.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const La="lk_e2ee";var Oa,xa,Na,Ua,Fa;function ja(){return Ba()||"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform}function Ba(){return"undefined"!=typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(Oa||(Oa={})),function(e){e.KeyRatcheted="keyRatcheted"}(xa||(xa={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(Na||(Na={})),function(e){e.Error="cryptorError"}(Ua||(Ua={}));Dn.EventEmitter;function Va(){return Gs()}function qa(e){return!!(null==e?void 0:e.worker)&&(Ba()||Va())}function Ka(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}function Ha(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n,r;let s;const a=null!==(n=i.isImmediate)&&void 0!==n&&n,o=null!==(r=i.callback)&&void 0!==r&&r,c=i.maxWait;let d=Date.now(),l=[];const u=function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];const u=this;return new Promise(((i,r)=>{const h=a&&void 0===s;if(void 0!==s&&hs.clearTimeout(s),s=hs.setTimeout((function(){if(s=void 0,d=Date.now(),!a){const t=e.apply(u,n);o&&o(t),l.forEach((e=>(0,e.resolve)(t))),l=[]}}),function(){if(void 0!==c){const e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){const t=e.apply(u,n);return o&&o(t),i(t)}l.push({resolve:i,reject:r})}))};return u.cancel=function(e){void 0!==s&&hs.clearTimeout(s),l.forEach((t=>(0,t.reject)(e))),l=[]},u}!function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(Fa||(Fa={}));const Wa=2e3;function za(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class Ga extends Us{constructor(e,t,i,n,r){super(e,i,r),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?es.Muted:es.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(es.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Cn(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()),Wa)),"undefined"!=typeof RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&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 e=i.timestamp,t=i.rtpTimestamp;t&&this.rtpTimestamp!==t&&(this.emit(es.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Ja extends Ga{constructor(e,t,i,n,r){super(e,t,Us.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>Cn(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=za(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Ha((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}lookupFrameMetadata(e){let t=e.rtpTimestamp;var i;return null===(i=this.frameMetadataExtractor)||void 0===i?void 0:i.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===Us.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?js(this._mediaStreamTrack,t):Fs(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 Qa(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){if(e)return this.stopObservingElement(e),super.detach(e);const 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 Cn(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 Cn(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(e){var t,i;const n=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),r=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!r||s;(this.lastVisible!==a||e)&&(!a&&Date.now()-n<100?hs.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(es.VisibilityChanged,a,this)))}updateDimensions(){var e,t;let i=0,n=0;const r=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*r,s=e.height()*r;t+s>i+n&&(i=t,n=s)}(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(es.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return na();if(!t){return na()>2?2:1}return t}}class Qa{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const i=e.target,n=e.isIntersecting;i===this.element&&(this.isIntersecting=n,this.isPiP=Ya(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),queueMicrotask((()=>{requestAnimationFrame((()=>{var e;this.isPiP=Ya(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)}))}))},this.onLeavePiP=()=>{var e;this.isPiP=Ya(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:$a(e),this.isPiP=$s()&&Ya(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=$a(this.element),this.isPiP=Ya(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,la().observe(this.element),ca().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,r;null===(e=la())||void 0===e||e.unobserve(this.element),null===(t=ca())||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===(r=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===r||r.removeEventListener("pagehide",this.onLeavePiP)}}function Ya(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&$a(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function $a(e,t){const i=t||window;let n=e.offsetTop,r=e.offsetLeft;const s=e.offsetWidth,a=e.offsetHeight,o=e.hidden,c=getComputedStyle(e).display;for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&r<i.pageXOffset+i.innerWidth&&n+a>i.pageYOffset&&r+s>i.pageXOffset&&!o&&"none"!==c}class Xa extends Dn.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;const n=e.data,r=n.kind,s=n.data;switch(r){case"error":if(kn.error(s.error.message),s.uuid){const e=this.decryptDataRequests.get(s.uuid);if(null==e?void 0:e.reject){e.reject(s.error);break}const t=this.encryptDataRequests.get(s.uuid);if(null==t?void 0:t.reject){t.reject(s.error);break}}this.emit(Na.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(Na.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(Na.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(Oa.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const e=this.decryptDataRequests.get(s.uuid);(null==e?void 0:e.resolve)&&e.resolve(s);break;case"encryptDataResponse":const n=this.encryptDataRequests.get(s.uuid);(null==n?void 0:n.resolve)&&n.resolve(s);break;case"packetTrailerMetadata":this.handleFrameMetadata(s.trackId,s.rtpTimestamp,s.ssrc,s.metadata)}},this.onWorkerError=e=>{kn.error("e2ee worker encountered an error:",{error:e.error}),this.emit(Na.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!ja())throw new is("tried to setup end-to-end encryption on an unsupported browser");if(kn.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:bn.getLevel()}};this.worker&&(kn.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){kn.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):kn.warn("ignoring server sent trailer as it's empty")}handleFrameMetadata(e,t,i,n){if(this.room)for(const r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const s of r.trackPublications.values())if(s.track&&s.track.mediaStreamID===e&&s.track instanceof Ja&&s.track.frameMetadataExtractor)return void s.track.frameMetadataExtractor.storeMetadata(t,i,n)}setupEngine(e){e.on(Zr.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on($r.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==mt.NONE,t.identity))),e.on($r.ConnectionStateChanged,(t=>{t===Vd.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==mt.NONE,e.identity)}))}))})).on($r.TrackUnsubscribed,((e,t,i)=>{var n;const r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(r)})).on($r.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on($r.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach((t=>{var i;this.postKey(t,e===(null!==(i=t.keyIndex)&&void 0!==i?i:0))})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),e.localParticipant.on(Xr.LocalSenderCreated,((e,t)=>Cn(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),e.localParticipant.on(Xr.LocalTrackPublished,(e=>{if(!Sa(e.track)||!Qs())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:Ds(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)})),t.on(Oa.SetKey,((e,t)=>this.postKey(e,null==t||t))).on(Oa.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}encryptData(e){return Cn(this,void 0,void 0,(function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new ma;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise}))}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),s={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:n}},a=new ma;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(s),a.promise}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,t){let i=e.key,n=e.participantIdentity,r=e.keyIndex;var s;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:i,keyIndex:r,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}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)return;if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const n="video"===e.kind&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?Ds(i.mimeType):void 0,n)}setupE2EESender(e,t){var i,n,r;ba(e)&&t?this.handleSender(t,e.mediaStreamID,void 0,Sa(e)?null!==(n=null===(i=e.publishOptions)||void 0===i?void 0:i.frameMetadata)&&void 0!==n?n:null===(r=e.publishOptions)||void 0===r?void 0:r.packetTrailer:void 0):t||kn.warn("early return because sender is not ready")}handleReceiver(e,t,i,n,r){return Cn(this,void 0,void 0,(function*(){if(this.worker){if(Gs()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n,hasPacketTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(La in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i,hasPacketTrailer:r}};return void this.worker.postMessage(e)}let s=e.writableStream,a=e.readableStream;if(!s||!a){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,a=t.readable}const o={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:n,participantIdentity:i,isReuse:La in e,hasPacketTrailer:r}};this.worker.postMessage(o,[a,s])}e[La]=!0}}))}handleSender(e,t,i,n){var r;if(!(La in e)&&this.worker){if(!(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Gs()){kn.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:Ka(n),packetTrailer:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{kn.info("initialize encoded streams");const r=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:Ka(n),packetTrailer:n}};this.worker.postMessage(s,[r.readable,r.writable])}e[La]=!0}}}class Za{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,i){for(0!==this.activeSsrc&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=300;){const e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,i)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class eo{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{const t=e.data;if("metadata"===t.kind){const e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{kn.error("frame metadata worker encountered an error:",{error:e.error})},this.worker=null==e?void 0:e.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),e.on($r.TrackSubscribed,((e,t,i)=>{"video"===e.kind&&this.setupReceiver(e,t.trackInfo)})).on($r.TrackUnsubscribed,(e=>{this.teardownTrack(e)})).on($r.Disconnected,(()=>{this.cleanup()})))}setupReceiver(e,t){var i,n,r;const s=e.receiver;if(!s)return;if(!(!!(null==t?void 0:t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0))return void((null===(i=this.room)||void 0===i?void 0:i.hasE2EESetup)||this.setupPassthroughReceiver(s,e.mediaStreamID));if(!qa(this.worker?{worker:this.worker}:void 0)&&!(null===(n=this.room)||void 0===n?void 0:n.hasE2EESetup))return void kn.warn("frame metadata transform not supported; skipping extraction");const a=new Za,o=e.mediaStreamID;this.extractors.set(o,a),e.frameMetadataExtractor=a,(null===(r=this.room)||void 0===r?void 0:r.hasE2EESetup)||this.setupWorkerReceiver(s,o,!0)}setupPassthroughReceiver(e,t){Va()?"transform"in e&&(e.transform=null):(this.worker&&qa({worker:this.worker})&&!this.workerPipelines.has(e)||this.worker&&this.workerPipelines.has(e))&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const n=this.worker;if(!n)return;if(Va())return void(e.transform=new RTCRtpScriptTransform(n,{kind:"decode",trackId:t}));const r=this.workerPipelines.get(e);if(r){const s={kind:"updateTrackId",data:{oldTrackId:r,newTrackId:t,hasPacketTrailer:i}};return n.postMessage(s),void this.workerPipelines.set(e,t)}if(!("createEncodedStreams"in e))return void kn.warn("createEncodedStreams not supported");let s;try{s=e.createEncodedStreams()}catch(e){return void kn.warn("failed to create encoded streams",{error:e})}const a={kind:"decode",data:{readableStream:s.readable,writableStream:s.writable,trackId:t,hasPacketTrailer:i}};n.postMessage(a,[s.readable,s.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,i=this.extractors.get(t);i&&(i.dispose(),this.extractors.delete(t)),e instanceof Ja&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(const e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear(),null===(e=this.worker)||void 0===e||e.terminate()}}class to{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new to),this._instance}addFailedConnectionAttempt(e){var t;const i=ea(new URL(e));if(!i)return;let n=null!==(t=this.failedConnectionAttempts.get(i))&&void 0!==t?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,Vs(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){const t=new URL(e),i=t&&ea(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&ea(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}to._instance=null;const io="default";class no{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new no),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Cn(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=no.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){kn.debug("awaiting getUserMedia promise");try{e?yield no.userMediaPromiseMap.get(e):yield Promise.all(no.userMediaPromiseMap.values())}catch(e){kn.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(i&&(!Js()||!t.hasDeviceInUse(e))){if(0===r.filter((t=>t.kind===e)).length||r.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);r=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=r,e&&(r=r.filter((t=>t.kind===e))),r}()}))}normalizeDeviceId(e,t,i){return Cn(this,void 0,void 0,(function*(){if(t!==io)return t;const n=yield this.getDevices(e),r=n.find((e=>e.deviceId===io));if(!r)return void kn.warn("could not reliably determine default device");const s=n.find((e=>e.deviceId!==io&&e.groupId===(null!=i?i:r.groupId)));if(s)return null==s?void 0:s.deviceId;kn.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?no.userMediaPromiseMap.has(e):no.userMediaPromiseMap.size>0}}no.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],no.userMediaPromiseMap=new Map;const ro=65535,so=4294967295;class ao{static u16(e){return new ao(e,ro)}static u32(e){return new ao(e,so)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new ao(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t+e))}decrement(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t-e))}getThenIncrement(){const e=this.value;return this.increment(),new ao(e,this.maxSize)}isBefore(e){const t=this.value>>>0,i=(e.value>>>0)-t>>>0;return 0!==i&&i<this.maxSize+1}}class oo{static fromRtpTicks(e){return new oo(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*so);return oo.fromRtpTicks(e)}constructor(e,t){this.timestamp=ao.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new oo(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class co{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new co(t,new Date,e)}static startingAtTime(e,t,i){return new co(i,e,t)}static rtpStartingNow(e){return co.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return co.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=co.durationInMsToTicks(t,this.rateInHz),n=this.base.clone();return n.wrappingAdd(i),n.isBefore(this.previous)&&(n=this.previous),this.previous=n.clone(),n.clone()}static durationInMsToTicks(e,t){let i=(1e6*e*t+5e8)/1e9;return Math.round(i)}}function lo(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw new Error("Error coercing ".concat(e," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var uo;!function(e){e[e.Reserved=0]="Reserved",e[e.TooLarge=1]="TooLarge"}(uo||(uo={}));class ho extends Gr{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=uo[t]}isReason(e){return this.reason===e}static tooLarge(){return new ho("Value too large to be a valid track handle",uo.TooLarge)}static reserved(e){return new ho("0x".concat(e.toString(16)," is a reserved value."),uo.Reserved)}}const po={fromNumber(e){if(0===e)throw ho.reserved(e);if(e>ro)throw ho.tooLarge();return e}};class mo{constructor(){this.value=0}get(){return this.value+=1,this.value>ro?null:this.value}reset(){this.value=0}}const go={from:e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==mt.NONE}),toProtobuf:e=>new vt({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?mt.GCM:mt.NONE})};var fo;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(fo||(fo={}));class vo{constructor(){this.pendingTasks=new Map,this.taskMutex=new d,this.nextTaskIndex=0}run(e){return Cn(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:fo.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=fo.RUNNING,yield e()}finally{t.status=fo.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Cn(this,void 0,void 0,(function*(){return this.run((()=>Cn(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}class ko{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;if(null===(i=t.signal)||void 0===i?void 0:i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,null!==(n=t.protocols)&&void 0!==n?n:[]);r.binaryType="arraybuffer",this.ws=r;const s=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.closeCode,i=e.reason;return r.close(t,i)};this.opened=new jr(((e,t)=>{const i=()=>{t(ts.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let i=t.data;return e.enqueue(i)},r.onerror=t=>e.error(t)},cancel:s}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:s}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",i)},r.addEventListener("error",i)})),this.closed=new jr(((e,t)=>{const i=()=>Cn(this,void 0,void 0,(function*(){const i=new jr((e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",(t=>{e(t)}),{once:!0})})),n=yield jr.race([Vs(250),i]);n?e(n):t(ts.websocket("Encountered unspecified websocket error without a timely close event"))}));r.onclose=t=>{let n=t.code,s=t.reason;e({closeCode:n,reason:s}),r.removeEventListener("error",i)},r.addEventListener("error",i)})),t.signal&&(t.signal.onabort=()=>r.close()),this.close=s}}const yo=["syncState","trickle","offer","answer","simulate","leave"];var bo;!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"}(bo||(bo={}));class To{get currentState(){return this.state}get isDisconnected(){return this.state===bo.DISCONNECTING||this.state===bo.DISCONNECTED}get isEstablishingConnection(){return this.state===bo.CONNECTING||this.state===bo.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=bo.DISCONNECTED,this.log=kn,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=t.loggerContextCb,this.log=yn(null!==(i=t.loggerName)&&void 0!==i?i:fn.Signal,(()=>this.logContext)),this.useJSON=e,this.requestQueue=new vo,this.queuedRequests=[],this.closingLock=new d,this.connectionLock=new d,this.state=bo.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 Cn(this,arguments,void 0,(function(e,t,i,n){var r=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=arguments.length>5?arguments[5]:void 0;return function*(){r.state=bo.CONNECTING,r.options=i;return yield r.connect(e,t,i,n,s,a)}()}))}reconnect(e,t,i,n){return Cn(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring");this.state=bo.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath)}))}connect(e,t,i,n){return Cn(this,arguments,void 0,(function(e,t,i,n){var r=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=arguments.length>5?arguments[5]:void 0;return function*(){const o=yield r.connectionLock.lock();r.connectOptions=i,r.useV0SignalPath=s;const c=function(e){var t;const i=new jt({capabilities:e,sdk:Bt.JS,protocol:17,clientProtocol:1,version:"2.20.0"});return Xs()&&(i.os=null!==(t=ia())&&void 0!==t?t:""),i}(i.clientInfoCapabilities),d=s?function(e,t,i){var n;const r=new URLSearchParams;r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid));r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",Xs()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),r.set("client_protocol",t.clientProtocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);i.adaptiveStream&&r.set("adaptive_stream","1");i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&r.set("network",navigator.connection.type);return r}(t,c,i):yield function(e,t,i,n){return Cn(this,void 0,void 0,(function*(){const r=new URLSearchParams;r.set("access_token",e);const s=new sn({clientInfo:t,connectionSettings:new rn({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0,publisherOffer:n});i.reconnectReason&&(s.reconnectReason=i.reconnectReason);const a=s.toBinary();let o,c;if(Ia()){const e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(a)),t.close();const i=[],n=e.readable.getReader();for(;;){const e=yield n.read(),t=e.done,r=e.value;if(t)break;i.push(r)}const r=i.reduce(((e,t)=>e+t.length),0),s=new Uint8Array(r);let d=0;for(const e of i)s.set(e,d),d+=e.length;o=s,c=on.GZIP}else o=a,c=on.NONE;const d=new an({joinRequest:o,compression:c}).toBinary(),l=e=>{const t=Array.from(e,(e=>String.fromCodePoint(e))).join("");return btoa(t)};return r.set("join_request",l(d).replace(/\+/g,"-").replace(/\//g,"_")),r}))}(t,c,i,a),l=Ma(e,d,s).toString(),u=(h=l,Aa(new URL(fa(h)),"validate")).toString();var h;return new Promise(((e,t)=>Cn(r,void 0,void 0,(function*(){var r,s;try{let a=!1;const o=e=>Cn(this,void 0,void 0,(function*(){if(a)return;a=!0;const i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;const i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then((()=>this.close(i))).catch((e=>{this.log.error(e),this.close()})):this.close(),c(),t(ts.cancelled(i))}));null==n||n.addEventListener("abort",o);const c=()=>{clearTimeout(d),null==n||n.removeEventListener("abort",o)},d=setTimeout((()=>{o(ts.timeout("room connection has timed out (signal)"))}),i.websocketTimeout),h=(e,t)=>{this.handleSignalConnected(e,d,t)},p=new URL(l);if(p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.ws){const e=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-e,"ms"))}this.log.info("signal connecting to ".concat(p),{reconnect:i.reconnect,reconnectReason:i.reconnectReason}),this.ws=new ko(l);try{this.ws.closed.then((e=>{var i;this.isEstablishingConnection&&t(ts.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state}),this.state===bo.CONNECTED&&this.handleOnClose(null!==(i=e.reason)&&void 0!==i?i:"Unexpected WS error"))})).catch((e=>{this.isEstablishingConnection&&t(ts.internal("Websocket error during a (re)connection attempt: ".concat(e)))}));const n=yield this.ws.opened.catch((e=>Cn(this,void 0,void 0,(function*(){if(this.state===bo.CONNECTED)this.handleWSError(e),t(e);else{this.state=bo.DISCONNECTED,clearTimeout(d);const i=yield this.handleConnectionError(e,u);t(i)}}))));if(clearTimeout(d),!n)return;const a=n.readable.getReader();this.streamWriter=n.writable.getWriter();const o=yield a.read();if(a.releaseLock(),!o.value)throw ts.internal("no message received as first message");const c=_a(o.value),l=this.validateFirstMessage(c,null!==(r=i.reconnect)&&void 0!==r&&r);if(!l.isValid)return void t(l.error);"join"===(null===(s=c.message)||void 0===s?void 0:s.case)&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(c.message.value));h(n,l.shouldProcessFirstMessage?c:void 0),e(l.response)}catch(e){t(e)}finally{c()}}finally{o()}}))))}()}))}startReadingLoop(e,t){return Cn(this,void 0,void 0,(function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Vs(this.signalLatency));const t=yield e.read(),i=t.done,n=t.value;if(i)break;const r=_a(n);this.handleSignalResponse(r)}}))}close(){return Cn(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([bo.DISCONNECTING||bo.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=bo.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,Vs(250)])}}catch(t){e.log.debug("websocket error while closing",{error:t})}finally{t&&(e.state=bo.DISCONNECTED),n()}}()}))}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Co(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Co(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new hi({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new pi({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Cn(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const r=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new Mi({requestId:r,metadata:e,name:t,attributes:n})}),r}()}))}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 Ii({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new qi({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:A.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Qi({timestamp:A.parse(Date.now()),rtt:A.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new wi({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ri({reason:it.CLIENT_INITIATED,action:Pi.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new ai({pubHandle:e,name:t,encryption:i?mt.GCM:mt.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new ci({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Ti({updates:[new Si({trackSid:e,subscribe:t})]})})}sendRequest(e){return Cn(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=yo.indexOf(e.case)>=0;return kn.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===bo.RECONNECTING)return void t.queuedRequests.push((()=>Cn(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield Vs(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case));const r=new ii({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary().buffer)}catch(e){t.log.error("error sending signal message",{error:e})}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message");let r=!1;if("answer"===n.case){const e=So(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const e=So(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}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(),r=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(n.value):"publishDataTrackResponse"===n.case?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(n.value):"unpublishDataTrackResponse"===n.case?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(n.value):"dataTrackSubscriberHandles"===n.case?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(n.value):this.log.debug("unsupported message",{msgCase:n.case}));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Cn(this,void 0,void 0,(function*(){if(this.state===bo.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=hs.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&hs.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval"),this.pingInterval=hs.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set")}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&hs.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=bo.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,r,s,a;return"join"===(null===(i=e.message)||void 0===i?void 0:i.case)?{isValid:!0,response:e.message.value}:this.state===bo.RECONNECTING&&"leave"!==(null===(n=e.message)||void 0===n?void 0:n.case)?"reconnect"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&"leave"===(null===(s=e.message)||void 0===s?void 0:s.case)?{isValid:!1,error:ts.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:ts.internal("Unexpected first message")}:{isValid:!1,error:ts.internal("did not receive join response, got ".concat(null===(a=e.message)||void 0===a?void 0:a.case," instead"))}}handleConnectionError(e,t){return Cn(this,void 0,void 0,(function*(){try{const i=yield fetch(t);switch(i.status){case 404:const e=yield i.text();return e.includes("requested room does not exist")?ts.notAllowed(e,i.status):ts.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield i.text();return ts.notAllowed(t,i.status)}return e instanceof ts?e:ts.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(e){return e instanceof ts?e:ts.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}}))}}function So(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 Co(e,t){return new ki({sdp:e.sdp,type:e.type,id:t})}class wo{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 Eo{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 i of this._map.entries()){var t=B(i,2);const n=t[0];t[1].expiresAt<e&&this._map.delete(n)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const i of this._map.entries()){var t=B(i,2);const n=t[0],r=t[1];r.expiresAt>=Date.now()&&e(r.value,n,this.asValueMap())}}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const r of i.entries()){var n=B(r,2);const s=n[0],a=n[1];t.push(e(a,s,i))}return t}asValueMap(){const e=new Map;for(const i of this._map.entries()){var t=B(i,2);const n=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(n,r.value)}return e}}var Ro,Po,Io,Mo,Do,Ao={},_o={},Lo={exports:{}};function Oo(){if(Ro)return Lo.exports;Ro=1;var e=Lo.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")}))})),Lo.exports}function xo(){return Po||(Po=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;!function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=Oo(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(r))return i(c,a,r)}})),t.media=s,t};var s=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(_o)),_o}function No(){if(Mo)return Io;Mo=1;var e=Oo(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,r=n.length;return e.replace(t,(function(e){if(i>=r)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 r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?r.push(n[t.name][a]):r.push(n[t.names[s]])}else r.push(n[t.name]);return i.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return Io=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var a=i.outerOrder||r,o=i.innerOrder||s,c=[];return a.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))})),t.media.forEach((function(t){c.push(n("m",e.m[0],t)),o.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))}))})),c.join("\r\n")+"\r\n"},Io}var Uo=function(){if(Do)return Ao;Do=1;var e=xo(),t=No(),i=Oo();return Ao.grammar=i,Ao.write=t,Ao.parse=e.parse,Ao.parseParams=e.parseParams,Ao.parseFmtpConfig=e.parseFmtpConfig,Ao.parsePayloads=e.parsePayloads,Ao.parseRemoteCandidates=e.parseRemoteCandidates,Ao.parseImageAttributes=e.parseImageAttributes,Ao.parseSimulcastStreamList=e.parseSimulcastStreamList,Ao}();const Fo="negotiationStarted",jo="negotiationComplete",Bo="offerAnswered",Vo="rtpVideoPayloadTypes";class qo extends Dn.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=kn,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Ha((e=>Cn(this,void 0,void 0,(function*(){this.emit(Fo);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this.pendingInitialOffer=void 0,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=yn(null!==(i=t.loggerName)&&void 0!==i?i:fn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new d}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 Cn(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 Cn(this,void 0,void 0,(function*(){var i,n;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 r;if("offer"===e.type){let t=function(e){var t;const i=[],n=[],r=Uo.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return r.media.forEach((e=>{var t;const r=Wo(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(s=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===s&&"nack"===e.type)))&&n.push(r),e.fmtp.some((e=>e.payload===s&&(e.config.includes("sprop-stereo=1")&&i.push(r),!0))))})),{stereoMids:i,nackMids:n}}(e),i=t.stereoMids,n=t.nackMids;this.remoteStereoMids=i,this.remoteNackMids=n}else if("answer"===e.type){if(this.pendingInitialOffer&&this._pc){const e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const t=Uo.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{Ho(e)})),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(e,Uo.write(t))}const t=Uo.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{const t=Wo(e.mid);"audio"===e.type&&this.trackBitrates.some((i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;let r=!1;for(const t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),r=!0;break}return r||i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0}))})),r=Uo.write(t)}if(yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,"answer"===e.type&&(this.latestAcknowledgedOfferId=t,this.emit(Bo,t)),this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(jo),e.sdp)){Uo.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Vo,e.rtp)}))}return!0}))}createInitialOffer(){return Cn(this,void 0,void 0,(function*(){var e;const t=yield this.offerLock.lock();try{if("stable"!==this.pc.signalingState)return void this.log.warn("signaling state is not stable, cannot create initial offer",this.logContext);const t=this.latestOfferId+1;this.latestOfferId=t;const i=yield this.pc.createOffer();this.pendingInitialOffer={sdp:i.sdp,type:i.type};const n=Uo.parse(null!==(e=i.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{Ho(e)})),i.sdp=Uo.write(n),{offer:i,offerId:t}}finally{t()}}))}createAndSendOffer(e){return Cn(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||this.pendingInitialOffer)){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return this.renegotiate=!0,void this.log.debug("requesting renegotiation",Object.assign({},this.logContext));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 r=Uo.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(r.media.forEach((e=>{Ho(e),"audio"===e.type?Ko(e,["all"],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(Hs(t.codec)&&!Js()&&this.ensureVideoDDExtensionForSVC(e,r),!Hs(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,Uo.write(r)),this.onOffer(n,this.latestOfferId)}finally{i()}}))}createAndSetAnswer(){return Cn(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=Uo.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Ho(e),"audio"===e.type&&Ko(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Uo.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ss("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 ss("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()}getMaxMessageSize(){var e,t;return null===(t=null===(e=this._pc)||void 0===e?void 0:e.sctp)||void 0===t?void 0:t.maxMessageSize}getConnectedAddress(){return Cn(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 r=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==r?n.get(r):void 0}))}setMungedSDP(e,t,i){return Cn(this,void 0,void 0,(function*(){var n,r;const s=e.sdp;if(t){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,mungedSdp:t,originalSdp:s})),e.sdp=s}}try{i?yield null===(n=this._pc)||void 0===n?void 0:n.setRemoteDescription(e):yield null===(r=this._pc)||void 0===r?void 0:r.setLocalDescription(e)}catch(n){let r="unknown error";n instanceof Error?r=n.message:"string"==typeof n&&(r=n);const a={error:r,sdp:e.sdp};throw t&&t!==s&&(a.mungedSdp=t),!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new as(r)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Bs)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;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:Bs})}}}function Ko(e,t,i){const n=Wo(e.mid);let r=0;e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),r>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some((e=>e.payload===r&&"nack"===e.type))&&e.rtcpFb.push({payload:r,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some((e=>e.payload===r&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Ho(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)}}function Wo(e){return"number"==typeof e?e.toFixed(0):e}const zo="vp8",Go={audioPreset:ys.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ss.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:zo,backupCodec:!0,preConnectBuffer:!1},Jo={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Qo={deviceId:{ideal:"default"},resolution:bs.h720.resolution},Yo={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Sn}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,singlePeerConnection:!0},$o={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Xo;!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"}(Xo||(Xo={}));class Zo{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var n;this.peerConnectionTimeout=$o.peerConnectionTimeout,this.log=kn,this.updateState=()=>{var e,t;const i=this.state,n=this.requiredTransports.map((e=>e.getConnectionState()));n.every((e=>"connected"===e))?this.state=Xo.CONNECTED:n.some((e=>"failed"===e))?this.state=Xo.FAILED:n.some((e=>"connecting"===e))?this.state=Xo.CONNECTING:n.every((e=>"closed"===e))?this.state=Xo.CLOSED:n.some((e=>"closed"===e))?this.state=Xo.CLOSING:n.every((e=>"new"===e))&&(this.state=Xo.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(Xo[i]," to ").concat(Xo[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.log=yn(null!==(n=t.loggerName)&&void 0!==n?n:fn.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired="subscriber-primary"!==e,this.isSubscriberConnectionRequired="subscriber-primary"===e,this.publisher=new qo(i,t),this._mode=e,"publisher-only"!==e&&(this.subscriber=new qo(i,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Zt.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.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Zt.PUBLISHER)},this.publisher.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=Xo.NEW,this.connectionLock=new d,this.remoteOfferLock=new d}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()}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 Cn(this,void 0,void 0,(function*(){var e;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(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()}))}triggerIceRestart(){return Cn(this,void 0,void 0,(function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Cn(this,void 0,void 0,(function*(){var i;t===Zt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return Cn(this,void 0,void 0,(function*(){var i,n,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(i=this.subscriber)||void 0===i?void 0:i.getSignallingState().toString()}));const s=yield this.remoteOfferLock.lock();try{if(!(yield null===(n=this.subscriber)||void 0===n?void 0:n.setRemoteDescription(e,t)))return;return yield null===(r=this.subscriber)||void 0===r?void 0:r.createAndSetAnswer()}finally{s()}}))}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null===(i=this.subscriber)||void 0===i||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Cn(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 Cn(this,void 0,void 0,(function*(){return new jr(((t,i)=>{const n=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>n)return this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),void t();let r=!1;const s=()=>{r||(r=!0,clearTimeout(c),this.publisher.off(Bo,a),e.signal.removeEventListener("abort",o))},a=e=>{e>n&&(s(),t())},o=()=>{s(),i(new as("negotiation aborted"))},c=setTimeout((()=>{s(),i(new as("negotiation timed out"))}),this.peerConnectionTimeout);e.signal.addEventListener("abort",o),this.publisher.on(Bo,a),this.publisher.negotiate((e=>{s(),e instanceof Error?i(e):i(new Error(String(e)))}))}))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find((t=>t.receiver===e));return null==t?void 0:t.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Zt.PUBLISHER||e===Zt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return Cn(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,r)=>Cn(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),hs.clearTimeout(s),r(ts.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const s=hs.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),r(ts.internal("could not establish pc connection"))}),n);for(;this.state!==Xo.CONNECTED;)if(yield Vs(50),null==t?void 0:t.signal.aborted)return void r(ts.cancelled("room connection has been cancelled"));hs.clearTimeout(s),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}const ec="undefined"!=typeof MediaRecorder;const tc=ec?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class ic extends tc{constructor(e,t){if(!ec)throw new Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([e.mediaStreamTrack]),t);const r=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",s),null==n||n.close(),n=void 0},s=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",s),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>Cn(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:()=>{r()}}),this.addEventListener("stop",r),this.addEventListener("error",s)}}class nc extends Us{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.pendingDeviceChange=!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=Ha((()=>Cn(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Cn(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(es.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new d,this.pauseUpstreamLock=new d,this.trackChangeLock=new d,this.trackChangeLock.lock().then((t=>Cn(this,void 0,void 0,(function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})))),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Us.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,i=e.height;return t&&i?{width:t,height:i}: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,i){return Cn(this,void 0,void 0,(function*(){var n;if(e===this._mediaStreamTrack&&!t)return;let r;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{js(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Fs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),r=this.processor.processedTrack}this.sender&&"closed"!==(null===(n=this.sender.transport)||void 0===n?void 0:n.state)&&(yield this.sender.replaceTrack(null!=r?r:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!!i||!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Fs(null!=r?r:e,t)})))}))}waitForDimensions(){return Cn(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===Us.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=qr())||void 0===i?void 0:i.os)&&(yield Vs(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield Vs(50)}throw new ns("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Cn(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===ga(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),ga(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Cn(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===Us.Source.ScreenShare)return;const i=e._mediaStreamTrack.getSettings(),n=i.deviceId,r=i.groupId,s=e.kind===Us.Kind.Audio?"audioinput":"videoinput";return t?no.getInstance().normalizeDeviceId(s,n,r):n}()}))}mute(){return Cn(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Cn(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Cn(this,void 0,void 0,(function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new ns("unable to replace an unpublished track");let i,n;"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor())}finally{i()}return yield this.onSenderTrackSwapped(),this}))}onSenderTrackSwapped(){return Cn(this,void 0,void 0,(function*(){}))}restart(e,t){return Cn(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const i=e,n=i.deviceId,r=i.facingMode,s=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 r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===Us.Kind.Video?a.video=!n&&!r||{deviceId:n,facingMode:r}:a.audio=!n||Object.assign({deviceId:n},s),this.attachedElements.forEach((e=>{js(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===Us.Kind.Video&&(yield o.applyConstraints(s)),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(es.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}}))}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?es.Muted:es.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 Cn(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ys()&&(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 Cn(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(es.UpstreamPaused,this);const t=qr();if("Safari"===(null==t?void 0:t.name)&&ra(t.version,"12.0")<0)throw new is("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 Cn(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(es.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 Cn(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 Cn(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 r=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);const r=document.createElement(t.kind),s={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext,localTrack:t};if(yield e.init(s),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(Fs(t._mediaStreamTrack,r),r.muted=!0,r.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((()=>{r.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=r,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(js(t._mediaStreamTrack,e),Fs(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(es.TrackProcessorUpdate,t.processor)}finally{r()}yield t.onSenderTrackSwapped()}()}))}getProcessor(){return this.processor}stopProcessor(){return Cn(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.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}yield e.onSenderTrackSwapped()}()}))}internalStopProcessor(){return Cn(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(es.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(ec)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 ic(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 rc extends nc{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,r=arguments.length>4?arguments[4]:void 0;super(e,Us.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Cn(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=za(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(es.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(es.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Cn(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===Us.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 Cn(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Us.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!this.pendingDeviceChange||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}restartTrack(e){return Cn(this,void 0,void 0,(function*(){let t;if(e){const i=Es({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e,t){const i=Object.create(null,{restart:{get:()=>super.restart}});return Cn(this,void 0,void 0,(function*(){const n=yield i.restart.call(this,e,t);return this.checkForSilence(),n}))}startMonitor(){$s()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Wa)))}setProcessor(e){return Cn(this,void 0,void 0,(function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Xs()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};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(es.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Cn(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 Cn(this,void 0,void 0,(function*(){const e=yield Rs(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(es.AudioSilenceDetected)),e}))}}const sc=Object.values(bs),ac=Object.values(Ts),oc=Object.values(Ss),cc=[bs.h180,bs.h360],dc=[Ts.h180,Ts.h360],lc=["q","h","f"];function uc(e,t,i,n){var r,s;let a=null==n?void 0:n.videoEncoding;e&&(a=null==n?void 0:n.screenShareEncoding);const o=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!a&&!o&&!c||!t||!i)return[{}];a||(a=function(e,t,i,n){const r=function(e,t,i){if(e)return oc;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return sc;return ac}(e,t,i);let s=r[0].encoding;const a=Math.max(t,i);for(let e=0;e<r.length;e+=1){const t=r[e];if(s=t.encoding,t.width>=a)break}if(n)switch(n){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,i,d),kn.debug("using video encoding",a));const l=a.maxFramerate,u=new ps(t,i,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Hs(d)){const e=new fc(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=qr();if(Qs()||Xs()||"Chrome"===(null==i?void 0:i.name)&&ra(null==i?void 0:i.version,"113")<0){const n="h"==e.suffix?2:3,r=function(e){return e||(e=qr()),"Safari"===(null==e?void 0:e.name)&&ra(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&ra(e.osVersion,"18.3")>0}(i);for(let i=0;i<e.spatial;i+=1)t.push({rid:lc[2-i],maxBitrate:a.maxBitrate/Math.pow(n,i),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,i):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),kn.debug("using svc encoding",{encodings:t}),t}if(!o)return[a];let h,p;if(h=e?null!==(r=gc(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==r?r:pc(e,u):null!==(s=gc(null==n?void 0:n.videoSimulcastLayers))&&void 0!==s?s:pc(e,u),h.length>0){const e=h[0];if(h.length>1)p=B(h,2)[1];const n=Math.max(t,i);if(n>=960&&p)return mc(t,i,[e,p,u],l);if(n>=480)return mc(t,i,[e,u],l)}return mc(t,i,[u])}function hc(e,t,i){var n,r,s,a;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&kn.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const o=e.mediaStreamTrack.getSettings(),c=null!==(n=o.width)&&void 0!==n?n:null===(r=e.dimensions)||void 0===r?void 0:r.width,d=null!==(s=o.height)&&void 0!==s?s:null===(a=e.dimensions)||void 0===a?void 0:a.height;e.source===Us.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1);return uc(e.source===Us.Source.ScreenShare,c,d,i)}function pc(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new ps(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 n=t.width,r=t.height,s=n>r?n/r:r/n;return Math.abs(s-16/9)<Math.abs(s-4/3)?cc:dc}function mc(e,t,i,n){const r=[];if(i.forEach(((i,s)=>{if(s>=lc.length)return;const a=Math.min(e,t),o={rid:lc[s],scaleResolutionDownBy:Math.max(1,a/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(o.maxFramerate=c);const d=qr(),l="Firefox"===(null==d?void 0:d.name)&&"iOS"!==d.os||0===s;i.encoding.priority&&l&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),r.push(o)})),Xs()&&"ios"===ia()){let e;r.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;r.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,kn.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),kn.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return r}function gc(e){if(e)return e.slice().sort(((e,t)=>{const i=e.encoding,n=t.encoding;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 fc{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 vc extends nc{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,Us.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Cn(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(es.CpuConstrained)),this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const r=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=za(t,r)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new d}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!$s())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()}),Wa))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;yield e.pauseUpstream.call(this);try{for(var a,o=!0,c=Pn(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){r=a.value,o=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(null)}}catch(e){i={error:e}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;yield e.resumeUpstream.call(this);try{for(var a,o=!0,c=Pn(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){r=a.value,o=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(e.mediaStreamTrack)}}catch(e){i={error:e}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Cn(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!==Us.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 Cn(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Us.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),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 Cn(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 r={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},s=i.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}})),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=Ns.LOW;i<=Ns.HIGH;i+=1)t.push(new Ui({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Hs(this.codec),t)}restartTrack(e){return Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;let a;if(e){const t=Es({video:e});"boolean"!=typeof t.video&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o,c=!0,d=Pn(this.simulcastCodecs.values());!(t=(o=yield d.next()).done);c=!0){r=o.value,c=!1;const e=r;e.sender&&"closed"!==(null===(s=e.sender.transport)||void 0===s?void 0:s.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}}yield this.onSenderTrackSwapped()}))}onSenderTrackSwapped(){return Cn(this,void 0,void 0,(function*(){yield this.refreshSenderEncodings()}))}refreshSenderEncodings(){return Cn(this,void 0,void 0,(function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let t;try{t=yield this.waitForDimensions()}catch(e){return void this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:e}))}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;const n=uc(this.source===Us.Source.ScreenShare,t.width,t.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,n),this.encodings=n,this.lastEncodedDimensions=t;for(const t of this.simulcastCodecs){var i=B(t,2);const n=i[0],r=i[1];if(!r.sender||"closed"===(null===(e=r.sender.transport)||void 0===e?void 0:e.state))continue;if(!fs(n))continue;const s=hc(this,n,Object.assign({},this.publishOptions));s&&(yield this.applyEncodingsToSender(r.sender,s),r.encodings=s)}}catch(e){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:e}))}finally{t()}}))}applyEncodingsToSender(e,t){return Cn(this,void 0,void 0,(function*(){const i=e.getParameters();i.encodings&&i.encodings.length===t.length&&(i.encodings.forEach(((e,i)=>{if(!1===e.active)return;const n=t[i];void 0!==n.scaleResolutionDownBy&&(e.scaleResolutionDownBy=n.scaleResolutionDownBy),void 0!==n.maxBitrate&&(e.maxBitrate=n.maxBitrate),void 0!==n.maxFramerate&&(e.maxFramerate=n.maxFramerate),void 0!==n.priority&&(e.priority=n.priority,e.networkPriority=n.priority)})),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:i.encodings})),yield e.setParameters(i))}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Cn(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r,s,a,o,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Pn(i.simulcastCodecs.values());!(r=(l=yield h.next()).done);u=!0){o=l.value,u=!1;const e=o;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(e){s={error:e}}finally{try{u||r||!(a=h.return)||(yield a.call(h))}finally{if(s)throw s.error}}}()}))}setDegradationPreference(e){return Cn(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 Cn(this,void 0,void 0,(function*(){var t,i,n,r,s,a,o;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Hs(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Pn(e);!(r=(n=yield i.next()).done);t=!0){o=n.value,t=!1;const e=o;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield kc(t.sender,t.encodings,e.qualities,this.senderLock,Hs(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(Hs(e.codec),e.qualities)}}catch(e){s={error:e}}finally{try{t||r||!(a=i.return)||(yield a.call(i))}finally{if(s)throw s.error}}return c}))}setPublishingLayers(e,t){return Cn(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 kc(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return Cn(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&&Hs(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 Cn(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ys()&&this.isInBackground&&this.source===Us.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function kc(e,t,i,n,r,s,a){return Cn(this,void 0,void 0,(function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),o=n.encodings;if(!o)return;if(o.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:o,senderEncodings:t}));let c=!1;if(!1&&o[0].scalabilityMode);else{if(r){i.some((e=>e.enabled))&&i.forEach((e=>e.enabled=!0))}o.forEach(((e,n)=>{var r;let o=null!==(r=e.rid)&&void 0!==r?r:"";""===o&&(o="q");const d=yc(o),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),a),zs()&&(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=o,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}}))}function yc(e){switch(e){case"f":default:return Ns.HIGH;case"h":return Ns.MEDIUM;case"q":return Ns.LOW}}function bc(e,t,i,n){if(!i)return[new yt({quality:Ns.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,r=new fc(n),s=[],a="h"==r.suffix?1.5:2,o="h"==r.suffix?2:3;for(let n=0;n<r.spatial;n+=1)s.push(new yt({quality:Math.min(Ns.HIGH,r.spatial-1)-n,width:Math.ceil(e/Math.pow(a,n)),height:Math.ceil(t/Math.pow(a,n)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(o,n)):0,ssrc:0}));return s}return i.map((i=>{var n,r,s;const a=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let o=yc(null!==(r=i.rid)&&void 0!==r?r:"");return new yt({quality:o,width:Math.ceil(e/a),height:Math.ceil(t/a),bitrate:null!==(s=i.maxBitrate)&&void 0!==s?s:0,ssrc:0})}))}const Tc="_lossy",Sc="_reliable",Cc="_data_track",wc="leave-reconnect";var Ec,Rc;!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"}(Ec||(Ec={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"}(Rc||(Rc={}));class Pc extends Dn.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=$o.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ec.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=kn,this.reliableDataSequence=1,this.reliableMessageBuffer=new wo,this.reliableReceivedState=new Eo(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new ma,this.handleDataChannel=e=>Cn(this,[e],void 0,(function(e){var t=this;let i=e.channel;return function*(){if(!i)return;let e;if(i.label===Sc)t.reliableDCSub=i,e=t.handleDataMessage;else if(i.label===Tc)t.lossyDCSub=i,e=t.handleDataMessage;else{if(i.label!==Cc)return;t.dataTrackDCSub=i,e=t.handleDataTrackMessage}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label)),i.onmessage=e}()})),this.handleDataMessage=e=>Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;const a=yield this.dataProcessLock.lock();try{let a;if(e.data instanceof ArrayBuffer)a=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",{data:e.data});a=yield e.data.arrayBuffer()}const o=Tt.fromBinary(new Uint8Array(a));if(o.sequence>0&&""!==o.participantSid){const e=this.reliableReceivedState.get(o.participantSid);if(e&&o.sequence<=e)return;this.reliableReceivedState.set(o.participantSid,o.sequence)}if("speaker"===(null===(t=o.value)||void 0===t?void 0:t.case))this.emit(Zr.ActiveSpeakersUpdate,o.value.value.speakers);else if("encryptedPacket"===(null===(i=o.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up");const e=yield null===(n=this.e2eeManager)||void 0===n?void 0:n.handleEncryptedData(o.value.value.encryptedValue,o.value.value.iv,o.participantIdentity,o.value.value.keyIndex),t=wt.fromBinary(e.payload),i=new Tt({value:t.value,participantIdentity:o.participantIdentity,participantSid:o.participantSid});"user"===(null===(r=i.value)||void 0===r?void 0:r.case)&&Ic(i,i.value.value),this.emit(Zr.DataPacketReceived,i,o.value.value.encryptionType)}else"user"===(null===(s=o.value)||void 0===s?void 0:s.case)&&Ic(o,o.value.value),this.emit(Zr.DataPacketReceived,o,mt.NONE)}finally{a()}})),this.handleDataTrackMessage=e=>Cn(this,void 0,void 0,(function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",{data:e.data});t=yield e.data.arrayBuffer()}this.emit("dataTrackPacketReceived",new Uint8Array(t))})),this.handleDataError=e=>{if(this._isClosed)return;const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if("undefined"!=typeof RTCErrorEvent&&e instanceof RTCErrorEvent&&e.error){const i=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(i.message),{error:i,errorDetail:i.errorDetail,sctpCauseCode:i.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleDataChannelClose=e=>()=>{var t;this._isClosed||"connected"!==(null===(t=this.pcManager)||void 0===t?void 0:t.publisher.getConnectionState())||this.log.error("publisher data channel '".concat(Rc[e],"' closed unexpectedly"),this.logContext)},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected")),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.emit(Zr.Disconnected),this.close()},n=Date.now()-this.reconnectStart;let r=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==r?(e===wc&&(r=0),this.log.debug("reconnecting in ".concat(r,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(Zr.TokenRefreshed,this.token),this.reconnectTimeout=hs.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),r)):i(n)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===Ec.Connected&&e();const i=()=>{this.off(Zr.Disconnected,n),e()},n=()=>{this.off(Zr.Restarted,i),t()};this.once(Zr.Restarted,i),this.once(Zr.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{if(e===Rc.RELIABLE){const t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Zr.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.onRtpMapAvailable=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(Zr.RTPVideoMapUpdate,t)},this.handleBrowserOnLine=()=>Cn(this,void 0,void 0,(function*(){if(!this.url)return;(yield fetch(fa(this.url),{method:"HEAD"}).then((e=>e.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===bo.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===bo.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(nt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>Cn(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(fa(this.url),{method:"HEAD"}),Vs(4e3).then((()=>Promise.reject()))])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=yn(null!==(t=e.loggerName)&&void 0!==t?t:fn.Engine,(()=>this.logContext)),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new To(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new d,this.dataProcessLock=new d,this.dcBufferStatus=new Map([[Rc.RELIABLE,!0],[Rc.LOSSY,!0],[Rc.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(Zr.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Zr.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Zr.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Zr.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Zr.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Zr.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Zr.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Zr.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(Zr.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(Zr.Joined,e),this.on(Zr.Closing,(()=>{var e,t;null===(t=(e=this.bufferStatusLowClosingFuture).reject)||void 0===t||t.call(e,new ss("engine closed"))})),this.bufferStatusLowClosingFuture.promise.catch((()=>{}))}get logContext(){var e,t,i,n,r,s;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===(s=null===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===s?void 0:s.identity,participantID:this.participantSid}}join(e,t,i,n){return Cn(this,arguments,void 0,(function(e,t,i,n){var r=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var a,o,c;r._isNewlyCreated=!1,r.url=e,r.token=t,r.signalOpts=i,r.maxJoinAttempts=i.maxRetries;try{r.joinAttempts+=1,r.setupSignalClientCallbacks();const d=!s&&Ia()&&!zs();let l;if(d){r.pcManager||(yield r.configure(),r.applyInitialPublisherLayout());const e=yield null===(a=r.pcManager)||void 0===a?void 0:a.publisher.createInitialOffer();e&&(l=Co(e.offer,e.offerId))}if(null==n?void 0:n.aborted)throw ts.cancelled("Connection aborted");if(!s&&r.shouldFailOnV1Path)throw r.shouldFailOnV1Path=!1,ts.serviceNotFound("Simulated v1 path failure","v0-rtc");const u=yield r.client.join(e,t,i,n,s,l);r._isClosed=!1,r.latestJoinResponse=u,r.participantSid=null===(o=u.participant)||void 0===o?void 0:o.sid,r.subscriberPrimary=u.subscriberPrimary,d?null===(c=r.pcManager)||void 0===c||c.updateConfiguration(r.makeRTCConfiguration(u)):(r.pcManager||(yield r.configure(u,!s),s||r.applyInitialPublisherLayout()),r.subscriberPrimary&&!u.fastPublish||r.negotiate().catch((e=>{r.log.error(e)}))),r.registerOnLineListener(),r.clientConfiguration=u.clientConfiguration,r.emit(Zr.SignalConnected,u);let h=u.serverInfo;return h||(h={version:u.serverVersion,region:u.serverRegion}),r.log.info("connected to Livekit Server ".concat(Object.entries(h).map((e=>{let t=B(e,2),i=t[0],n=t[1];return"".concat(i,": ").concat(n)})).join(", "))),{joinResponse:u,serverInfo:h}}catch(a){if(a instanceof ts)if(a.reason===Jr.ServerUnreachable){if(r.log.warn("Couldn't connect to server, attempt ".concat(r.joinAttempts," of ").concat(r.maxJoinAttempts)),r.joinAttempts<r.maxJoinAttempts)return r.join(e,t,i,n,s)}else if(a.reason===Jr.ServiceNotFound)return r.log.warn("Initial connection failed: ".concat(a.message," – Retrying")),r.pcManager&&(r.pcManager.onStateChange=void 0,yield r.cleanupPeerConnections()),r.join(e,t,i,n,!0);throw a}}()}))}close(){return Cn(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(Zr.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return Cn(this,void 0,void 0,(function*(){var e;const t=e=>{e&&(e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null,e.close())};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0,this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new wo,this.reliableDataSequence=1,this.reliableReceivedState.clear()}))}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return Cn(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new ns("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(ts.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",{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 Cn(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return Cn(this,void 0,void 0,(function*(){var i;if(!this.pcManager||this.pcManager.currentState===Xo.NEW){if(e){this.participantSid=null===(i=e.participant)||void 0===i?void 0:i.sid;const n=this.makeRTCConfiguration(e);this.pcManager=new Zo(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,n)}else{const e=this.makeRTCConfiguration();this.pcManager=new Zo("publisher-only",this.loggerOptions,e)}this.emit(Zr.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=(e,t,i)=>Cn(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(e)),["closed","disconnected","failed"].includes(t)&&(this.publisherConnectionPromise=void 0),e===Xo.CONNECTED){const e=this.pcState===Ec.New;this.pcState=Ec.Connected,e&&this.emit(Zr.Connected,this.latestJoinResponse)}else e===Xo.FAILED&&(this.pcState!==Ec.Connected&&this.pcState!==Ec.Reconnecting||(this.pcState=Ec.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?nt.RR_SUBSCRIBER_FAILED:nt.RR_PUBLISHER_FAILED)));const n=this.client.isDisconnected||this.client.currentState===bo.RECONNECTING,r=[Xo.FAILED,Xo.CLOSING,Xo.CLOSED].includes(e);n&&r&&!this._isClosed&&this.emit(Zr.Offline)})),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(Zr.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}}))}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>Cn(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i}),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>Cn(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{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),{cid:e.cid});const i=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Zr.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Zr.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(Zr.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Zr.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Zr.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(Zr.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(Zr.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(Zr.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(Zr.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",nt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(null==e?void 0:e.action,")"),{reason:null==e?void 0:e.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(Zr.ServerRegionsReported,e.regions)),e.action){case Pi.DISCONNECT:this.emit(Zr.Disconnected,null==e?void 0:e.reason),this.close();break;case Pi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wc);break;case Pi.RESUME:this.handleDisconnect(wc)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!Va())&&Ba()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(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===tt.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(){this.createDataChannels(),Xs()||this.addMediaSections(3,3)}addMediaSections(e,t){var i,n;const r={direction:"recvonly"};for(let t=0;t<e;t++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("audio",r);for(let e=0;e<t;e++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("video",r)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null,this.lossyDC.onclose=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null,this.reliableDC.onclose=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null,this.dataTrackDC.onclose=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Tc,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Sc,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(Cc,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.onclose=this.handleDataChannelClose(Rc.LOSSY),this.reliableDC.onclose=this.handleDataChannelClose(Rc.RELIABLE),this.dataTrackDC.onclose=this.handleDataChannelClose(Rc.DATA_TRACK_LOSSY),this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Rc.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Rc.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Rc.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval((()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Rc.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,8192),262144)}}),1e3))}createSender(e,t,i){return Cn(this,void 0,void 0,(function*(){let n;if(qs())n=yield this.createTransceiverRTCRtpSender(e,t,i);else{if(!Ks())throw new ss("Required webRTC APIs not supported on this device");this.log.warn("using add-track fallback"),n=yield this.createRTCRtpSender(e.mediaStreamTrack)}return this.setupFrameMetadataSender(n,t),n}))}createSimulcastSender(e,t,i,n){return Cn(this,void 0,void 0,(function*(){let r;if(qs())r=yield this.createSimulcastTransceiverSender(e,t,i,n);else{if(!Ks())throw new ss("Cannot stream on this device");this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack)}return r&&this.setupFrameMetadataSender(r,i),r}))}get frameMetadataWorker(){var e,t;return null===(t=null!==(e=this.options.frameMetadata)&&void 0!==e?e:this.options.packetTrailer)||void 0===t?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n,r;const s=this.frameMetadataWorker;if(!s||(null===(i=this.signalOpts)||void 0===i?void 0:i.e2eeEnabled))return;const a=null!==(n=t.frameMetadata)&&void 0!==n?n:t.packetTrailer,o=Ka(a);if(Va())return void(o&&(e.transform=new RTCRtpScriptTransform(s,{kind:"encode",packetTrailer:a})));if(!qa(null!==(r=this.options.frameMetadata)&&void 0!==r?r:this.options.packetTrailer)||!("createEncodedStreams"in e))return void(o&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext));const c=e.createEncodedStreams(),d=c.readable,l=c.writable;o?s.postMessage({kind:"encode",data:{readableStream:d,writableStream:l,packetTrailer:a}},[d,l]):d.pipeTo(l)}createTransceiverRTCRtpSender(e,t,i){return Cn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ss("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Sa(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:n};i&&(r.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return Cn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ss("publisher is closed");const r={direction:"sendonly"};n&&(r.sendEncodings=n);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,s.sender),s.sender}))}createRTCRtpSender(e){return Cn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ss("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return Cn(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)this.log.warn("already attempting reconnect, returning early");else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==tt.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:Xo.NEW)!==Xo.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 ss?(this.log.debug("received unrecoverable error",{error:e}),t=!1):e instanceof us||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",nt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(Zr.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",{error:e})}return null}restartConnection(e){return Cn(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new ss("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(Zr.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"),new us;i=(yield this.join(null!=e?e:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(e){if(e instanceof ts&&e.reason===Jr.NotAllowed)throw new ss("could not reconnect, token might be expired");throw new us}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Zr.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==bo.CONNECTED)throw new us("Signal connection got severed during reconnect");null===(t=this.regionStrategy)||void 0===t||t.resetAttempts(),this.emit(Zr.Restarted)}catch(e){const t=yield null===(i=this.regionStrategy)||void 0===i?void 0:i.getNextUrl();if(t)return void(yield this.restartConnection(t));throw null===(n=this.regionStrategy)||void 0===n||n.resetAttempts(),e}}))}resumeConnection(e){return Cn(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new ss("could not reconnect, url or token not saved");if(!this.pcManager)throw new ss("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(Zr.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,{error:e})),e instanceof ts&&e.reason===Jr.NotAllowed)throw new ss("could not reconnect, token might be expired");if(e instanceof ts&&e.reason===Jr.LeaveRequest)throw e;throw new us(t)}if(this.emit(Zr.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");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==bo.CONNECTED)throw new us("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(Zr.Resumed)}))}waitForPCInitialConnection(e,t){return Cn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ss("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Cn(this,void 0,void 0,(function*(){this.pcState=Ec.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Vs(2e3),!this.pcManager)throw new ss("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ec.Connected}catch(e){throw this.pcState=Ec.Disconnected,ts.internal("could not establish PC connection, ".concat(e.message))}}))}publishRpcAck(e,t){return Cn(this,void 0,void 0,(function*(){const i=new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcAck",value:new Lt({requestId:t})}});yield this.sendDataPacket(i,Rc.RELIABLE)}))}sendDataPacket(e,t){return Cn(this,void 0,void 0,(function*(){var i,n;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=function(e){var t,i,n,r,s;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"speaker"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"transcription"!==(null===(r=e.value)||void 0===r?void 0:r.case)&&"encryptedPacket"!==(null===(s=e.value)||void 0===s?void 0:s.case))return new wt({value:e.value})}(e);if(t){const i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Ct({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===Rc.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const r=e.toBinary(),s=Math.min(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.getMaxPublisherMessageSize())&&void 0!==n?n:64e3,64e3);if(void 0!==s&&0!==s&&r.byteLength>s)throw new os("cannot publish data packet larger than ".concat(s," bytes (got ").concat(r.byteLength,")"));switch(t){case Rc.LOSSY:case Rc.DATA_TRACK_LOSSY:return this.sendLossyBytes(r,t);case Rc.RELIABLE:const i=this.dataChannelForKind(t);if(i){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:r,sequence:e.sequence}),this.attemptingReconnect)return;i.send(r)}this.updateAndEmitDCBufferStatus(t)}}))}sendLossyBytes(e,t){return Cn(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"drop";return function*(){yield i.ensurePublisherConnected(t);const r=i.dataChannelForKind(t);if(r){if(!i.isBufferStatusLow(t))switch(n){case"wait":yield i.waitForBufferStatusLow(t);break;case"drop":return i.lossyDataDropCount+=1,void(i.lossyDataDropCount%100==0&&i.log.warn("dropping lossy data channel messages, total dropped: ".concat(i.lossyDataDropCount)))}if(i.lossyDataStatCurrentBytes+=e.byteLength,i.attemptingReconnect)return;r.send(e)}i.updateAndEmitDCBufferStatus(t)}()}))}resendReliableMessagesForResume(e){return Cn(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(Rc.RELIABLE);const t=this.dataChannelForKind(Rc.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach((e=>{t.send(e.data)}))),this.updateAndEmitDCBufferStatus(Rc.RELIABLE)}))}waitForBufferStatusLow(e){return Cn(this,void 0,void 0,(function*(){return new jr(((t,i)=>Cn(this,void 0,void 0,(function*(){if(this.isClosed&&i(new ss("engine closed")),this.isBufferStatusLow(e))t();else{const n=this.dataChannelForKind(e);if(!n)return void i(new ss("DataChannel not found, kind: ".concat(e)));this.bufferStatusLowClosingFuture.promise.catch((e=>i(e))),n.addEventListener("bufferedamountlow",(()=>t()),{once:!0})}}))))}))}ensureDataTransportConnected(e){return Cn(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 ss("PC manager is closed");const r=i?t.pcManager.subscriber:t.pcManager.publisher,s=i?"Subscriber":"Publisher";if(!r)throw ts.internal("".concat(s," connection not set"));let a=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),a=!0),a||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(a=!0),a&&t.negotiate().catch((e=>{t.log.error(e)}));const o=t.dataChannelForKind(e,i);if("open"===(null==o?void 0:o.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(r.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield Vs(50)}throw ts.internal("could not establish ".concat(s," connection, state: ").concat(r.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return Cn(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){if(!this.pcManager)return!1;return!![Xo.CONNECTING,Xo.CONNECTED].includes(this.pcManager.currentState)&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Cn(this,void 0,void 0,(function*(){return new jr(((e,t)=>Cn(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new as("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.dataTrackDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new as("cannot negotiate on closed engine")),this.on(Zr.Closing,n),this.on(Zr.Restarting,n),this.pcManager.publisher.off(Vo,this.onRtpMapAvailable),this.pcManager.publisher.once(Vo,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),e()}catch(n){if(i.signal.aborted)return void e();n instanceof as&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",nt.RR_UNKNOWN),n instanceof Error?t(n):t(new Error(String(n)))}finally{this.off(Zr.Closing,n),this.off(Zr.Restarting,n)}}))))}))}dataChannelForKind(e,t){switch(e){case Rc.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case Rc.LOSSY:return t?this.lossyDCSub:this.lossyDC;case Rc.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,i){var n,r,s,a;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup");const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getRemoteDescription(),l=null===(r=this.pcManager.subscriber)||void 0===r?void 0:r.getLocalDescription(),u=null===(a=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===a||a,h=new Array,p=new Array;e.forEach((e=>{e.isDesired!==u&&h.push(e.trackSid),e.isEnabled||p.push(e.trackSid)})),this.client.sendSyncState(new Wi({answer:"publisher-only"===this.pcManager.mode?c?Co({sdp:c.sdp,type:c.type}):void 0:l?Co({sdp:l.sdp,type:l.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?Co({sdp:o.sdp,type:o.type}):void 0:d?Co({sdp:d.sdp,type:d.type}):void 0,subscription:new bi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:As(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new zi({publisherSid:t,lastSeq:e}))),publishDataTracks:i.map((e=>new oi({info:go.toProtobuf(e)})))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Gi({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(Rc.LOSSY),Zt.PUBLISHER),t(this.dataChannelForKind(Rc.RELIABLE),Zt.PUBLISHER),t(this.dataChannelForKind(Rc.LOSSY,!0),Zt.SUBSCRIBER),t(this.dataChannelForKind(Rc.RELIABLE,!0),Zt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&hs.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){$s()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){$s()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(i){const e=Object.entries(this.midToTrackId).find((e=>B(e,1)[0]===i));if(e)return e[1]}}}function Ic(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}const Mc=5e3;class Dc{static fetchRegionSettings(e,t,i){return Cn(this,void 0,void 0,(function*(){const n=yield Dc.fetchLock.lock();try{const n=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){const e=function(e){var t;const i=e.get("Cache-Control");if(i){const e=null===(t=i.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers),t=e?1e3*e:Mc;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===n.status?ts.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):ts.internal("Could not fetch region settings: ".concat(n.statusText))}catch(e){throw e instanceof ts?e:(null==i?void 0:i.aborted)?ts.cancelled("Region fetching was aborted"):ts.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{n()}}))}static scheduleRefetch(e,t,i){return Cn(this,void 0,void 0,(function*(){const n=Dc.settingsTimeouts.get(e.hostname);clearTimeout(n),Dc.settingsTimeouts.set(e.hostname,setTimeout((()=>Cn(this,void 0,void 0,(function*(){try{const i=yield Dc.fetchRegionSettings(e,t);Dc.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof ts&&n.reason===Jr.NotAllowed)return void kn.debug("token is not valid, cancelling auto region refresh");kn.debug("auto refetching of region settings failed",{error:n}),Dc.scheduleRefetch(e,t,i)}}))),i))}))}static updateCachedRegionSettings(e,t,i){Dc.cache.set(e.hostname,i),Dc.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=Dc.settingsTimeouts.get(e);t&&(clearTimeout(t),Dc.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Dc.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout((()=>{const t=Dc.connectionTrackers.get(e);t&&0===t.connectionCount&&(kn.debug("stopping region refetch after disconnect delay",{hostname:e}),Dc.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(e){const t=Dc.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Dc.connectionTrackers.get(e);t||(t={connectionCount:0},Dc.connectionTrackers.set(e,t)),t.connectionCount++,Dc.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Dc.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&Dc.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const i=this.getServerUrl(),n=Dc.cache.get(i.hostname);Dc.scheduleRefetch(this.serverUrl,this.token,null!==(t=null==n?void 0:n.maxAgeInMs)&&void 0!==t?t:Mc)}isCloud(){return Zs(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Cn(this,void 0,void 0,(function*(){return Dc.fetchRegionSettings(this.serverUrl,this.token,e)}))}getNextBestRegionUrl(e){return Cn(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Dc.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Dc.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(i.length>0){const e=i[0];return this.attemptedRegions.push(e),kn.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Dc.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Dc.cache=new Map,Dc.settingsTimeouts=new Map,Dc.connectionTrackers=new Map,Dc.fetchLock=new d;class Ac{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new ls("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Qr.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new ls("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Qr.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class _c extends Ac{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();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();e.closed.catch((()=>{}));const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>Cn(this,void 0,void 0,(function*(){try{const t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;const i=yield new Promise(((i,n)=>{if(t){const r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),e.read().then(i,n).finally((()=>{t.removeEventListener("abort",r)}))}else e.read().then(i,n)}));return i.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(i.value),{done:!1,value:i.value.content})}catch(e){throw t(),e}})),return(){return Cn(this,void 0,void 0,(function*(){return t(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Cn(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,s;let a=new Set;const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Pn(o);!(i=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;a.add(e)}}catch(e){n={error:e}}finally{try{d||i||!(r=l.return)||(yield r.call(l))}finally{if(n)throw n.error}}return Array.from(a)}()}))}}class Lc extends Ac{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=ka(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch((()=>{}));const t=new TextDecoder("utf-8",{fatal:!0}),i=this.signal,n=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>Cn(this,void 0,void 0,(function*(){try{if(null==i?void 0:i.aborted)throw i.reason;const n=yield new Promise(((t,n)=>{if(i){const r=()=>n(i.reason);i.addEventListener("abort",r,{once:!0}),e.read().then(t,n).finally((()=>{i.removeEventListener("abort",r)}))}else e.read().then(t,n)}));if(n.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(n.value);try{e=t.decode(n.value.content)}catch(e){throw new ls("Cannot decode datastream chunk ".concat(n.value.chunkIndex," as text: ").concat(e),Qr.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw n(),e}})),return(){return Cn(this,void 0,void 0,(function*(){return n(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Cn(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,s;let a="";const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Pn(o);!(i=(c=yield l.next()).done);d=!0){s=c.value,d=!1;a+=s}}catch(e){n={error:e}}finally{try{d||i||!(r=l.return)||(yield r.call(l))}finally{if(n)throw n.error}}return a}()}))}}class Oc{constructor(){this.log=kn,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const e=t.packet,i=t.encryptionType;this.handleDataStreamPacket(e,i)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new ls('A text stream handler for topic "'.concat(e,'" has already been set.'),Qr.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new ls('A byte stream handler for topic "'.concat(e,'" has already been set.'),Qr.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.entries()).filter((t=>t[1].sendingParticipantIdentity===e)),i=Array.from(this.byteStreamControllers.entries()).filter((t=>t[1].sendingParticipantIdentity===e));if(t.length>0||i.length>0){const s=new ls("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Qr.AbnormalEnd);for(const e of i){var n=B(e,2);const t=n[0];n[1].controller.error(s),this.byteStreamControllers.delete(t)}for(const e of t){var r=B(e,2);const t=r[0];r[1].controller.error(s),this.textStreamControllers.delete(t)}}}handleDataStreamPacket(e,t){if(this.isConnected)switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}else this.bufferedPackets.push({packet:e,encryptionType:t})}handleStreamHeader(e,t,i){var n;if("byteHeader"===e.contentHeader.case){const r=this.byteStreamHandlers.get(e.topic);if(!r)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const a={id:e.streamId,name:null!==(n=e.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ka(e.timestamp),attributes:e.attributes,encryptionType:i},o=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(e.streamId))throw new ls("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Qr.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new _c(a,o,ka(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const n=this.textStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let r;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,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},a=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(e.streamId))throw new ls("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Qr.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now(),sendingParticipantIdentity:t})}});n(new Lc(s,a,ka(e.totalLength)),{identity:t})}}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new ls("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Qr.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new ls("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),Qr.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new ls("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Qr.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new ls("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),Qr.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class xc{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 Cn(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 Nc extends xc{}class Uc extends xc{}class Fc{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Cn(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),r=(new TextEncoder).encode(e).byteLength,s=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),a=new Array(s?s.length+1:1).fill(0),o=(e,i)=>{var n;a[i]=e;const r=a.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,r)},c=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:s,attributes:null==t?void 0:t.attributes});return yield c.write(e),o(1,0),yield c.close(),(null==t?void 0:t.attachments)&&s&&(yield Promise.all(t.attachments.map(((e,i)=>Cn(this,void 0,void 0,(function*(){return this._sendFile(s[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,i+1)}})})))))),c.info}))}streamText(e){return Cn(this,void 0,void 0,(function*(){var t,i,n;const r=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:r,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,encryptionType:(null===(n=this.engine.e2eeManager)||void 0===n?void 0:n.isDataChannelEncryptionEnabled)?mt.GCM:mt.NONE,attachedStreamIds:null==e?void 0:e.attachedStreamIds},a=new Qt({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:ya(s.timestamp),totalLength:ya(s.size),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Gt({version:null==e?void 0:e.version,attachedStreamIds:s.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?zt.UPDATE:zt.CREATE})}}),o=null==e?void 0:e.destinationIdentities,c=new Tt({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,Rc.RELIABLE);let d=0;const l=this.engine,u=new WritableStream({write(e){return Cn(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)){const e=new Yt({content:t,streamId:r,chunkIndex:ya(d)}),i=new Tt({destinationIdentities:o,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(i,Rc.RELIABLE),d+=1}}))},close(){return Cn(this,void 0,void 0,(function*(){const e=new $t({streamId:r}),t=new Tt({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield l.sendDataPacket(t,Rc.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let h=()=>Cn(this,void 0,void 0,(function*(){yield p.close()}));l.once(Zr.Closing,h);const p=new Nc(u,s,(()=>this.engine.off(Zr.Closing,h)));return p}))}sendFile(e,t){return Cn(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return Cn(this,void 0,void 0,(function*(){var n;const r=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}),s=t.stream().getReader();for(;;){const e=yield s.read(),t=e.done,i=e.value;if(t)break;yield r.write(i)}return yield r.close(),r.info}))}streamBytes(e){return Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),o=null==e?void 0:e.destinationIdentities,c={id:a,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(r=null==e?void 0:e.name)&&void 0!==r?r:"unknown",encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?mt.GCM:mt.NONE},l=new Qt({totalLength:ya(c.size),mimeType:c.mimeType,streamId:a,topic:c.topic,timestamp:ya(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Jt({name:c.name})}}),u=new Tt({destinationIdentities:o,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,Rc.RELIABLE);let h=0;const p=new d,m=this.engine,g=this.log,f=new WritableStream({write(e){return Cn(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),n=new Tt({destinationIdentities:o,value:{case:"streamChunk",value:new Yt({content:t,streamId:a,chunkIndex:ya(h)})}});yield m.sendDataPacket(n,Rc.RELIABLE),h+=1,i+=t.byteLength}}finally{t()}}))},close(){return Cn(this,void 0,void 0,(function*(){const e=new $t({streamId:a}),t=new Tt({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,Rc.RELIABLE)}))},abort(e){g.error("Sink error:",e)}});return new Uc(f,c)}))}}function jc(e){if(0===e.length){return(new AbortController).signal}if(1===e.length)return e[0];for(const t of e)if(t.aborted)return t;const t=new AbortController,i=Array(e.length);return e.forEach(((e,n)=>{const r=()=>{t.abort(e.reason),(()=>{for(const e of i)e()})()};e.addEventListener("abort",r),i[n]=()=>e.removeEventListener("abort",r)})),t.signal}function Bc(e){const t=new AbortController;return setTimeout((()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))}),e),t.signal}var Vc,qc,Kc;!function(e){e[e.TooShort=0]="TooShort",e[e.HeaderOverrun=1]="HeaderOverrun",e[e.MissingExtWords=2]="MissingExtWords",e[e.UnsupportedVersion=3]="UnsupportedVersion",e[e.InvalidHandle=4]="InvalidHandle",e[e.MalformedExt=5]="MalformedExt"}(Vc||(Vc={}));class Hc extends Gr{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Vc[t]}static tooShort(){return new Hc("Too short to contain a valid header",Vc.TooShort)}static headerOverrun(){return new Hc("Header exceeds total packet length",Vc.HeaderOverrun)}static missingExtWords(){return new Hc("Extension word indicator is missing",Vc.MissingExtWords)}static unsupportedVersion(e){return new Hc("Unsupported version ".concat(e),Vc.UnsupportedVersion)}static invalidHandle(e){return new Hc("invalid track handle: ".concat(e.message),Vc.InvalidHandle,{cause:e})}static malformedExt(e){return new Hc("Extension with tag ".concat(e," is malformed"),Vc.MalformedExt)}}!function(e){e[e.TooSmallForHeader=0]="TooSmallForHeader",e[e.TooSmallForPayload=1]="TooSmallForPayload"}(qc||(qc={}));class Wc extends Gr{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=qc[t]}static tooSmallForHeader(){return new Wc("Buffer cannot fit header",qc.TooSmallForHeader)}static tooSmallForPayload(){return new Wc("Buffer cannot fit payload",qc.TooSmallForPayload)}}class zc{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),n=this.toBinaryInto(i);if(e!==n)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(n," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}!function(e){e[e.UserTimestamp=2]="UserTimestamp",e[e.E2ee=1]="E2ee"}(Kc||(Kc={}));class Gc extends zc{}class Jc extends Gc{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+Jc.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Jc.tag),t+=1,e.setUint8(t,Jc.lengthBytes),t+=1,e.setBigUint64(t,this.timestamp),t+=8;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:Jc.tag,lengthBytes:Jc.lengthBytes,timestamp:this.timestamp}}}Jc.tag=Kc.UserTimestamp,Jc.lengthBytes=8;class Qc extends Gc{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+Qc.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Qc.tag),t+=1,e.setUint8(t,Qc.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let i=0;i<this.iv.length;i+=1)e.setUint8(t,this.iv[i]),t+=1;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:Qc.tag,lengthBytes:Qc.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}Qc.tag=Kc.E2ee,Qc.lengthBytes=13;class Yc extends zc{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){t+=this.e2ee.toBinaryInto(e)}if(this.userTimestamp){t+=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t))}const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){const t=lo(e);let i,n,r=0;for(;t.byteLength-r>=2;){const e=t.getUint8(r);r+=1;const s=t.getUint8(r);if(r+=1,0!==e)switch(e){case Kc.UserTimestamp:if(t.byteLength-r<Jc.lengthBytes)throw Hc.malformedExt(e);i=new Jc(t.getBigUint64(r)),r+=s;break;case Kc.E2ee:if(t.byteLength-r<Qc.lengthBytes)throw Hc.malformedExt(e);const a=t.getUint8(r),o=new Uint8Array(12);for(let e=0;e<o.length;e+=1){let i=r;i+=1,i+=1*e,o[e]=t.getUint8(i)}n=new Qc(a,o),r+=s;break;default:if(t.byteLength-r<s)throw Hc.malformedExt(e);r+=s}}return[new Yc({userTimestamp:i,e2ee:n}),t.byteLength]}toJSON(){var e,t,i,n;return{userTimestamp:null!==(t=null===(e=this.userTimestamp)||void 0===e?void 0:e.toJSON())&&void 0!==t?t:null,e2ee:null!==(n=null===(i=this.e2ee)||void 0===i?void 0:i.toJSON())&&void 0!==n?n:null}}}const $c={from:e=>({payload:e.payload,extensions:new Yc({userTimestamp:e.userTimestamp?new Jc(e.userTimestamp):void 0})}),lossyIntoFrame(e){var t;return{payload:e.payload,userTimestamp:null===(t=e.extensions.userTimestamp)||void 0===t?void 0:t.timestamp}}},Xc=Symbol.for("lk.track"),Zc=Symbol.for("lk.data-track");class ed{constructor(e,t,i){this.trackSymbol=Xc,this.isLocal=!1,this.typeSymbol=Zc,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{const t=B(this.manager.openSubscriptionStream(this.info.sid,null==e?void 0:e.signal,null==e?void 0:e.bufferSize),2),i=t[0];return t[1].catch((()=>{})),i}catch(e){throw e}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class td extends zc{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=null!==(t=e.extensions)&&void 0!==t?t:new Yc}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((2+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-2-e}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,i=e.paddingLengthBytes;let n=12;return t>0&&(n+=2+t+i),n}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Wc.tooSmallForHeader();let t,i=0;switch(this.marker){case id.Inter:t=0;break;case id.Final:t=1;break;case id.Start:t=2;break;case id.Single:t=3}i|=t<<3;const n=this.extensionsMetrics(),r=n.lengthBytes,s=n.lengthWords,a=n.paddingLengthBytes;r>0&&(i|=4);let o=0;if(e.setUint8(o,i),o+=1,e.setUint8(o,0),o+=1,e.setUint16(o,this.trackHandle),o+=2,e.setUint16(o,this.sequence.value),o+=2,e.setUint16(o,this.frameNumber.value),o+=2,e.setUint32(o,this.timestamp.asTicks()),o+=4,r>0){const t=s-1;e.setUint16(o,t),o+=2;o+=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));for(let t=0;t<a;t+=1)e.setUint8(o,0),o+=1}const c=this.toBinaryLengthBytes();if(o!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(o," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){const t=lo(e);if(t.byteLength<12)throw Hc.tooShort();let i=0;const n=t.getUint8(i);i+=1;const r=n>>5&7;if(r>0)throw Hc.unsupportedVersion(r);let s;switch(n>>3&3){case 2:s=id.Start;break;case 1:s=id.Final;break;case 3:s=id.Single;break;default:s=id.Inter}const a=(n>>2&1)>0;let o;i+=1;try{o=po.fromNumber(t.getUint16(i))}catch(e){throw e instanceof ho&&(e.isReason(uo.Reserved)||e.isReason(uo.TooLarge))?Hc.invalidHandle(e):e}i+=2;const c=ao.u16(t.getUint16(i));i+=2;const d=ao.u16(t.getUint16(i));i+=2;const l=oo.fromRtpTicks(t.getUint32(i));i+=4;let u=new Yc;if(a){if(t.byteLength-i<2)throw Hc.missingExtWords();let e=t.getUint16(i);i+=2;let n=4*(e+1)-2;if(i+n>t.byteLength)throw Hc.headerOverrun();let r=new DataView(t.buffer,t.byteOffset+i,n);const s=B(Yc.fromBinary(r),2);u=s[0],i+=s[1]}return[new td({marker:s,trackHandle:o,sequence:c,frameNumber:d,timestamp:l,extensions:u}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var id;!function(e){e[e.Start=0]="Start",e[e.Inter=1]="Inter",e[e.Final=2]="Final",e[e.Single=3]="Single"}(id||(id={}));class nd extends zc{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;if(t+=this.header.toBinaryInto(e),e.byteLength-t<this.payload.byteLength)throw Wc.tooSmallForPayload();for(let i=0;i<this.payload.length;i+=1)e.setUint8(t,this.payload[i]),t+=1;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return i}static fromBinary(e){const t=lo(e),i=B(td.fromBinary(t),2),n=i[0],r=i[1],s=t.buffer.slice(t.byteOffset+r,t.byteOffset+t.byteLength);return[new nd(n,new Uint8Array(s)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const rd=yn(fn.DataTracks);class sd extends Gr{constructor(e,t,i,n){super(19,"Frame ".concat(i," dropped: ").concat(e),n),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=ad[t],this.frameNumber=i}static interrupted(e,t){return new sd("Interrupted by the start of a new frame ".concat(t),ad.Interrupted,e)}static unknownFrame(e){return new sd("Initial packet was never received.",ad.UnknownFrame,e)}static bufferFull(e){return new sd("Reorder buffer is full.",ad.BufferFull,e)}static incomplete(e,t,i){return new sd("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),ad.Incomplete,e)}}var ad,od;!function(e){e[e.Interrupted=0]="Interrupted",e[e.UnknownFrame=1]="UnknownFrame",e[e.BufferFull=2]="BufferFull",e[e.Incomplete=3]="Incomplete"}(ad||(ad={}));class cd{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case id.Single:return this.frameFromSingle(e,t);case id.Start:return this.beginPartial(e,t);case id.Inter:case id.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==id.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const n=null!==(i=null==t?void 0:t.maxPartialFrames)&&void 0!==i?i:1;if(this.partials.size>=n){const i=this.peekOldestPartialFrameNumber();if("number"!=typeof i)throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(i),null==t?void 0:t.throwOnInterruption)throw sd.interrupted(i,e.header.frameNumber.value);rd.warn("Data track frame ".concat(i," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var i;if(e.header.marker!==id.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const n=e.header.sequence,r=e.header.frameNumber.value,s={startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},a=null!==(i=null==t?void 0:t.maxPartialFrames)&&void 0!==i?i:1;for(;this.partials.size>=a;){const e=this.peekOldestPartialFrameNumber();if("number"!=typeof e)break;if(this.partials.delete(e),null==t?void 0:t.throwOnInterruption)throw sd.interrupted(e,r);rd.warn("Data track partials full (max ".concat(a,"), evicted oldest frame ").concat(e," to make room for new frame ").concat(r,"."))}return this.partials.set(r,s),null}pushToPartial(e){if(e.header.marker!==id.Inter&&e.header.marker!==id.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),sd.unknownFrame(t);if(i.payloads.size>=cd.MAX_BUFFER_PACKETS)throw this.partials.delete(t),sd.bufferFull(t);return i.payloads.has(e.header.sequence.value)&&rd.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),i.payloads.set(e.header.sequence.value,e.payload),e.header.marker===id.Final?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){const n=t.payloads.size;let r=0;for(const e of t.payloads.values())r+=e.length;const s=new Uint8Array(r);let a=t.startSequence.clone(),o=0;for(;;){const n=t.payloads.get(a.value);if(!n)break;t.payloads.delete(a.value);const r=s.length-o;if(n.length>r)throw new Error("Depacketizer.finalize: Expected at least ".concat(n.length," more bytes left in the payload buffer, only got ").concat(r," bytes."));if(s.set(n,o),o+=n.length,a.value==i)return this.partials.delete(e),{payload:s,extensions:t.extensions};a.increment()}throw this.partials.delete(e),sd.incomplete(e,n,i-t.startSequence.value+1)}}cd.MAX_BUFFER_PACKETS=128,function(e){e[e.Unpublished=0]="Unpublished",e[e.Timeout=1]="Timeout",e[e.Disconnected=2]="Disconnected",e[e.Cancelled=4]="Cancelled"}(od||(od={}));class dd extends Gr{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=od[t]}static unpublished(){return new dd("The track has been unpublished and is no longer available",od.Unpublished)}static timeout(){return new dd("Request to subscribe to data track timed-out",od.Timeout)}static disconnected(){return new dd("Cannot subscribe to data track when disconnected",od.Disconnected)}static cancelled(){return new dd("Subscription to data track cancelled by caller",od.Cancelled)}}const ld=yn(fn.DataTracks);class ud{constructor(e){var t,i;const n=null!==e.e2eeManager;if(e.info.usesE2ee!==n)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const r=new cd;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=null!==(t=e.e2eeManager)&&void 0!==t?t:null,this.depacketizer=r,this.options=null!==(i=e.pipelineOptions)&&void 0!==i?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return Cn(this,void 0,void 0,(function*(){const t=this.depacketize(e);if(!t)return null;const i=yield this.decryptIfNeeded(t);return i||null}))}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(e){return ld.warn("Data frame depacketize error: ".concat(e)),null}return t}decryptIfNeeded(e){return Cn(this,void 0,void 0,(function*(){var t,i;const n=this.e2eeManager;if(!n)return e;const r=null!==(i=null===(t=e.extensions)||void 0===t?void 0:t.e2ee)&&void 0!==i?i:null;if(!r)return ld.error("Missing E2EE meta"),null;let s;try{s=yield n.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(e){return ld.error("Error decrypting packet: ".concat(e)),null}return e.payload=s.payload,e}))}}const hd=yn(fn.DataTracks);class pd extends Dn.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.subscription.type&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const i=this.descriptors.get(e);i?(i.pipelineOptions=t,"active"===i.subscription.type&&i.subscription.pipeline.setOptions(t)):hd.warn("Unknown track ".concat(e,", cannot set pipeline options."))}openSubscriptionStream(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16,n=null;const r=new ma,s=()=>{null==t||t.removeEventListener("abort",o)},a=()=>{if(s(),!n)return void hd.warn("ReadableStream subscribed to ".concat(e," was not started."));const t=this.descriptors.get(e);t?"active"===t.subscription.type?(t.subscription.streamControllers.delete(n),0===t.subscription.streamControllers.size&&this.unSubscribeRequest(t.info.sid)):hd.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):hd.warn("Unknown track ".concat(e,", skipping cancel..."))},o=()=>{var t;if(!n)return;const i=this.descriptors.get(e);"active"===(null==i?void 0:i.subscription.type)&&i.subscription.streamControllers.delete(n),n.error(dd.cancelled()),null===(t=r.reject)||void 0===t||t.call(r,dd.cancelled()),a()},c=new ReadableStream({start:i=>{n=i,this.subscribeRequest(e,t).then((()=>Cn(this,void 0,void 0,(function*(){var n,a,c;const d=this.descriptors.get(e);if(!d){hd.error("Unknown track ".concat(e));const t=dd.disconnected();return i.error(t),void(null===(n=r.reject)||void 0===n||n.call(r,t))}if("active"!==d.subscription.type){hd.error("Subscription for track ".concat(e," is not active"));const t=dd.disconnected();return i.error(t),void(null===(a=r.reject)||void 0===a||a.call(r,t))}(null==t?void 0:t.aborted)?o():(null==t||t.addEventListener("abort",o),d.subscription.streamControllers.set(i,s),null===(c=r.resolve)||void 0===c||c.call(r))})))).catch((e=>{var t;i.error(e),null===(t=r.reject)||void 0===t||t.call(r,e)}))},cancel:()=>{a()}},new CountQueuingStrategy({highWaterMark:i}));return[c,r.promise]}subscribeRequest(e,t){return Cn(this,void 0,void 0,(function*(){const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");const n=(t,i,n)=>Cn(this,void 0,void 0,(function*(){if("active"===t.subscription.type)return;if("pending"!==t.subscription.type)throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(t.subscription.type));const r=jc([i,n].filter((e=>void 0!==e))),s=new ma;t.subscription.completionFuture.promise.then((()=>{var e;return null===(e=s.resolve)||void 0===e?void 0:e.call(s)})).catch((e=>{var t;return null===(t=s.reject)||void 0===t?void 0:t.call(s,e)}));const a=()=>{var e;"pending"===t.subscription.type&&(t.subscription.pendingRequestCount-=1,(null==n?void 0:n.aborted)||t.subscription.pendingRequestCount<=0?t.subscription.cancel():null===(e=s.reject)||void 0===e||e.call(s,dd.cancelled()))};r.aborted&&a(),r.addEventListener("abort",a),yield s.promise,r.removeEventListener("abort",a)}));switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new ma,pendingRequestCount:1,cancel:()=>{var t,n;const s=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),"pending"===s.type&&(null===(n=(t=s.completionFuture).reject)||void 0===n||n.call(t,r.aborted?dd.timeout():dd.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=Bc(1e4);return void(yield n(i,t,r))}case"pending":return i.subscription.pendingRequestCount+=1,void(yield n(i,t));case"active":return}}))}querySubscribed(){return Cn(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.subscription.type)).map((e=>[e.info,e.publisherIdentity]))}))}unSubscribeRequest(e){var t;const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");if("active"!==i.subscription.type)return void hd.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat(null===(t=i.subscription)||void 0===t?void 0:t.type));this.closeStreamControllers(i.subscription.streamControllers,e);const n=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const n of e){var i=B(n,2);const e=i[0];(0,i[1])();try{e.close()}catch(e){hd.warn("Failed to close readable stream for track ".concat(t,": ").concat(e))}}}receiveSfuPublicationUpdates(e){return Cn(this,void 0,void 0,(function*(){if(0===e.size)return;const t=new Map;for(const n of e.entries()){var i=B(n,2);const e=i[0],r=i[1],s=new Set;for(const t of r)s.add(t.sid),this.descriptors.has(t.sid)||(yield this.handleTrackPublished(e,t));t.set(e,s)}for(const e of t.entries()){var n=B(e,2);const t=n[0],i=n[1];let r=Array.from(this.descriptors.entries()).filter((e=>{let i=B(e,2);return i[0],i[1].publisherIdentity===t})).map((e=>B(e,1)[0])).filter((e=>!i.has(e)));for(const e of r)this.handleTrackUnpublished(e)}}))}queryPublications(){return Cn(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).map((e=>e.info))}))}handleTrackPublished(e,t){return Cn(this,void 0,void 0,(function*(){if(this.descriptors.has(t.sid))return void hd.error("Existing descriptor for track ".concat(t.sid));let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);const n=new ed(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:n})}))}handleTrackUnpublished(e){const t=this.descriptors.get(e);t?(this.descriptors.delete(e),"active"===t.subscription.type&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})):hd.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(const i of e.entries()){var t=B(i,2);const e=t[0],n=t[1];this.registerSubscriberHandle(e,n)}}registerSubscriberHandle(e,t){var i,n;const r=this.descriptors.get(t);if(r)switch(r.subscription.type){case"none":return void hd.warn("No subscription for ".concat(t));case"active":return r.subscription.subcriptionHandle=e,void this.subscriptionHandles.set(e,t);case"pending":{const s=new ud({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:r.pipelineOptions}),a=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:s,streamControllers:new Map},this.subscriptionHandles.set(e,t),null===(n=(i=a.completionFuture).resolve)||void 0===n||n.call(i)}}else hd.error("Unknown track ".concat(t))}packetReceived(e){return Cn(this,void 0,void 0,(function*(){let t;try{t=B(nd.fromBinary(e),1)[0]}catch(e){return void hd.error("Failed to deserialize packet: ".concat(e))}const i=this.subscriptionHandles.get(t.header.trackHandle);if(!i)return void hd.warn("Unknown subscriber handle ".concat(t.header.trackHandle));const n=this.descriptors.get(i);if(!n)return void hd.error("Missing descriptor for track ".concat(i));if("active"!==n.subscription.type)return void hd.warn("Received packet for track ".concat(i," without active subscription"));const r=yield n.subscription.pipeline.processPacket(t);if(r)for(const e of n.subscription.streamControllers.keys()){if(null!==e.desiredSize&&e.desiredSize<=0){hd.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(e.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const t=$c.lossyIntoFrame(r);e.enqueue(t)}}))}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=B(t,2);const i=e[0];"none"!==e[1].subscription.type&&this.emit("sfuUpdateSubscription",{sid:i,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,i;for(const n of this.descriptors.values())if(n.publisherIdentity===e)switch(n.subscription.type){case"none":break;case"pending":null===(i=(t=n.subscription.completionFuture).reject)||void 0===i||i.call(t,dd.disconnected());break;case"active":this.unSubscribeRequest(n.info.sid)}}reset(){var e,t;for(const i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),"pending"===i.subscription.type&&(null===(t=(e=i.subscription.completionFuture).reject)||void 0===t||t.call(e,dd.disconnected())),"active"===i.subscription.type&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class md extends Gr{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=gd[t]}static mtuTooShort(){return new md("MTU is too short to send frame",gd.MtuTooShort)}}var gd,fd,vd,kd;!function(e){e[e.MtuTooShort=0]="MtuTooShort"}(gd||(gd={}));class yd{constructor(e,t){this.sequence=ao.u16(0),this.frameNumber=ao.u16(0),this.clock=co.rtpStartingNow(oo.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?id.Single:0===e?id.Start:e===t-1?id.Final:id.Inter}*packetize(e,t){var i;const n=this.frameNumber.getThenIncrement(),r={marker:id.Inter,trackHandle:this.handle,sequence:ao.u16(0),frameNumber:n,timestamp:null!==(i=null==t?void 0:t.now)&&void 0!==i?i:this.clock.now(),extensions:e.extensions},s=new td(r).toBinaryLengthBytes();if(s>=this.mtuSizeBytes)throw md.mtuTooShort();const a=this.mtuSizeBytes-s,o=Math.ceil(e.payload.byteLength/a);for(let t=0,i=0;i<e.payload.byteLength;t=(c=[t+1,i+a])[0],i=c[1],c){var c;const n=this.sequence.getThenIncrement(),s=new td(Object.assign(Object.assign({},r),{marker:yd.computeFrameMarker(t,o),sequence:n})),d=Math.min(a,e.payload.byteLength-i),l=new Uint8Array(e.payload.buffer,e.payload.byteOffset+i,d);yield new nd(s,l)}}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.DuplicateName=1]="DuplicateName",e[e.Timeout=2]="Timeout",e[e.LimitReached=3]="LimitReached",e[e.Disconnected=4]="Disconnected",e[e.Cancelled=5]="Cancelled",e[e.InvalidName=6]="InvalidName",e[e.Unknown=7]="Unknown"}(fd||(fd={}));class bd extends Gr{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=fd[t],this.rawMessage=null==i?void 0:i.rawMessage}static notAllowed(e){return new bd("Data track publishing unauthorized",fd.NotAllowed,{rawMessage:e})}static duplicateName(e){return new bd("Track name already taken",fd.DuplicateName,{rawMessage:e})}static invalidName(e){return new bd("Track name is invalid",fd.InvalidName,{rawMessage:e})}static timeout(){return new bd("Publish data track timed-out. Does the LiveKit server support data tracks?",fd.Timeout)}static limitReached(e){return new bd("Data track publication limit reached",fd.LimitReached,{rawMessage:e})}static unknown(e,t){return new bd("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),fd.Unknown)}static disconnected(){return new bd("Room disconnected",fd.Disconnected)}static cancelled(){return new bd("Publish data track cancelled by caller",fd.Cancelled)}}!function(e){e[e.TrackUnpublished=0]="TrackUnpublished",e[e.Dropped=1]="Dropped"}(vd||(vd={}));class Td extends Gr{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=vd[t]}static trackUnpublished(){return new Td("Track is no longer published",vd.TrackUnpublished)}static dropped(e){return new Td("Frame was dropped",vd.Dropped,{cause:e})}}!function(e){e[e.Packetizer=0]="Packetizer",e[e.Encryption=1]="Encryption"}(kd||(kd={}));class Sd extends Gr{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=kd[t]}static packetizer(e){return new Sd("Error packetizing frame",kd.Packetizer,{cause:e})}static encryption(e){return new Sd("Error encrypting frame",kd.Encryption,{cause:e})}}class Cd{constructor(e,t){this.trackSymbol=Xc,this.isLocal=!0,this.typeSymbol=Zc,this.handle=null,this.log=kn,this.flushedFuture=new ma,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;null===(t=(e=this.flushedFuture).resolve)||void 0===t||t.call(e),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,i;this.isFlushed=e.isFlushed,e.isFlushed&&(null===(i=(t=this.flushedFuture).resolve)||void 0===i||i.call(t),this.flushedFuture=new ma)},this.options=e,this.manager=t,this.log=yn(fn.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){const n=new Cd(e,t);return n.handle=i,n}get info(){const e=this.descriptor;return"active"===(null==e?void 0:e.type)?e.info:void 0}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return Cn(this,void 0,void 0,(function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}}))}isPublished(){var e;return"active"===(null===(e=this.descriptor)||void 0===e?void 0:e.type)&&"unpublished"!==this.descriptor.publishState}tryPush(e){if(!this.handle)throw Td.trackUnpublished();const t=$c.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}flush(){return Cn(this,void 0,void 0,(function*(){if(!this.isFlushed)return this.flushedFuture.promise}))}unpublish(){return Cn(this,void 0,void 0,(function*(){if(this.handle)try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}else kn.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'))}))}}class wd{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new yd(e.info.pubHandle,wd.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return Rn(this,arguments,(function*(){const t=yield En(this.encryptIfNeeded(e));try{yield En(yield*function(e){var t,i;return t={},n("next"),n("throw",(function(e){throw e})),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,r){t[n]=e[n]?function(t){return(i=!i)?{value:En(e[n](t)),done:!1}:r?r(t):t}:r}}(Pn(this.packetizer.packetize(t))))}catch(e){if(e instanceof md)throw Sd.packetizer(e);throw e}}))}encryptIfNeeded(e){return Cn(this,void 0,void 0,(function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw Sd.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new Qc(t.keyIndex,t.iv),e}))}}wd.TRANSPORT_MTU_BYTES=16e3;const Ed=yn(fn.DataTracks),Rd={pending:()=>({type:"pending",completionFuture:new ma}),active:(e,t)=>({type:"active",info:e,publishState:"published",pipeline:new wd({info:e,e2eeManager:t}),unpublishingFuture:new ma})};class Pd extends Dn.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new mo,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}static withDescriptors(e){const t=new Pd;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.type&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return null!==(t=this.descriptors.get(e))&&void 0!==t?t:null}tryProcessAndSend(e,t){return Cn(this,void 0,void 0,(function*(){var i,n,r,s,a;const o=this.getDescriptor(e);if("active"!==(null==o?void 0:o.type))throw Td.trackUnpublished();if("unpublished"===o.publishState)throw Td.trackUnpublished();if("republishing"===o.publishState)throw Td.dropped("Data track republishing");try{try{for(var c,d=!0,l=Pn(o.pipeline.processFrame(t));!(i=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const t=s,i=null!==(a=this.inFlightPacketCounter.get(e))&&void 0!==a?a:0;this.inFlightPacketCounter.set(e,i+1),0===i&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:t.toBinary()})}}catch(e){n={error:e}}finally{try{d||i||!(r=l.return)||(yield r.call(l))}finally{if(n)throw n.error}}}catch(e){throw Td.dropped(e)}}))}handlePacketSendComplete(e){var t;let i=(null!==(t=this.inFlightPacketCounter.get(e))&&void 0!==t?t:0)-1;i<0&&(Ed.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),i=0),this.inFlightPacketCounter.set(e,i),0===i&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return Cn(this,void 0,void 0,(function*(){const i=this.handleAllocator.get();if(!i)throw bd.limitReached();const n=Bc(1e4),r=t?jc([t,n]):n;if(this.descriptors.has(i))throw new Error("Descriptor for handle already exists");const s=Rd.pending();this.descriptors.set(i,s);const a=()=>{var e,t;const r=this.descriptors.get(i);r?(this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),"pending"===r.type&&(null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,n.aborted?bd.timeout():bd.cancelled()))):Ed.warn("No descriptor for ".concat(i))};return r.aborted?(a(),s.completionFuture.promise.then((()=>i))):(r.addEventListener("abort",a),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:null!==this.e2eeManager}),yield s.completionFuture.promise,r.removeEventListener("abort",a),this.emit("trackPublished",{track:Cd.withExplicitHandle(e,this,i)}),i)}))}queryPublished(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.type)).map((e=>e.info))}unpublishRequest(e){return Cn(this,void 0,void 0,(function*(){const t=this.descriptors.get(e);t?"active"===t.type?(this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})):Ed.warn("Track ".concat(e," not active")):Ed.warn("No descriptor for ".concat(e))}))}receivedSfuPublishResponse(e,t){var i,n,r,s;const a=this.descriptors.get(e);if(a)switch(this.descriptors.delete(e),a.type){case"pending":if("ok"===t.type){const e=t.data,r=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,Rd.active(e,r)),null===(n=(i=a.completionFuture).resolve)||void 0===n||n.call(i)}else null===(s=(r=a.completionFuture).reject)||void 0===s||s.call(r,t.error);return;case"active":if("republishing"!==a.publishState)return void Ed.warn("Track ".concat(e," already active"));if("error"===t.type)return void Ed.warn("Republish failed for track ".concat(e));Ed.debug("Track ".concat(e," republished")),a.info.sid=t.data.sid,a.publishState="published",this.descriptors.set(a.info.pubHandle,a)}else Ed.warn("No descriptor for ".concat(e))}receivedSfuUnpublishResponse(e){var t,i;const n=this.descriptors.get(e);n?(this.descriptors.delete(e),"active"===n.type?(n.publishState="unpublished",null===(i=(t=n.unpublishingFuture).resolve)||void 0===i||i.call(t)):Ed.warn("Track ".concat(e," not active"))):Ed.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(const n of this.descriptors.entries()){var i=B(n,2);const r=i[0],s=i[1];switch(s.type){case"pending":this.descriptors.delete(r),null===(t=(e=s.completionFuture).reject)||void 0===t||t.call(e,bd.disconnected());break;case"active":s.publishState="republishing",this.emit("sfuPublishRequest",{handle:s.info.pubHandle,name:s.info.name,usesE2ee:s.info.usesE2ee})}}}reset(){return Cn(this,void 0,void 0,(function*(){var e,t,i,n;this.handleAllocator.reset();for(const r of this.descriptors.values())switch(r.type){case"pending":null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,bd.disconnected());break;case"active":null===(n=(i=r.unpublishingFuture).resolve)||void 0===n||n.call(i),yield this.unpublishRequest(r.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")}))}}class Id extends Error{constructor(e,t,i,n){super(t),this.code=e,this.message=Ld(t,Id.MAX_MESSAGE_BYTES),this.data=i?Ld(i,Id.MAX_DATA_BYTES):void 0,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}static fromProto(e){return new Id(e.code,e.message,e.data)}toProto(){return new xt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new Id(Id.ErrorCode[e],Id.ErrorMessage[e],t,i)}}Id.MAX_MESSAGE_BYTES=256,Id.MAX_DATA_BYTES=15360,Id.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},Id.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const Md="lk.rpc_request",Dd="lk.rpc_response";var Ad;!function(e){e.RPC_REQUEST_ID="lk.rpc_request_id",e.RPC_REQUEST_METHOD="lk.rpc_request_method",e.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",e.RPC_REQUEST_VERSION="lk.rpc_request_version"}(Ad||(Ad={}));function _d(e){return(new TextEncoder).encode(e).length}function Ld(e,t){if(_d(e)<=t)return e;let i=0,n=e.length;const r=new TextEncoder;for(;i<n;){const s=Math.floor((i+n+1)/2);r.encode(e.slice(0,s)).length<=t?i=s:n=s-1}return e.slice(0,i)}class Od extends Dn.EventEmitter{constructor(e,t,i,n){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=n}performRpc(e){return Cn(this,arguments,void 0,(function(e){var t=this;let i=e.destinationIdentity,n=e.method,r=e.payload,s=e.responseTimeout,a=void 0===s?15e3:s;return function*(){const e=t.getRemoteParticipantClientProtocol(i);if(_d(r)>15360&&e<1)throw Id.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const s=t.getServerVersion();if(s&&ra(s,"1.8.0")<0)throw Id.builtIn("UNSUPPORTED_SERVER");const o=Math.max(a,8e3),c=crypto.randomUUID(),d=new ma;let l=null;const u=setTimeout((()=>{var e;t.pendingAcks.delete(c),null===(e=d.reject)||void 0===e||e.call(d,Id.builtIn("CONNECTION_TIMEOUT")),t.pendingResponses.delete(c),null!==l&&clearTimeout(l)}),7e3);t.pendingAcks.set(c,{resolve:()=>{clearTimeout(u)},participantIdentity:i}),t.pendingResponses.set(c,{completionFuture:d,participantIdentity:i}),yield t.publishRpcRequest(i,c,n,r,o,e),l=setTimeout((()=>{var e;t.pendingResponses.delete(c),null===(e=d.reject)||void 0===e||e.call(d,Id.builtIn("RESPONSE_TIMEOUT"))}),a);const h=d.promise.finally((()=>{clearTimeout(l),t.pendingAcks.has(c)&&(t.log.warn("RPC response received before ack",c),t.pendingAcks.delete(c),clearTimeout(u))}));return[c,h]}()}))}publishRpcRequest(e,t,i,n,r,s){return Cn(this,void 0,void 0,(function*(){if(s>=1){const s=yield this.outgoingDataStreamManager.streamText({topic:Md,destinationIdentities:[e],attributes:{[Ad.RPC_REQUEST_ID]:t,[Ad.RPC_REQUEST_METHOD]:i,[Ad.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[Ad.RPC_REQUEST_VERSION]:"".concat(2)}});return yield s.write(n),void(yield s.close())}this.emit("sendDataPacket",{packet:new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcRequest",value:new _t({id:t,method:i,payload:n,responseTimeoutMs:r,version:1})}})})}))}handleIncomingDataStream(e,t,i){return Cn(this,void 0,void 0,(function*(){const n=i[Ad.RPC_REQUEST_ID];if(!n)return void this.log.warn("RPC data stream malformed: ".concat(Ad.RPC_REQUEST_ID," not set."));const r=this.pendingResponses.get(n);if(r&&r.participantIdentity!==t)return void this.log.warn("RPC response stream for ".concat(n," arrived from unexpected sender ").concat(t,", expected ").concat(r.participantIdentity,". Ignoring."));let s;try{s=yield e.readAll()}catch(e){return this.log.warn("Error reading RPC response payload: ".concat(e)),void this.handleIncomingRpcResponseFailure(n,Id.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:e}))}this.handleIncomingRpcResponseSuccess(n,s)}))}handleIncomingRpcResponseSuccess(e,t){var i,n;const r=this.pendingResponses.get(e);r?(null===(n=(i=r.completionFuture).resolve)||void 0===n||n.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,n;const r=this.pendingResponses.get(e);r?(null===(n=(i=r.completionFuture).reject)||void 0===n||n.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const t of this.pendingAcks){var i=B(t,2);const n=i[0];i[1].participantIdentity===e&&this.pendingAcks.delete(n)}for(const i of this.pendingResponses){var n=B(i,2);const s=n[0];var r=n[1];const a=r.participantIdentity,o=r.completionFuture;a===e&&(null===(t=o.reject)||void 0===t||t.call(o,Id.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(s))}}}class xd extends Dn.EventEmitter{constructor(e,t,i){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i}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){return Cn(this,void 0,void 0,(function*(){var i;if(this.publishRpcAck(e,t.id),1!==t.version)return void this.publishRpcResponsePacket(e,t.id,null,Id.builtIn("UNSUPPORTED_VERSION"));const n=this.rpcHandlers.get(t.method);if(!n)return void this.publishRpcResponsePacket(e,t.id,null,Id.builtIn("UNSUPPORTED_METHOD"));let r;try{r=yield n({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(n){let r;return n instanceof Id?r=n:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),n),r=Id.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!==(i=null==n?void 0:n.message)&&void 0!==i?i:n),{cause:n})),void this.publishRpcResponsePacket(e,t.id,null,r)}yield this.publishRpcResponse(e,t.id,null!=r?r:"")}))}handleIncomingDataStream(e,t,i){return Cn(this,void 0,void 0,(function*(){const n=i[Ad.RPC_REQUEST_ID],r=i[Ad.RPC_REQUEST_METHOD],s=parseInt(i[Ad.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),a=parseInt(i[Ad.RPC_REQUEST_VERSION],10);if(!n||!r||Number.isNaN(s)||Number.isNaN(a))return this.log.warn("RPC data stream malformed: ".concat(Ad.RPC_REQUEST_ID," / ").concat(Ad.RPC_REQUEST_METHOD," / ").concat(Ad.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(Ad.RPC_REQUEST_VERSION," not set.")),void this.publishRpcResponsePacket(t,n,null,Id.builtIn("APPLICATION_ERROR","RPC data stream malformed"));if(this.publishRpcAck(t,n),2!==a)return void this.publishRpcResponsePacket(t,n,null,Id.builtIn("UNSUPPORTED_VERSION"));let o;try{o=yield e.readAll()}catch(e){return this.log.warn("Error reading RPC request payload: ".concat(e)),void this.publishRpcResponsePacket(t,n,null,Id.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:e}))}const c=this.rpcHandlers.get(r);if(!c)return void this.publishRpcResponsePacket(t,n,null,Id.builtIn("UNSUPPORTED_METHOD"));let d;try{d=yield c({requestId:n,callerIdentity:t,payload:o,responseTimeout:s})}catch(e){let i;return e instanceof Id?i=e:(this.log.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),e),i=Id.builtIn("APPLICATION_ERROR")),void this.publishRpcResponsePacket(t,n,null,i)}yield this.publishRpcResponse(t,n,null!=d?d:"")}))}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcAck",value:new Lt({requestId:t})}})})}publishRpcResponsePacket(e,t,i,n){this.emit("sendDataPacket",{packet:new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcResponse",value:new Ot({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}})})}publishRpcResponse(e,t,i){return Cn(this,void 0,void 0,(function*(){if(this.getRemoteParticipantClientProtocol(e)>=1){const n=yield this.outgoingDataStreamManager.streamText({topic:Dd,destinationIdentities:[e],attributes:{[Ad.RPC_REQUEST_ID]:t}});return yield n.write(i),void(yield n.close())}if(_d(i)>15360)return this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),void this.publishRpcResponsePacket(e,t,null,Id.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));this.publishRpcResponsePacket(e,t,i,null)}))}}class Nd extends Ga{constructor(e,t,i,n,r,s){super(e,t,Us.Kind.Audio,i,s),this.monitorReceiver=()=>Cn(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=za(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Xs()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Xs())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Cn(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Ws(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Ws(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(es.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(es.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 Cn(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 Ud extends Dn.EventEmitter{constructor(e,t,i,n){var r;super(),this.metadataMuted=!1,this.encryption=mt.NONE,this.log=kn,this.handleMuted=()=>{this.emit(es.Muted)},this.handleUnmuted=()=>{this.emit(es.Unmuted)},this.log=yn(null!==(r=null==n?void 0:n.loggerName)&&void 0!==r?r:fn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=Us.Source.Unknown}setTrack(e){this.track&&(this.track.off(es.Muted,this.handleMuted),this.track.off(es.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(es.Muted,this.handleMuted),e.on(es.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),_s(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==mt.NONE}get audioTrack(){if(Ta(this.track))return this.track}get videoTrack(){if(Sa(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Us.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Us.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"}(Ud||(Ud={}));class Fd extends Ud{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(es.Ended)},this.handleCpuConstrained=()=>{this.track&&Sa(this.track)&&this.emit(es.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(es.Ended,this.handleTrackEnded),this.track.off(es.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(es.Ended,this.handleTrackEnded),e.on(es.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 Cn(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Cn(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Cn(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Cn(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(Ta(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(st.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(st.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(st.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(st.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(st.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(st.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function jd(e,t){return Cn(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const n=Ls(e),r=n.audioProcessor,s=n.videoProcessor,a=n.optionsWithoutProcessor;let o=a.audio,c=a.video;if(r&&"object"==typeof a.audio&&(a.audio.processor=r),s&&"object"==typeof a.video&&(a.video.processor=s),e.audio&&"object"==typeof a.audio&&"string"==typeof a.audio.deviceId){const e=a.audio.deviceId;a.audio.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&"object"==typeof a.video&&"string"==typeof a.video.deviceId){const e=a.video.deviceId;a.video.deviceId={exact:e},i=!0,c=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}!0===a.audio?a.audio={deviceId:"default"}:"object"==typeof a.audio&&null!==a.audio&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),!0===a.video?a.video={deviceId:"default"}:"object"!=typeof a.video||a.video.deviceId||(a.video.deviceId="default");const d=Es(Cs(a,Jo,Qo)),l=navigator.mediaDevices.getUserMedia(d);a.audio&&(no.userMediaPromiseMap.set("audioinput",l),l.catch((()=>no.userMediaPromiseMap.delete("audioinput")))),a.video&&(no.userMediaPromiseMap.set("videoinput",l),l.catch((()=>no.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>Cn(this,void 0,void 0,(function*(){let n;const a="audio"===i.kind?d.audio:d.video;"boolean"!=typeof a&&(n=a);const o=i.getSettings().deviceId;(null==n?void 0:n.deviceId)&&ga(n.deviceId)!==o?n.deviceId=o:n||(n={deviceId:o});const c=function(e,t,i){switch(e.kind){case"audio":return new rc(e,t,!1,void 0,i);case"video":return new vc(e,t,!1,i);default:throw new ns("unsupported track type: ".concat(e.kind))}}(i,n,t);return c.kind===Us.Kind.Video?c.source=Us.Source.Camera:c.kind===Us.Kind.Audio&&(c.source=Us.Source.Microphone),c.mediaStream=e,Ta(c)&&r?yield c.setProcessor(r):Sa(c)&&s&&(yield c.setProcessor(s)),c})))))}catch(n){if(!i)throw n;return jd(Object.assign(Object.assign({},e),{audio:o,video:c}),t)}}))}var Bd,Vd;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(Bd||(Bd={}));class qd extends Dn.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===ht.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===ut.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,r,s){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ht.STANDARD;var o;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Bd.Unknown,this.log=kn,this.loggerOptions=s,this.log=yn(null!==(o=null==s?void 0:s.loggerName)&&void 0!==o?o:fn.Participant,(()=>this.logContext)),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const t of this.trackPublications){const i=B(t,2)[1];if(i.source===e)return i}}getTrackPublicationByName(e){for(const t of this.trackPublications){const i=B(t,2)[1];if(i.trackName===e)return i}}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new ma,this.once(Xr.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(Us.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Us.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Us.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===ut.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==ut.ACTIVE&&this.emit(Xr.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(Xr.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(Xr.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)],r={};for(const s of n)e[s]!==t[s]&&(r[s]=null!==(i=t[s])&&void 0!==i?i:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(Xr.AttributesChanged,t)}setPermissions(e){var t,i,n,r,s,a;const o=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||e.recorder!==(null===(s=this.permissions)||void 0===s?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(a=this.permissions)||void 0===a?void 0:a.canSubscribeMetrics);return this.permissions=e,c&&this.emit(Xr.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Xr.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case et.EXCELLENT:return Bd.Excellent;case et.GOOD:return Bd.Good;case et.POOR:return Bd.Poor;case et.LOST:return Bd.Lost;default:return Bd.Unknown}}(e),t!==this._connectionQuality&&this.emit(Xr.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=>Ta(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on(es.Muted,(()=>{this.emit(Xr.TrackMuted,e)})),e.on(es.Unmuted,(()=>{this.emit(Xr.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Us.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Us.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class Kd extends qd{constructor(e,t,i,n,r,s,a,o){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=mt.NONE,this.e2eeStateMutex=new d,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ma)},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,r,s;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(s=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===s||s.call(r,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new ma),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{const t=e.requestId,i=e.reason,n=e.message,r=this.pendingSignalRequests.get(t);switch(r&&(i!==tn.OK&&r.reject(new ds(n,i)),this.pendingSignalRequests.delete(t)),e.request.case){case"publishDataTrack":{let t;switch(e.reason){case tn.NOT_ALLOWED:t=bd.notAllowed(e.message);break;case tn.DUPLICATE_NAME:t=bd.duplicateName(e.message);break;case tn.INVALID_NAME:t=bd.invalidName(e.message);break;case tn.LIMIT_EXCEEDED:t=bd.limitReached(e.message);break;default:t=bd.unknown(e.reason,e.message)}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:"error",error:t});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Vi({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",_s(e))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",_s(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",_s(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.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",_s(t)),this.emit(Xr.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>Cn(this,void 0,void 0,(function*(){var t,i,n,r,s;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const a=this.videoTrackPublications.get(e.trackSid);if(!a)return void this.log.warn("received subscribed quality update for unknown track",{trackSid:e.trackSid});if(!a.videoTrack)return;const o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Pn(o);!(t=(c=yield l.next()).done);d=!0){r=c.value,d=!1;const e=r;vs(e)&&(this.log.debug("publish ".concat(e," for ").concat(a.videoTrack.sid),_s(a)),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.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",{trackSid:e.trackSid})},this.handleTrackEnded=e=>Cn(this,void 0,void 0,(function*(){if(e.source===Us.Source.ScreenShare||e.source===Us.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",_s(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(wa(e)||Ca(e))try{if($s())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Us.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),_s(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",_s(e)),wa(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",_s(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.roomOutgoingDataStreamManager=r,this.roomOutgoingDataTrackManager=s,this.rpcClientManager=a,this.rpcServerManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==mt.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(Zr.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(Zr.Connected,this.handleReconnected).on(Zr.SignalConnected,this.handleSignalConnected).on(Zr.SignalRestarted,this.handleReconnected).on(Zr.SignalResumed,this.handleReconnected).on(Zr.Restarting,this.handleReconnecting).on(Zr.Resuming,this.handleReconnecting).on(Zr.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Zr.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Zr.Closing,this.handleClosing).on(Zr.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return Cn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Cn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Cn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Cn(this,arguments,void 0,(function(e){var t=this;let i=e.metadata,n=e.name,r=e.attributes;return function*(){return new jr(((e,s)=>Cn(t,void 0,void 0,(function*(){var t,a;try{let o=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(a=null!=n?n:this.name)&&void 0!==a?a:"",r),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{s(e),o=!0},values:{name:n,metadata:i,attributes:r}});performance.now()-d<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!r||Object.entries(r).every((e=>{let t=B(e,2),i=t[0],n=t[1];return this.attributes[i]===n||""===n&&!this.attributes[i]}))))return this.pendingSignalRequests.delete(c),void e();yield Vs(50)}s(new ds("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error?s(e):s(new Error(String(e)))}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(Us.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Us.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Us.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return Cn(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?mt.GCM:mt.NONE,yield Promise.all(this.pendingPublishPromises.values()),0===this.trackPublications.size||Array.from(this.trackPublications.values()).every((t=>t.isEncrypted===e)))return;yield this.republishAllTracks(void 0,!1)}finally{t()}}))}setTrackEnabled(e,t,i,n){return Cn(this,void 0,void 0,(function*(){var r,s;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",{source:e}),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case Us.Source.Camera:t=yield this.createTracks({video:null===(r=i)||void 0===r||r});break;case Us.Source.Microphone:t=yield this.createTracks({audio:null===(s=i)||void 0===s||s});break;case Us.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new ns(e)}}catch(i){throw null==t||t.forEach((e=>{e.stop()})),i instanceof Error&&this.emit(Xr.MediaDevicesError,i,Ms(e)),this.pendingPublishing.delete(e),i}for(const n of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===Us.Source.Microphone&&Ta(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),n.startPreConnectBuffer())}try{const e=[];for(const i of t)this.log.info("publishing track",_s(i)),e.push(this.publishTrack(i,n));a=B(yield Promise.all(e),1)[0]}catch(e){throw null==t||t.forEach((e=>{e.stop()})),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==a?void 0:a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",{source:e})),a&&a.track)if(e===Us.Source.ScreenShare){const e=[this.unpublishTrack(a.track)],t=this.getTrackPublication(Us.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),a=B(yield Promise.all(e),1)[0]}else yield a.mute();return a}))}enableCameraAndMicrophone(){return Cn(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Us.Source.Camera)&&!this.pendingPublishing.has(Us.Source.Microphone)){this.pendingPublishing.add(Us.Source.Camera),this.pendingPublishing.add(Us.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(Us.Source.Camera),this.pendingPublishing.delete(Us.Source.Microphone)}}}))}createTracks(e){return Cn(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=Cs(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 jd(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return e.map((e=>(Ta(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=Us.Source.Microphone,this.emit(Xr.AudioStreamAcquired)),Sa(e)&&(this.cameraError=void 0,e.source=Us.Source.Camera),e)))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}}))}createScreenTracks(e){return Cn(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new is("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=qr();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)&&ra(e.osVersion,"17")>=0}()||(e.resolution=Ss.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=Js()?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 ns("no video track found");const r=new vc(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Us.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(i.getAudioTracks().length>0){this.emit(Xr.AudioStreamAcquired);const e=new rc(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=Us.Source.ScreenShareAudio,s.push(e)}return s}))}publishTrack(e,t){return Cn(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}waitForNextEngineRestart(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;return new Promise(((t,i)=>{const n=()=>{clearTimeout(a),this.engine.off(Zr.Restarted,r),this.engine.off(Zr.Closing,s)},r=()=>{n(),t()},s=()=>{n(),i(new Error("engine closed before restart completed"))},a=setTimeout((()=>{n(),i(new Error("timed out waiting for engine restart"))}),e);this.engine.once(Zr.Restarted,r),this.engine.once(Zr.Closing,s)}))}publishOrRepublishTrack(e,t){return Cn(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return function*(){var s,a,o,c;let d,l;if(wa(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),ba(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)d=e.getConstraints();else{let t;switch(d=e.constraints,e.source){case Us.Source.Microphone:t="audioinput";break;case Us.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(d=Object.assign(Object.assign({},d),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new rc(e,d,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new vc(e,d,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new ns("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&&(l=t)})),l)return i.log.warn("track has already been published, skipping",_s(l)),l;const u=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),h="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,p=null!==(a=u.forceStereo)&&void 0!==a?a:h;p&&(void 0===u.dtx&&i.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",_s(e)),void 0===u.red&&i.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=u.dtx)&&void 0!==o||(u.dtx=!1),null!==(c=u.red)&&void 0!==c||(u.red=!1)),!function(){const e=qr(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&ra(e.osVersion,t)>=0)||"Safari"===e.name&&ra(e.version,t)>=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"),u.simulcast=!1),u.source&&(e.source=u.source);const m=new Promise(((t,n)=>Cn(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==bo.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:_s(e)});let i=!1;const r=setTimeout((()=>{i=!0,e.stop(),n(new cs("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),i)return;const s=yield this.publish(e,u,p);t(s)}else try{const i=yield this.publish(e,u,p);t(i)}catch(e){n(e)}}catch(e){n(e)}}))));i.pendingPublishPromises.set(e,m);try{return yield m}catch(s){if(!r&&s instanceof as)return i.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:s}),i.pendingPublishPromises.delete(e),yield i.waitForNextEngineRestart(),yield i.publishOrRepublishTrack(e,t,n,!0);throw s}finally{i.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new ma),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",_s(e)),!1;const t=this.permissions,i=t.canPublish,n=t.canPublishSources;return!(!i||0!==n.length&&!n.map((e=>function(e){switch(e){case Xe.CAMERA:return Us.Source.Camera;case Xe.MICROPHONE:return Us.Source.Microphone;case Xe.SCREEN_SHARE:return Us.Source.ScreenShare;case Xe.SCREEN_SHARE_AUDIO:return Us.Source.ScreenShareAudio;default:return Us.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",_s(e)),!1)}publish(e,t,i){return Cn(this,void 0,void 0,(function*(){var n,r,s,a,o,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new cs("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>ba(e)&&t.source===e.source))&&e.source!==Us.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),_s(e)),t.stopMicTrackOnMute&&Ta(e)&&(e.stopOnMute=!0),e.source===Us.Source.ScreenShare&&zs()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Js()||zs())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(zs())return!1;if(Js()){const e=qr();if((null==e?void 0:e.version)&&ra(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&ra(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.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=zo),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===Ds(e.mime)))||(t.videoCodec=Ds(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(es.Muted,this.onTrackMuted),e.on(es.Unmuted,this.onTrackUnmuted),e.on(es.Ended,this.handleTrackEnded),e.on(es.UpstreamPaused,this.onTrackUpstreamPaused),e.on(es.UpstreamResumed,this.onTrackUpstreamResumed),e.on(es.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(n=t.dtx)||void 0===n||n),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(st.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(st.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(st.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(st.TF_STEREO),g&&m.push(st.TF_NO_DTX),wa(e)&&e.hasPreConnectBuffer&&m.push(st.TF_PRECONNECT_BUFFER);const v=this.normalizeRequestedFrameMetadataOptions(e,t),k=new si({cid:e.mediaStreamTrack.id,name:t.name,type:Us.kindToProto(e.kind),muted:e.isMuted,source:Us.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(r=t.red)||void 0===r||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m,packetTrailerFeatures:v});let y;if(e.kind===Us.Kind.Video){let i;try{i=yield e.waitForDimensions()}catch(t){const n=null!==(a=null===(s=this.roomOptions.videoCaptureDefaults)||void 0===s?void 0:s.resolution)&&void 0!==a?a:bs.h720.resolution;i={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},_s(e)),{dims:i}))}k.width=i.width,k.height=i.height,Ca(e)&&(Hs(p)&&(e.source===Us.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",_s(e)))),t.scalabilityMode=null!==(o=t.scalabilityMode)&&void 0!==o?o:"L3T3_KEY"),k.simulcastCodecs=[new ri({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:zo}),t.backupCodec&&p!==t.backupCodec.codec&&k.encryption===mt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),k.simulcastCodecs.push(new ri({codec:t.backupCodec.codec,cid:""})))),y=uc(e.source===Us.Source.ScreenShare,k.width,k.height,t),k.layers=bc(k.width,k.height,y,Hs(t.videoCodec))}else e.kind===Us.Kind.Audio&&(y=[{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 ss("cannot publish track when not connected");const b=()=>Cn(this,void 0,void 0,(function*(){var i,n,r;if(!this.engine.pcManager)throw new ss("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),Ca(e)&&(e.publishOptions=t),this.emit(Xr.LocalSenderCreated,e.sender,e),Ca(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===Us.Source.ScreenShare||e.constraints.height&&ga(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),y)if(zs()&&e.kind===Us.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=y[0])||void 0===n?void 0:n.maxBitrate)?y[0].maxBitrate/1e3:0})}else e.codec&&Hs(e.codec)&&(null===(r=y[0])||void 0===r?void 0:r.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:k.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()}));let T;const S=new Promise(((t,i)=>Cn(this,void 0,void 0,(function*(){var n;try{T=yield this.engine.addTrack(k),t(T)}catch(t){if(e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(e){this.log.error(e)}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({},_s(e)),{error:t}))}))}i(t)}}))));if(this.enabledPublishVideoCodecs.length>0&&0===v.length){const e=yield Promise.all([S,b()]);T=e[0]}else{let i;if(T=yield S,T.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===Us.Kind.Video){const n=Ds(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},_s(e)),{codec:n})),t.videoCodec=n,y=uc(e.source===Us.Source.ScreenShare,k.width,k.height,t))}yield b()}const C=new Fd(e.kind,T,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(es.CpuConstrained,(e=>this.onTrackCpuConstrained(e,C))),C.options=t,e.sid=T.sid,Ca(e)&&(e.publishOptions=t,k.width&&k.height&&(e.lastEncodedDimensions={width:k.width,height:k.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:y,trackInfo:T}),Ca(e)?e.startMonitor(this.engine.client):wa(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit(Xr.LocalTrackPublished,C),wa(e)&&T.audioFeatures.includes(st.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();if(this.on(Xr.LocalTrackSubscribed,(t=>{if(t.trackSid===T.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed");this.log.debug("finished recording preconnect buffer",_s(e)),e.stopPreConnectBuffer()}})),t){const n=new Promise(((n,r)=>Cn(this,void 0,void 0,(function*(){var s,a,o,c,d,l;try{this.log.debug("waiting for agent",_s(e));const m=setTimeout((()=>{r(new Error("agent not active within 10 seconds"))}),1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",_s(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=Pn(t);!(s=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){a={error:e}}finally{try{h||s||!(o=p.return)||(yield o.call(p))}finally{if(a)throw a.error}}yield v.close(),n()}catch(e){r(e)}}))));n.then((()=>{this.log.debug("preconnect buffer sent successfully",_s(e))})).catch((t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},_s(e)),{error:t}))}))}}return C}))}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||qa(null!==(e=this.roomOptions.frameMetadata)&&void 0!==e?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var i;const n=null!==(i=t.frameMetadata)&&void 0!==i?i:t.packetTrailer;if(e.kind!==Us.Kind.Video||!Ka(n))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),_s(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const r=function(e){const t=[];return(null==e?void 0:e.timestamp)&&t.push(at.PTF_USER_TIMESTAMP),(null==e?void 0:e.frameId)&&t.push(at.PTF_FRAME_ID),t}(n),s=function(e){if(!e||0===e.length)return;const t={};return e.includes(at.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(at.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}(r);return t.frameMetadata=s,t.packetTrailer=s,r}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Cn(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==mt.NONE)return;let r;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(r=t)})),!r)throw new ns("track is not published");if(!Ca(e))throw new ns("track is not a video track");const s=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),a=hc(e,t,s);if(!a)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",_s(e));const o=e.addSimulcastTrack(t,a);if(!o)return;const c=this.normalizeRequestedFrameMetadataOptions(e,s),d=new si({cid:o.mediaStreamTrack.id,type:Us.kindToProto(e.kind),muted:e.isMuted,source:Us.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:s.videoCodec,cid:o.mediaStreamTrack.id}]});if(d.layers=bc(d.width,d.height,a),!this.engine||this.engine.isClosed)throw new ss("cannot publish track when not connected");const l=(yield Promise.all([this.engine.addTrack(d),(()=>Cn(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,o,s,a),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:a,trackInfo:l})}))}unpublishTrack(e,t){return Cn(this,void 0,void 0,(function*(){var i,n;if(ba(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.debug("awaiting publish promise before attempting to unpublish",_s(e)),yield t)}const r=this.getPublicationForTrack(e),s=r?_s(r):void 0;if(this.log.info("unpublishing track",s),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",s);(e=r.track).off(es.Muted,this.onTrackMuted),e.off(es.Unmuted,this.onTrackUnmuted),e.off(es.Ended,this.handleTrackEnded),e.off(es.UpstreamPaused,this.onTrackUpstreamPaused),e.off(es.UpstreamResumed,this.onTrackUpstreamResumed),e.off(es.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let a=!1;const o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Xo.FAILED&&o)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",a=!0);try{a=this.engine.removeTrack(o)}catch(e){this.log.warn(e),a=!0}if(Ca(e)){for(const t of e.simulcastCodecs){const e=B(t,2)[1];if(e.sender){try{a=this.engine.removeTrack(e.sender)}catch(e){this.log.warn(e),a=!0}e.sender=void 0}}e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},s),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Us.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Us.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(Xr.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r}))}unpublishTracks(e){return Cn(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Cn(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 jr(((n,r)=>Cn(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=>Cn(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===Us.Source.ScreenShare||t.source===Us.Source.ScreenShareAudio||!wa(t)&&!Ca(t)||t.isUserProvided||(this.log.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),n()}catch(e){e instanceof Error?r(e):r(new Error(String(e)))}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Cn(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?Rc.RELIABLE:Rc.LOSSY,r=i.reliable?St.RELIABLE:St.LOSSY,s=i.destinationIdentities,a=i.topic;let o=new Pt({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:a});const c=new Tt({kind:r,value:{case:"user",value:o}});yield t.engine.sendDataPacket(c,n)}()}))}publishDtmf(e,t){return Cn(this,void 0,void 0,(function*(){const i=new Tt({kind:St.RELIABLE,value:{case:"sipDtmf",value:new It({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Rc.RELIABLE)}))}sendChatMessage(e,t){return Cn(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 Tt({value:{case:"chatMessage",value:new At(Object.assign(Object.assign({},i),{timestamp:A.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,Rc.RELIABLE),this.emit(Xr.ChatMessage,i),i}))}editChatMessage(e,t){return Cn(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new Tt({value:{case:"chatMessage",value:new At(Object.assign(Object.assign({},i),{timestamp:A.parse(i.timestamp),editTimestamp:A.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,Rc.RELIABLE),this.emit(Xr.ChatMessage,i),i}))}sendText(e,t){return Cn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)}))}streamText(e){return Cn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(e)}))}sendFile(e,t){return Cn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)}))}streamBytes(e){return Cn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)}))}performRpc(e){return this.rpcClientManager.performRpc(e).then((e=>{let t=B(e,2);return t[0],t[1]}))}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(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()}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 r=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},_s(n)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}})),!0)}setActiveAgent(e){var t,i,n,r;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===(r=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new ma),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(wa(n)||Ca(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return Cn(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>B(t,1)[0].source===e));if(t)return t[1];yield Vs(20)}}))}publishDataTrack(e){return Cn(this,void 0,void 0,(function*(){const t=new Cd(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t}))}}class Hd extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class Wd extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,n;super.set(e,t);const r=null===(i=this.pending)||void 0===i?void 0:i.get(e);if(r){for(const e of r)e.isResolved||null===(n=e.resolve)||void 0===n||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return Cn(this,void 0,void 0,(function*(){const i=this.get(e);if(void 0!==i)return i;if(null==t?void 0:t.aborted)throw new Hd("The operation was aborted.",t.reason);const n=new ma(void 0,(()=>{const t=this.pending.get(e);if(!t)return;const i=t.indexOf(n);-1!==i&&t.splice(i,1),0===t.length&&this.pending.delete(e)})),r=this.pending.get(e);if(r?r.push(n):this.pending.set(e,[n]),t){const e=()=>{var e;n.isResolved||null===(e=n.reject)||void 0===e||e.call(n,new Hd("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0}),n.promise.finally((()=>{t.removeEventListener("abort",e)}))}return n.promise}))}}class zd extends Ud{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(es.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 bi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Nt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(es.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Ud.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ud.SubscriptionStatus.Subscribed:Ud.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ud.PermissionStatus.Allowed:Ud.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||(Pa(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Pa(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:Ns.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(es.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(es.VisibilityChanged,this.handleVisibilityChange),n.off(es.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(es.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(es.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(es.VisibilityChanged,this.handleVisibilityChange),e.on(es.Ended,this.handleEnded),this.emit(es.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(es.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?es.Muted:es.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(es.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(es.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Pa(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ci({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Us.Kind.Video){let t=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(t){Os(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=function(e,t){var i;return null===(i=e.layers)||void 0===i?void 0:i.find((e=>e.quality===t))}(this.trackInfo,this.requestedMaxQuality);e&&Os(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.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:Ns.HIGH})),e.quality=Ns.HIGH)}this.emit(es.UpdateSettings,e)}}class Gd extends qd{static fromParticipantInfo(e,t,i,n){return new Gd(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,t.dataTracks.map((e=>{const i=go.from(e);return new ed(i,n,{publisherIdentity:t.identity})})),t.clientProtocol)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,r,s,a){let o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:ht.STANDARD,c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],d=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0;super(t,i||"",n,r,s,a,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new Wd(c.map((e=>[e.info.name,e]))),this.volumeMap=new Map,this.clientProtocol=d}addTrackPublication(e){super.addTrackPublication(e),e.on(es.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),_s(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)})),e.on(es.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(es.SubscriptionPermissionChanged,(t=>{this.emit(Xr.TrackSubscriptionPermissionChanged,e,t)})),e.on(es.SubscriptionStatusChanged,(t=>{this.emit(Xr.TrackSubscriptionStatusChanged,e,t)})),e.on(es.Subscribed,(t=>{this.emit(Xr.TrackSubscribed,t,e)})),e.on(es.Unsubscribed,(t=>{this.emit(Xr.TrackUnsubscribed,t,e)})),e.on(es.SubscriptionFailed,(t=>{this.emit(Xr.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]:Us.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]:Us.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,r,s){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach((t=>{a||e.kind!==t.kind.toString()||(a=t)})),!a)return 0===s?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(Xr.TrackSubscriptionFailed,t)):(void 0===s&&(s=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,r,s-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),_s(a))),void this.emit(Xr.TrackSubscriptionFailed,t);let o;return o="video"===e.kind?new Ja(e,t,n,r):new Nd(e,t,n,this.audioContext,this.audioOutput),o.source=a.source,o.isMuted=a.isMuted,o.setMediaStream(i),o.start(),a.setTrack(o),this.volumeMap.has(a.source)&&Ea(o)&&Ta(o)&&o.setVolume(this.volumeMap.get(a.source)),a}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,r;let s=this.getTrackPublicationBySid(e.sid);if(s)s.updateInfo(e);else{const t=Us.kindFromProto(e.type);if(!t)return;s=new zd(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName}),s.updateInfo(e),i.set(e.sid,s);const a=Array.from(this.trackPublications.values()).find((e=>e.source===(null==s?void 0:s.source)));a&&s.source!==Us.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:_s(a),newTrack:_s(s)})),this.addTrackPublication(s)}t.set(e.sid,s)})),this.trackPublications.forEach((e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),_s(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(Xr.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const n=i.track;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case Us.Kind.Audio:this.audioTrackPublications.delete(e);break;case Us.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(Xr.TrackUnpublished,i)}setAudioOutput(e){return Cn(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;Ta(i.track)&&Ea(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const i of this.dataTracks.entries()){var t=B(i,2);const n=t[0];e===t[1].info.sid&&this.dataTracks.delete(n)}}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)}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(Vd||(Vd={}));class Jd extends Dn.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,r,s,a,o;if(super(),t=this,this.state=Vd.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new d,this.isVideoPlaybackBlocked=!1,this.log=kn,this.bufferedEvents=[],this.isResuming=!1,this.connect=(e,t,i)=>Cn(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!qs()&&!Ks())throw Xs()?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 r=yield this.disconnectLock.lock();if(this.state===Vd.Connected)return this.log.info("already connected to room ".concat(this.name)),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(Vd.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==Da(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Zs(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Dc(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",{error:e})})));const s=(n,a,o)=>Cn(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==r||r();try{if(yield to.getInstance().getBackOffPromise(e),l.signal.aborted)throw ts.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=o?o:e,t,i,l),this.abortController=void 0,n()}catch(t){if(this.regionUrlProvider&&t instanceof ts&&t.reason!==Jr.Cancelled&&t.reason!==Jr.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof ts&&(401===e.status||e.reason===Jr.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void a(e)}[Jr.InternalError,Jr.ServerUnreachable,Jr.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),to.getInstance().addFailedConnectionAttempt(e)),i&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i)),this.recreateEngine(!0),yield s(n,a,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,va(t)),a(t))}else{let e=it.UNKNOWN_REASON;t instanceof ts&&(e=va(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),a(t)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ma(((e,t)=>{s(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,r,s)=>Cn(this,void 0,void 0,(function*(){var a;const o=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,clientInfoCapabilities:qa(null!==(a=r.frameMetadata)&&void 0!==a?a:r.packetTrailer)||this.e2eeManager?[Vt.CAP_PACKET_TRAILER]:void 0,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},s.signal,!r.singlePeerConnection),c=o.joinResponse,d=o.serverInfo;if(this.serverInfo=d,!d.version)throw new rs("unknown server version");return"0.15.1"===d.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),r.dynacast=!1),c})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",{error:e})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>Cn(this,void 0,void 0,(function*(){var r,s;this.state===Vd.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},$o),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($r.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=n.signal.aborted?ts.cancelled("Signal connection aborted"):ts.serverUnreachable("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof ts&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",{error:e}),t}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),ts.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}$s()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),$s()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Vd.Connected),this.emit($r.Connected),to.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return Cn(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,r;const s=yield e.disconnectLock.lock();try{if(e.state===Vd.Disconnected)return void e.log.debug("already disconnected");if(e.log.info("disconnect from room"),e.state===Vd.Connecting||e.state===Vd.Reconnecting||e.isResuming){const t="Abort connection attempt due to user initiated disconnect";e.log.warn(t),null===(i=e.abortController)||void 0===i||i.abort(t),null===(r=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,ts.cancelled("Client initiated disconnect")),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,it.CLIENT_INITIATED),e.engine=void 0}finally{s()}}()}))},this.onPageLeave=()=>Cn(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()})),this.startAudio=()=>Cn(this,void 0,void 0,(function*(){const e=[],t=qr();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=pa();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.startAudio()))})),document.body.append(i),this.once($r.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=()=>Cn(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.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Vd.Reconnecting)&&this.emit($r.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>Cn(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),{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",{error:e})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:e.serverRegion})}catch(e){return}this.setAndEmitConnectionState(Vd.Connected),this.emit($r.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{var t;for(const i of e){if(i.identity===this.localParticipant.identity){this.localParticipant.updateInfo(i);continue}""===i.identity&&(i.identity=null!==(t=this.sidToIdentity.get(i.sid))&&void 0!==t?t:"");let e=this.remoteParticipants.get(i.identity);i.state===ut.DISCONNECTED?this.handleParticipantDisconnected(i.identity,e):this.getOrCreateParticipant(i.identity,i)}const i=new Map(e.filter((e=>e.identity!==this.localParticipant.identity)).map((e=>[e.identity,e.dataTracks.map((e=>go.from(e)))])));this.incomingDataTrackManager.receiveSfuPublicationUpdates(i)},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($r.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($r.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=Us.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(Xr.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected($r.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,t)=>{const i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.rpcServerManager.handleIncomingRpcRequest(e.participantIdentity,t)}else if("rpcResponse"===e.value.case){const t=e.value.value;switch(t.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(t.requestId,t.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(t.requestId,Id.fromProto(t.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(t.value.case),this.logContext)}}else"rpcAck"===e.value.case&&this.rpcClientManager.handleIncomingRpcAck(e.value.value.requestId)},this.handleUserPacket=(e,t,i,n)=>{this.emit($r.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(Xr.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit($r.SipDTMFReceived,t,e),null==e||e.emit(Xr.SipDTMFReceived,t)},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),r=function(e,t){return e.segments.map((e=>{let i=e.id,n=e.text,r=e.language,s=e.startTime,a=e.endTime,o=e.final;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return o?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(a.toString()),final:o,language:r,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit(es.TranscriptionReceived,r),null==i||i.emit(Xr.TranscriptionReceived,r,n),this.emit($r.TranscriptionReceived,r,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const t=e.id,i=e.timestamp,n=e.message,r=e.editTimestamp;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}(t);this.emit($r.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit($r.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit($r.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",{error:e}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit($r.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit($r.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit($r.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Cn(this,void 0,void 0,(function*(){var e;"iOS"!==(null===(e=qr())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit($r.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected($r.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected($r.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.getRemoteParticipantClientProtocol=e=>{var t,i;return null!==(i=null===(t=this.remoteParticipants.get(e))||void 0===t?void 0:t.clientProtocol)&&void 0!==i?i:0},this.onLocalParticipantMetadataChanged=e=>{this.emit($r.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit($r.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit($r.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit($r.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit($r.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=>Cn(this,void 0,void 0,(function*(){var t,i,n,r,s,a;if(null===(t=e.track)||void 0===t||t.on(es.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(es.Restarted,this.onLocalTrackRestarted),null===(s=null===(r=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===r?void 0:r.onPublish)||void 0===s||s.call(r,this),this.emit($r.LocalTrackPublished,e,this.localParticipant),wa(e.track)){(yield e.track.checkForSilence())&&this.emit($r.LocalAudioSilenceDetected,e)}const o=yield null===(a=e.track)||void 0===a?void 0:a.getDeviceId(!1),c=Ms(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit($r.ActiveDeviceChanged,c,o))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(es.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(es.Restarted,this.onLocalTrackRestarted),this.emit($r.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>Cn(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=Ms(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active")),this.localParticipant.activeDeviceMap.set(i,t),this.emit($r.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit($r.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit($r.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit($r.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit($r.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Yo),e),this.log=yn(null!==(i=this.options.loggerName)&&void 0!==i?i:fn.Room,(()=>this.logContext)),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Jo),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Qo),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Go),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Oc,this.outgoingDataStreamManager=new Fc(this.engine,this.log),this.incomingDataTrackManager=new pd({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",(e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)})).on("trackPublished",(e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit($r.DataTrackPublished,e.track),null===(t=this.remoteParticipants.get(e.track.publisherIdentity))||void 0===t||t.addRemoteDataTrack(e.track))})).on("trackUnpublished",(e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit($r.DataTrackUnpublished,e.sid),null===(t=this.remoteParticipants.get(e.publisherIdentity))||void 0===t||t.removeRemoteDataTrack(e.sid))})),this.outgoingDataTrackManager=new Pd({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",(e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)})).on("sfuUnpublishRequest",(e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)})).on("trackPublished",(e=>{this.emit($r.LocalDataTrackPublished,e.track)})).on("trackUnpublished",(e=>{this.emit($r.LocalDataTrackUnpublished,e.sid)})).on("packetAvailable",(e=>{let t=e.handle,i=e.bytes;this.engine.sendLossyBytes(i,Rc.DATA_TRACK_LOSSY,"wait").finally((()=>this.outgoingDataTrackManager.handlePacketSendComplete(t)))})),this.registerRpcDataStreamHandler(),this.rpcClientManager=new Od(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,(()=>{var e,t;return null===(t=null===(e=this.engine.latestJoinResponse)||void 0===e?void 0:e.serverInfo)||void 0===t?void 0:t.version})),this.rpcClientManager.on("sendDataPacket",(e=>{let t=e.packet;var i;null===(i=this.engine)||void 0===i||i.sendDataPacket(t,Rc.RELIABLE)})),this.rpcServerManager=new xd(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",(e=>{let t=e.packet;var i;null===(i=this.engine)||void 0===i||i.sendDataPacket(t,Rc.RELIABLE)})),this.disconnectLock=new d,this.localParticipant=new Kd("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(null!==(n=this.e2eeManager)&&void 0!==n?n:null),this.outgoingDataTrackManager.updateE2eeManager(null!==(r=this.e2eeManager)&&void 0!==r?r:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",ga(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",ga(this.options.audioCaptureDefaults.deviceId)),(null===(s=this.options.audioOutput)||void 0===s?void 0:s.deviceId)&&this.switchActiveDevice("audiooutput",ga(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),$s()){const e=new AbortController;let t;if(Jd.cleanupRegistry){const i=new WeakRef(this);t=()=>{const e=i.deref();e&&e.handleDeviceChange()},Jd.cleanupRegistry.register(this,(()=>{e.abort()}))}else t=this.handleDeviceChange;null===(o=null===(a=navigator.mediaDevices)||void 0===a?void 0:a.addEventListener)||void 0===o||o.call(a,"devicechange",t,{signal:e.signal})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return Cn(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity))}finally{t()}}))}setupE2EE(){var e,t;const i=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new Xa(n,i),this.e2eeManager.on(Na.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit($r.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(Na.EncryptionError,((e,t)=>{const i=t?this.getParticipantByIdentity(t):void 0;this.emit($r.EncryptionError,e,i)})),null===(e=this.e2eeManager)||void 0===e||e.setup(this),null===(t=this.e2eeManager)||void 0===t||t.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=null!==(e=this.options.frameMetadata)&&void 0!==e?e:this.options.packetTrailer;this.frameMetadataManager=new eo(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,i;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:null===(t=this.localParticipant)||void 0===t?void 0:t.identity,participantID:null===(i=this.localParticipant)||void 0===i?void 0:i.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 this.state===Vd.Disconnected?jr.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?jr.resolve(this.roomInfo.sid):new jr(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(Zr.RoomUpdate,i),e(t.sid))};this.engine.on(Zr.RoomUpdate,i),this.once($r.Disconnected,(()=>{this.engine.off(Zr.RoomUpdate,i),t(new ss("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.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new Pc(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Zr.ParticipantUpdate,this.handleParticipantUpdates).on(Zr.RoomUpdate,this.handleRoomUpdate).on(Zr.SpeakersChanged,this.handleSpeakersChanged).on(Zr.StreamStateChanged,this.handleStreamStateUpdate).on(Zr.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Zr.SubscriptionError,this.handleSubscriptionError).on(Zr.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Zr.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Zr.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(Zr.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Zr.DataPacketReceived,this.handleDataPacket).on(Zr.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(Vd.SignalReconnecting)&&this.emit($r.SignalReconnecting)})).on(Zr.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Vd.Connected)&&this.emit($r.Reconnected)})).on(Zr.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Vd.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Zr.Restarting,this.handleRestarting).on(Zr.Restarted,this.handleRestarted).on(Zr.SignalRestarted,this.handleSignalRestarted).on(Zr.Offline,(()=>{this.setAndEmitConnectionState(Vd.Reconnecting)&&this.emit($r.Reconnecting)})).on(Zr.DCBufferStatusChanged,((e,t)=>{this.emit($r.DCBufferStatusChanged,e,t)})).on(Zr.LocalTrackSubscribed,(e=>{this.handleLocalTrackSubscribed(e)})).on(Zr.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($r.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)})).on(Zr.PublishDataTrackResponse,(e=>{e.info?this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==mt.NONE}}):this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(Zr.UnPublishDataTrackResponse,(e=>{e.info?this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle):this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(Zr.DataTrackSubscriberHandles,(e=>{const t=new Map(Object.entries(e.subHandles).map((e=>{let t=B(e,2),i=t[0],n=t[1];return[parseInt(i,10),n.trackSid]})));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)})).on(Zr.DataTrackPacketReceived,(e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}})).on(Zr.Joined,(e=>{const t=new Map(e.otherParticipants.map((e=>[e.identity,e.dataTracks.map((e=>go.from(e)))])));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)})).on(Zr.TokenRefreshed,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)})).on(Zr.ServerRegionsReported,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Mc})})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>Cn(this,void 0,void 0,(function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null})),resetAttempts:()=>{var e;return null===(e=this.regionUrlProvider)||void 0===e?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return no.getInstance().getDevices(e,t)}prepareConnection(e,t){return Cn(this,void 0,void 0,(function*(){if(this.state===Vd.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(Zs(new URL(e))&&t){this.regionUrlProvider=new Dc(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Vd.Disconnected&&(this.regionUrl=i,yield fetch(fa(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(fa(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",{error:e})}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Cn(this,void 0,void 0,(function*(){let i,n=()=>Cn(this,void 0,void 0,(function*(){}));switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":i=new Ji({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Ji({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Ji({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Ji({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=()=>Cn(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ji({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Cn(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ji({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 Ji({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Cn(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Ri({reason:it.CLIENT_INITIATED,action:Pi.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Ji({scenario:{case:"subscriberBandwidth",value:ya(t)}});break;case"leave-full-reconnect":i=new Ji({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 Cn(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var r,s,a,o,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!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===Us.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 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("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Us.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 r=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&&r&&(h=!0)}else if("audiooutput"===e){if(h=!0,!Ws()&&!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!==(a=yield no.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==a?a:""),null!==(o=(l=i.options).audioOutput)&&void 0!==o||(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($r.ActiveDeviceChanged,e,t)),u}()}))}setupLocalParticipantEvents(){this.localParticipant.on(Xr.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Xr.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Xr.AttributesChanged,this.onLocalAttributesChanged).on(Xr.TrackMuted,this.onLocalTrackMuted).on(Xr.TrackUnmuted,this.onLocalTrackUnmuted).on(Xr.LocalTrackPublished,this.onLocalTrackPublished).on(Xr.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Xr.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Xr.MediaDevicesError,this.onMediaDevicesError).on(Xr.AudioStreamAcquired,this.startAudio).on(Xr.ChatMessage,this.onLocalChatMessageSent).on(Xr.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally((()=>t.close())):null==t||t.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===Vd.Connecting||this.state===Vd.Reconnecting){const n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map((e=>e.id))}),this.onTrackAdded(e,t,i),r()},r=()=>{this.off($r.Reconnected,n),this.off($r.Connected,n),this.off($r.Disconnected,r)};return this.once($r.Reconnected,n),this.once($r.Connected,n),void this.once($r.Disconnected,r)}if(this.state===Vd.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected");if("ended"===e.readyState)return void this.log.debug("skipping incoming track as it already ended");const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),r=n[0];let s=n[1],a=e.id;if(s&&s.startsWith("TR")&&(a=s),r===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant");const o=Array.from(this.remoteParticipants.values()).find((e=>e.sid===r));if(!o)return void(r.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r)));if(!a.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r));a=e}let c;a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(s,", trackId: ").concat(a),{remoteParticipantID:r,streamId:s,trackId:a}),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=o.addSubscribedMediaTrack(e,a,t,i,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit($r.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(o.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){const t=()=>this.localParticipant.getTrackPublications().find((t=>t.trackSid===e)),i=t();if(i)return void this.emitLocalTrackSubscribed(i);this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});let n;const r=t=>{t.trackSid===e&&(s(),this.emitLocalTrackSubscribed(t))},s=()=>{clearTimeout(n),this.localParticipant.off(Xr.LocalTrackPublished,r),this.off($r.Disconnected,s)};this.localParticipant.on(Xr.LocalTrackPublished,r),this.once($r.Disconnected,s),n=setTimeout((()=>{s();const i=t();i?this.emitLocalTrackSubscribed(i):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})}),1e4)}emitLocalTrackSubscribed(e){this.localParticipant.emit(Xr.LocalTrackSubscribed,e),this.emitWhenConnected($r.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i,n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==Vd.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,r;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===(r=t.track)||void 0===r||r.stopMonitor()})),this.localParticipant.off(Xr.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Xr.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Xr.AttributesChanged,this.onLocalAttributesChanged).off(Xr.TrackMuted,this.onLocalTrackMuted).off(Xr.TrackUnmuted,this.onLocalTrackUnmuted).off(Xr.LocalTrackPublished,this.onLocalTrackPublished).off(Xr.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Xr.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Xr.MediaDevicesError,this.onMediaDevicesError).off(Xr.AudioStreamAcquired,this.startAudio).off(Xr.ChatMessage,this.onLocalChatMessageSent).off(Xr.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),$s()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=null===(i=navigator.mediaDevices)||void 0===i?void 0:i.removeEventListener)||void 0===n||n.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Vd.Disconnected),this.emit($r.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit($r.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return Cn(this,void 0,void 0,(function*(){var e,t,i;const n=no.getInstance().previousDevices,r=yield no.getInstance().getDevices(void 0,!1),s=qr();if("Chrome"===(null==s?void 0:s.name)&&"iOS"!==s.os)for(let e of r){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($r.ActiveDeviceChanged,e.kind,e.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let s of a){const a=Is(s),o=this.localParticipant.getTrackPublication(a);if(o&&(null===(e=o.track)||void 0===e?void 0:e.isUserProvided))continue;const c=r.filter((e=>e.kind===s)),d=this.getActiveDevice(s);d===(null===(t=n.filter((e=>e.kind===s))[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(s,c[0].deviceId):"audioinput"===s&&!Qs()||"videoinput"===s||!(c.length>0)||c.find((e=>e.deviceId===this.getActiveDevice(s)))||"audiooutput"===s&&Qs()||(yield this.switchActiveDevice(s,c[0].deviceId))}}))}acquireAudioContext(){return Cn(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=Ps())&&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(),Vs(200)])}catch(e){this.log.warn("Could not resume audio context",{error:e})}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit($r.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?Gd.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new Gd(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)))),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($r.ParticipantConnected,i),i.on(Xr.TrackPublished,(e=>{this.emitWhenConnected($r.TrackPublished,e,i)})).on(Xr.TrackSubscribed,((e,t)=>{e.kind===Us.Kind.Audio?(e.on(es.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(es.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===Us.Kind.Video&&(e.on(es.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(es.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected($r.TrackSubscribed,e,t,i)})).on(Xr.TrackUnpublished,(e=>{this.emit($r.TrackUnpublished,e,i)})).on(Xr.TrackUnsubscribed,((e,t)=>{this.emit($r.TrackUnsubscribed,e,t,i)})).on(Xr.TrackMuted,(e=>{this.emitWhenConnected($r.TrackMuted,e,i)})).on(Xr.TrackUnmuted,(e=>{this.emitWhenConnected($r.TrackUnmuted,e,i)})).on(Xr.ParticipantMetadataChanged,(e=>{this.emitWhenConnected($r.ParticipantMetadataChanged,e,i)})).on(Xr.ParticipantNameChanged,(e=>{this.emitWhenConnected($r.ParticipantNameChanged,e,i)})).on(Xr.AttributesChanged,(e=>{this.emitWhenConnected($r.ParticipantAttributesChanged,e,i)})).on(Xr.ConnectionQualityChanged,(e=>{this.emitWhenConnected($r.ConnectionQualityChanged,e,i)})).on(Xr.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected($r.ParticipantPermissionsChanged,e,i)})).on(Xr.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected($r.TrackSubscriptionStatusChanged,e,t,i)})).on(Xr.TrackSubscriptionFailed,((e,t)=>{this.emit($r.TrackSubscriptionFailed,e,i,t)})).on(Xr.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected($r.TrackSubscriptionPermissionChanged,e,t,i)})).on(Xr.Active,(()=>{this.emitWhenConnected($r.ParticipantActive,i),i.kind===ht.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(),i=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ra(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(Md,((e,t)=>Cn(this,[e,t],void 0,(function(e,t){var i=this;let n=t.identity;return function*(){var t;const r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield i.rpcServerManager.handleIncomingDataStream(e,n,r)}()})))),this.incomingDataStreamManager.registerTextStreamHandler(Dd,((e,t)=>Cn(this,[e,t],void 0,(function(e,t){var i=this;let n=t.identity;return function*(){var t;const r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield i.rpcClientManager.handleIncomingDataStream(e,n,r)}()}))))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=hs.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,it.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&hs.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===Vd.Connected),this.emit($r.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let t=B(e,2),i=t[0],n=t[1];this.emit(i,...n)})),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===Vd.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Vd.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return Cn(this,void 0,void 0,(function*(){var t,i,n,r;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ot({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:A.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new lt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit($r.SignalConnected),this.emit($r.Connected),this.setAndEmitConnectionState(Vd.Connected),s.video){const e=new Fd(Us.Kind.Video,new ft({source:Xe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:$e.AUDIO,name:"video-dummy"}),new vc(s.useRealTracks&&(null===(t=window.navigator.mediaDevices)||void 0===t?void 0:t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:ua(160*(null!==(i=a.aspectRatios[0])&&void 0!==i?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(Xr.LocalTrackPublished,e)}if(s.audio){const e=new Fd(Us.Kind.Audio,new ft({source:Xe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:$e.AUDIO}),new rc(s.useRealTracks&&(null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:pa(),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(Xr.LocalTrackPublished,e)}for(let e=0;e<a.count-1;e+=1){let t=new lt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:ut.ACTIVE,tracks:[],joinedAt:A.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(a.video){const n=ua(160*(null!==(r=a.aspectRatios[e%a.aspectRatios.length])&&void 0!==r?r:1),160,!1,!0),s=new ft({source:Xe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:$e.AUDIO});i.addSubscribedMediaTrack(n,s.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,s]}if(a.audio){const e=pa(),n=new ft({source:Xe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:$e.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==$r.ActiveSpeakersChanged&&e!==$r.TranscriptionReceived){const t=Qd(i).filter((e=>void 0!==e));e!==$r.TrackSubscribed&&e!==$r.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(e),{event:e,args:t}),this.log.debug("room event ".concat(e),{event:e,args:t})}return super.emit(e,...i)}}function Qd(e){return e.map((e=>{if(e)return Array.isArray(e)?Qd(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}var Yd;Jd.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef&&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"}(Yd||(Yd={}));Dn.EventEmitter;Dn.EventEmitter;new TextEncoder,new TextDecoder;class $d extends Error{constructor(e,t){var i;super(e,t),j(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}j($d,"code","ERR_JOSE_GENERIC");j(class extends $d{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),j(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");j(class extends $d{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),j(this,"code","ERR_JWT_EXPIRED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_EXPIRED");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),j(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");j(class extends $d{constructor(){super(...arguments),j(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),j(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),j(this,Symbol.asyncIterator,void 0),j(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),j(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");j(class extends $d{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),j(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const Xd=(e,t)=>"error"===e||t,Zd=(e,t)=>{const i=(new Date).toISOString(),n=t?.source?`[${t.source}]`:"";return`${i} ${t?.level?`[${t.level.toUpperCase()}]`:""} ${n}`},el=e=>({log:(t,i)=>{if(!Xd(i?.level||"debug",e))return;const n=Zd(0,{...i,level:"debug"});console.log(n,t,i?.error||"")},info:(t,i)=>{if(!Xd(i?.level||"info",e))return;const n=Zd(0,{...i,level:"info"});console.info(n,t,i?.error||"")},warn:(t,i)=>{if(!Xd(i?.level||"warn",e))return;const n=Zd(0,{...i,level:"warn"});console.warn(n,t,i?.error||"")},error:(t,i)=>{if(!Xd(i?.level||"error",e))return;const n=Zd(0,{...i,level:"error"});console.error(n,t,i?.error||"")}});var tl,il,nl,rl,sl,al,ol,cl,dl,ll,ul,hl,pl,ml,gl,fl,vl,kl,yl,bl,Tl,Sl;const Cl=.02,wl=.001;class El extends n.EventEmitter{constructor(t=!1){super(),tl.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",this.logger=el(t),this.logger.log("Initializing LiveKitAnalytics",{source:"LiveKitAnalytics"}),e(this,tl,"m",il).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((()=>{e(this,tl,"m",nl).call(this)}),5e3)}stopAnalyticsCollection(){this.analyticsInterval&&(clearInterval(this.analyticsInterval),this.analyticsInterval=null)}handleConnectionQualityChanged(t,i){const n=e(this,tl,"m",rl).call(this,t);this.connectionMetrics.quality=n,this.callStats.connectionQuality=n,e(this,tl,"m",sl).call(this),e(this,tl,"m",Tl).call(this,n);const r={quality:t,participant:i.identity||"unknown",metrics:{quality:n}};this.emit("connectionQualityChanged",r)}handleAudioPlaybackChanged(t){this.emit("audioPlaybackChanged",t),e(this,tl,"m",cl).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:Cl,minSpeakingDuration:100,dropoutThreshold:wl,dropoutDetectionDuration:500}}getCallAnalytics(e,t,i,n){const r=this.getPerformanceMetrics(),s=this.getAudioLevels();return{connectionStats:this.getConnectionStats(),audioMetrics:{...s,isPaused:n,volume:i},performanceMetrics:r,participants:e,trackStats:t,callStats:this.callStats,metadata:{callStartTime:this.callStartTime,isConnected:this.isConnected,isPaused:n,volume:i},callDuration:r.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(),e(this,tl,"m",il).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 Rl,Pl,Il,Ml,Dl,Al,_l,Ll,Ol,xl,Nl,Ul,Fl,jl,Bl,Vl,ql,Kl,Hl,Wl,zl,Gl,Jl,Ql,Yl;tl=new WeakSet,il=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}},nl=function(){if(this.room&&this.isConnected)try{if(e(this,tl,"m",sl).call(this),this.room?.localParticipant){const t=this.room.localParticipant.connectionQuality;if(t){const i=e(this,tl,"m",rl).call(this,t);this.connectionMetrics.quality=i,this.callStats.connectionQuality=i}}e(this,tl,"m",cl).call(this),e(this,tl,"m",ul).call(this),e(this,tl,"m",Sl).call(this);const t=this.getPerformanceMetrics();this.emit("analyticsUpdated",{connectionStats:this.getConnectionStats(),audioMetrics:this.getAudioLevels(),performanceMetrics:t,callDuration:t.callDuration})}catch(e){}},rl=function(e){switch(e){case Bd.Excellent:return"excellent";case Bd.Good:return"good";case Bd.Poor:return"poor";default:return"lost"}},sl=function(){e(this,tl,"m",al).call(this)},al=function(){const t=this.room?.localParticipant?.connectionQuality;if(!t)return;const i=e(this,tl,"m",ol).call(this,t);0===this.connectionMetrics.latency&&(this.connectionMetrics.latency=i.latency,this.connectionMetrics.packetLoss=i.packetLoss,this.connectionMetrics.bandwidth=i.bandwidth)},ol=function(e){switch(e){case Bd.Excellent:return{latency:10,packetLoss:0,bandwidth:1e6};case Bd.Good:return{latency:50,packetLoss:.1,bandwidth:5e5};case Bd.Poor:return{latency:200,packetLoss:1,bandwidth:1e5};default:return{latency:1e3,packetLoss:10,bandwidth:0}}},cl=function(){if(!this.room)return;const t=Date.now(),i=this.room.activeSpeakers;let n=0,r=0;for(const s of i)s===this.room.localParticipant?n=e(this,tl,"m",dl).call(this,s,t):r=Math.max(r,e(this,tl,"m",ll).call(this,s,t));this.audioMetrics.userAudioLevel=n,this.audioMetrics.agentAudioLevel=r},dl=function(t,i){const n=t.audioLevel||0,r=t.isSpeaking;return r&&!this.lastUserSpeakStart?(this.lastUserSpeakStart=i,this.lastUserInputTime=i):!r&&this.lastUserSpeakStart&&(this.audioMetrics.userSpeakingTime+=i-this.lastUserSpeakStart,this.lastUserSpeakStart=null),e(this,tl,"m",pl).call(this,"user",n,i),e(this,tl,"m",vl).call(this,"user",n,i),n},ll=function(t,i){const n=t.audioLevel||0,r=t.isSpeaking;if(r&&!this.lastAgentSpeakStart){if(this.lastAgentSpeakStart=i,this.lastUserInputTime){const e=i-this.lastUserInputTime;this.performanceMetrics.responseTime=e,this.lastUserInputTime=null}}else!r&&this.lastAgentSpeakStart&&(this.audioMetrics.agentSpeakingTime+=i-this.lastAgentSpeakStart,this.lastAgentSpeakStart=null);return e(this,tl,"m",pl).call(this,"agent",n,i),e(this,tl,"m",vl).call(this,"agent",n,i),n},ul=function(){this.room&&(this.callStats.participantCount=1+this.room.remoteParticipants.size,this.callStats.trackCount=e(this,tl,"m",hl).call(this))},hl=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},pl=function(t,i,n){"user"===t?e(this,tl,"m",ml).call(this,i,n):e(this,tl,"m",gl).call(this,i,n)},ml=function(t,i){const n=t>Cl;n&&!this.vadUserSpeakStart?this.vadUserSpeakStart=i:!n&&this.vadUserSpeakStart&&e(this,tl,"m",fl).call(this,"user",t,i)},gl=function(t,i){const n=t>Cl;n&&!this.vadAgentSpeakStart?this.vadAgentSpeakStart=i:!n&&this.vadAgentSpeakStart&&e(this,tl,"m",fl).call(this,"agent",t,i)},fl=function(e,t,i){const n="user"===e?this.vadUserSpeakStart:this.vadAgentSpeakStart;if(!n)return;const r=i-n;r>=100&&this.emit("voiceActivityDetected",{participant:e,duration:r,audioLevel:t,timestamp:i}),"user"===e?this.vadUserSpeakStart=null:this.vadAgentSpeakStart=null},vl=function(t,i,n){"user"===t?e(this,tl,"m",kl).call(this,i,n):e(this,tl,"m",yl).call(this,i,n)},kl=function(t,i){this.lastUserAudioLevel>Cl&&t<wl?this.userDropoutStartTime||(this.userDropoutStartTime=i):t>=wl&&this.userDropoutStartTime&&e(this,tl,"m",bl).call(this,"user",i),this.lastUserAudioLevel=t},yl=function(t,i){this.lastAgentAudioLevel>Cl&&t<wl?this.agentDropoutStartTime||(this.agentDropoutStartTime=i):t>=wl&&this.agentDropoutStartTime&&e(this,tl,"m",bl).call(this,"agent",i),this.lastAgentAudioLevel=t},bl=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},Tl=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()})}},Sl=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 $l extends n.EventEmitter{constructor(e=!1){super(),Rl.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.sourceNodes=new Map,this.clonedTracks=new Map,this.trackCaptureMap=new Map,this.workletReady=null,this.logger=el(e)}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||e(this,Rl,"m",Fl).call(this),!this.inputAnalyser)return 0;const t=this.inputAnalyser.frequencyBinCount,i=new Uint8Array(t);if(this.inputAnalyser.getByteFrequencyData(i),0===i.length)return 0;let n=0;for(const e of i)n+=e;const r=n/(255*i.length);return Math.max(0,Math.min(1,r))}catch{return 0}}setMicMuted(t){try{if(this.room?.localParticipant){const i=!t,n=this.room.localParticipant.setMicrophoneEnabled(i);return n&&"function"==typeof n.then?void n.then((()=>{e(this,Rl,"m",Pl).call(this,t?"micMuted":"micUnmuted",t)})).catch((i=>{e(this,Rl,"m",Il).call(this,t,i)})):void e(this,Rl,"m",Pl).call(this,t?"micMuted":"micUnmuted",t)}e(this,Rl,"m",Pl).call(this,t?"micMuted":"micUnmuted",t)}catch(i){e(this,Rl,"m",Il).call(this,t,i)}}isMicMuted(){try{let e;const t=this.room?.localParticipant?.getTrackPublication;if(t)try{e=t(Us.Source.Microphone)}catch{e=t("microphone")}if(e&&"boolean"==typeof e.isMuted)return e.isMuted}catch{}return!1}getInputByteFrequencyData(){try{if(this.inputAnalyser||e(this,Rl,"m",Fl).call(this),!this.inputAnalyser)return new Uint8Array(0);const t=this.inputAnalyser.frequencyBinCount,i=new Uint8Array(t);return this.inputAnalyser.getByteFrequencyData(i),i}catch{return new Uint8Array(0)}}getOutputByteFrequencyData(){try{if(this.outputAnalyser||e(this,Rl,"m",jl).call(this),!this.outputAnalyser)return new Uint8Array(0);const t=this.outputAnalyser.frequencyBinCount,i=new Uint8Array(t);return this.outputAnalyser.getByteFrequencyData(i),i}catch{return new Uint8Array(0)}}handleTrackSubscribed(t,i,n){t.kind===Us.Kind.Audio&&(e(this,Rl,"m",Ml).call(this,t,i,n),e(this,Rl,"m",Dl).call(this,t,i,n),e(this,Rl,"m",Ll).call(this,t,n))}handleLocalTrackPublished(t,i,n){t.kind===Us.Kind.Audio&&(e(this,Rl,"m",Ml).call(this,t,i,n),e(this,Rl,"m",Ll).call(this,t,n))}handleTrackUnsubscribed(t,i,n){t.kind===Us.Kind.Audio&&(e(this,Rl,"m",xl).call(this,t),"detach"in t&&"function"==typeof t.detach&&e(this,Rl,"m",Ol).call(this,t),this.emit("trackUnsubscribed",{track:t,publication:i,participant:n.identity||"unknown"}))}handleLocalTrackUnsubscribed(e,t,i){this.handleTrackUnsubscribed(e,t,i)}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(t){const i=t.callback||t.onData;if(!i)throw new Error('Audio capture requires either "callback" or "onData" option');this.audioCaptureEnabled=!0,this.audioCaptureOptions={source:t.source||"agent",trackSourceFilter:t.trackSourceFilter||"microphone",format:t.format||"opus-webm",chunkSize:t.chunkSize||100,bufferSize:t.bufferSize||2048,callback:i},e(this,Rl,"m",Vl).call(this)}disableAudioCapture(){this.audioCaptureEnabled=!1,e(this,Rl,"m",Jl).call(this),this.audioCaptureOptions=null,this.workletReady=null}cleanup(){e(this,Rl,"m",Jl).call(this);for(const e of this.audioElements)try{e?.parentNode?.removeChild&&e.parentNode.removeChild(e)}catch{}this.audioElements.clear(),this.trackStats.clear()}}var Xl,Zl,eu,tu,iu,nu,ru,su,au,ou,cu,du,lu,uu,hu,pu;Rl=new WeakSet,Pl=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)}`))}},Il=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)}`))},Ml=function(t,i,n){this.trackStats.set(t.sid||t.mediaStreamTrack?.id||"unknown",{trackId:t.sid||t.mediaStreamTrack?.id||"unknown",kind:t.kind,participant:n.identity||"unknown",subscriptionTime:Date.now(),publication:i,source:e(this,Rl,"m",Bl).call(this,i.source),muted:i.isMuted,enabled:i.isEnabled,dimensions:i.dimensions,simulcasted:i.simulcasted})},Dl=function(t,i,n){const r=t.attach();r&&(r.volume=this.volume,r.autoplay=!0,e(this,Rl,"m",Nl).call(this,r),this.audioElements.add(r),e(this,Rl,"m",Al).call(this,t,i,n),e(this,Rl,"m",_l).call(this,r),e(this,Rl,"m",Ll).call(this,t,n))},Al=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)},_l=function(e){e.style.display="none";try{document.body.appendChild(e)}catch{}},Ll=function(t,i){if(!this.audioCaptureEnabled||!this.audioCaptureOptions)return;const n=t.sid||t.mediaStreamTrack?.id||"unknown",r=(i.identity||"").toLowerCase().includes("agent")?"agent":"user",{source:s,format:a,trackSourceFilter:o}=this.audioCaptureOptions;if("both"!==s&&s!==r)return;const c=e(this,Rl,"m",Bl).call(this,t.source);"all"!==o&&o!==c||a&&e(this,Rl,"m",ql).call(this,n,i.identity||"unknown",r,a)},Ol=function(e){for(const t of e.detach()){try{t?.parentNode?.removeChild&&t.parentNode.removeChild(t)}catch{}this.audioElements.delete(t)}},xl=function(e){this.trackStats.delete(e.sid||e.mediaStreamTrack?.id||"unknown")},Nl=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")}))},Ul=function(){if(this.audioContext)return;const e=globalThis.AudioContext||globalThis.webkitAudioContext;if("function"==typeof e)try{const t=new e({sampleRate:16e3});this.audioContext=t,"suspended"===t.state&&t.resume().catch((e=>{this.logger.warn("Failed to auto-resume AudioContext:",{source:"LiveKitAudioManager",error:e})}))}catch{try{this.audioContext=new e}catch{this.audioContext=null}}},Fl=function(){try{if(e(this,Rl,"m",Ul).call(this),!this.audioContext)return;let t=null;const i=this.room?.localParticipant?.getTrackPublication;if(i)try{t=i(Us.Source.Microphone)}catch{t=i("microphone")}const n=t?.track?.mediaStreamTrack;if(!n)return;const r=new MediaStream([n]),s=this.audioContext.createMediaStreamSource(r),a=this.audioContext.createAnalyser();a.fftSize=256;{const e=s;e&&"function"==typeof e.connect&&e.connect(a)}this.inputAnalyser=a}catch{this.inputAnalyser=null}},jl=function(){try{if(e(this,Rl,"m",Ul).call(this),!this.audioContext)return;const t=this.audioElements.values().next().value;if(!t)return;const i=this.audioContext.createMediaElementSource(t),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}},Bl=function(e){switch(e){case Us.Source.Microphone:return"microphone";case Us.Source.Camera:return"camera";case Us.Source.ScreenShare:return"screen_share";case Us.Source.ScreenShareAudio:return"screen_share_audio";default:return"unknown"}},Vl=function(){if(!this.audioCaptureOptions)return;const{source:t,format:i,trackSourceFilter:n}=this.audioCaptureOptions;if(i)for(const[r,s]of this.trackStats.entries()){const a=s.participant.toLowerCase().includes("agent")?"agent":"user";if("both"!==t&&t!==a)continue;const o=s.source;"all"!==n&&n!==o||e(this,Rl,"m",ql).call(this,r,s.participant,a,i)}},ql=function(t,i,n,r){if(!this.audioCaptureOptions)return;const s=e(this,Rl,"m",Gl).call(this,t);if(!s?.mediaStreamTrack)return;if(this.trackCaptureMap.has(t))return void this.logger.log(`Skipping duplicate setup for ${n} (${t})`,{source:"LiveKitAudioManager"});const a=e(this,Rl,"m",Bl).call(this,s.source);this.trackCaptureMap.set(t,{participant:i,source:n});const o=s.mediaStreamTrack.clone(),c=new MediaStream([o]);this.clonedTracks.set(t,o),"opus-webm"===r?e(this,Rl,"m",Kl).call(this,{stream:c,trackId:t,participant:i,source:n,trackSource:a}):e(this,Rl,"m",Hl).call(this,{stream:c,trackId:t,participant:i,source:n,format:r,trackSource:a})},Kl=function(t){const{stream:i,trackId:n,participant:r,source:s,trackSource:a}=t;if(!this.audioCaptureOptions?.callback)return;const{chunkSize:o,callback:c}=this.audioCaptureOptions;try{const t=e(this,Rl,"m",Ql).call(this),d=new MediaRecorder(i,t?{mimeType:t}:{});d.ondataavailable=e=>{e.data.size>0&&e.data.arrayBuffer().then((e=>{const t={participant:r,source:s,timestamp:Date.now(),trackId:n,trackSource:a,format:"opus-webm"};c(e,t)}))},d.start(o),this.recorders.set(n,d)}catch(e){this.emit("error",new Error(`Failed to setup encoded audio capture: ${e instanceof Error?e.message:String(e)}`))}},Hl=function(t){const{stream:i,trackId:n,participant:r,source:s,format:a,trackSource:o}=t;if(!this.audioCaptureOptions?.callback)return;const{callback:c}=this.audioCaptureOptions,d=this.audioCaptureOptions.bufferSize||4096;try{if(e(this,Rl,"m",Ul).call(this),!this.audioContext)throw new Error("WebAudio is not supported in this environment");const t=this.audioContext;if("suspended"===t.state&&t.resume().catch((()=>{})),t.audioWorklet&&"function"==typeof t.audioWorklet.addModule)return void e(this,Rl,"m",Wl).call(this,{audioContext:t,stream:i,trackId:n,participant:r,source:s,trackSource:o,format:a,bufferSize:d,callback:c});e(this,Rl,"m",zl).call(this,{audioContext:t,stream:i,trackId:n,participant:r,source:s,trackSource:o,format:a,bufferSize:d,callback:c})}catch(e){this.emit("error",new Error(`Failed to setup PCM audio capture: ${e instanceof Error?e.message:String(e)}`))}},Wl=async function(t){const{audioContext:i,stream:n,trackId:r,participant:s,source:a,trackSource:o,format:c,bufferSize:d,callback:l}=t;try{this.workletReady||(this.workletReady=(async()=>{const e=new Blob(["\n class PCMProcessor extends AudioWorkletProcessor {\n constructor(options) {\n super();\n this.bufferSize = options.processorOptions.bufferSize || 4096;\n this.buffer = new Float32Array(this.bufferSize);\n this.index = 0;\n }\n\n process(inputs, outputs, parameters) {\n const input = inputs[0];\n if (!input || !input.length) return true;\n\n const channelData = input[0];\n if (!channelData) return true;\n\n for (let i = 0; i < channelData.length; i++) {\n this.buffer[this.index++] = channelData[i];\n\n if (this.index >= this.bufferSize) {\n const bufferToSend = this.buffer.slice(0, this.bufferSize);\n this.index = 0;\n this.port.postMessage(bufferToSend, [bufferToSend.buffer]);\n }\n }\n \n return true;\n }\n }\n registerProcessor('pcm-processor', PCMProcessor);\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);await i.audioWorklet.addModule(t),URL.revokeObjectURL(t)})()),await this.workletReady;const t=i.createMediaStreamSource(n),u=new AudioWorkletNode(i,"pcm-processor",{processorOptions:{bufferSize:d}});u.port.onmessage=t=>{const n=t.data,d="pcm-i16"===c?e(this,Rl,"m",Yl).call(this,n):n,u={participant:s,source:a,timestamp:Date.now(),trackId:r,trackSource:o,format:c,sampleRate:i.sampleRate,channels:1};try{l(d,u)}catch(e){this.logger.error(`Callback error for ${a}:`,{source:"LiveKitAudioManager",error:e})}},u.onprocessorerror=e=>{this.logger.error(`Worklet processor error for ${a} (${r}):`,{source:"LiveKitAudioManager",error:e})},t.connect(u),this.sourceNodes.set(r,t),this.processors.set(r,u);const h=i.createGain();h.gain.value=0,u.connect(h),h.connect(i.destination),this.processors.set(`${r}_gain`,h)}catch(i){this.logger.error(`AudioWorklet setup failed for ${a}:`,{source:"LiveKitAudioManager",error:i}),this.workletReady=null,e(this,Rl,"m",zl).call(this,t)}},zl=function(t){const{audioContext:i,stream:n,trackId:r,participant:s,source:a,trackSource:o,format:c,bufferSize:d,callback:l}=t;try{const t=i.createMediaStreamSource(n),u=i.createScriptProcessor(d,1,1);u.onaudioprocess=t=>{const i=t.inputBuffer,n=i.getChannelData(0),d="pcm-i16"===c?e(this,Rl,"m",Yl).call(this,n):new Float32Array(n),u={participant:s,source:a,timestamp:Date.now(),trackId:r,trackSource:o,format:c,sampleRate:i.sampleRate,channels:i.numberOfChannels};l(d,u)},t.connect(u),this.sourceNodes.set(r,t),this.processors.set(r,u);const h=i.createGain();h.gain.value=0,u.connect(h),h.connect(i.destination),this.processors.set(`${r}_gain`,h)}catch(e){this.logger.error(`ScriptProcessor setup failed for ${a}:`,{source:"LiveKitAudioManager",error:e})}},Gl=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},Jl=function(){this.workletReady=null;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{}this.processors.clear();for(const e of this.sourceNodes.values())try{e.disconnect()}catch{}this.sourceNodes.clear();for(const e of this.clonedTracks.values())try{e.stop()}catch{}if(this.clonedTracks.clear(),this.trackCaptureMap.clear(),this.audioContext){const e=this.audioContext;"closed"!==e.state&&e.close().catch((()=>{})),this.audioContext=null}},Ql=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""},Yl=function(e){const t=e.length,i=new Int16Array(t);for(let n=0;n<t;n++)i[n]=32767*Math.max(-1,Math.min(1,e[n]));return i};const mu=/iP(hone|ad|od)|iPhone/i;class gu extends n.EventEmitter{constructor(t,i,n=!1,r=!1){super(),Xl.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=t,this.accessToken=i,this.logger=el(n),this.isChatOnly=r,this.room=new Jd({adaptiveStream:!0,dynacast:!0,videoCaptureDefaults:{resolution:bs.h720.resolution},audioCaptureDefaults:{echoCancellation:!0,noiseSuppression:!0}}),e(this,Xl,"m",Zl).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++;"undefined"!=typeof navigator&&mu.test(navigator.userAgent)||this.room?.prepareConnection(this.lkUrl,this.accessToken);const e=Date.now();await(this.room?.connect(this.lkUrl,this.accessToken,{maxRetries:3})),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"),e(this,Xl,"m",pu).call(this)}async disconnect(){const t=Date.now();try{if(this.logger.log("LiveKitConnection.disconnect() - START",{source:"LiveKitConnection",error:{timestamp:t,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();e(this,Xl,"m",pu).call(this);const n=Date.now();this.logger.log("LiveKitConnection.disconnect() - COMPLETE",{source:"LiveKitConnection",error:{timestamp:n,cleanupDuration:n-i,totalDisconnectDuration:n-t}})}catch(e){const i=Date.now();this.logger.error("LiveKitConnection.disconnect() - FAILED",{source:"LiveKitConnection",error:{timestamp:i,timeSinceStart:i-t,error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}}),this.emit("connectionError",new Error(`LiveKit disconnection failed: ${e instanceof Error?e.message:String(e)}`))}}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(){e(this,Xl,"m",pu).call(this)}}Xl=new WeakSet,Zl=function(){this.room&&this.room.on($r.Connected,e(this,Xl,"m",eu).bind(this)).on($r.Disconnected,e(this,Xl,"m",tu).bind(this)).on($r.Reconnecting,e(this,Xl,"m",iu).bind(this)).on($r.Reconnected,e(this,Xl,"m",nu).bind(this)).on($r.ParticipantConnected,e(this,Xl,"m",ru).bind(this)).on($r.ParticipantDisconnected,e(this,Xl,"m",su).bind(this)).on($r.ParticipantAttributesChanged,e(this,Xl,"m",au).bind(this)).on($r.ConnectionStateChanged,e(this,Xl,"m",ou).bind(this)).on($r.SignalConnected,e(this,Xl,"m",cu).bind(this)).on($r.SignalReconnecting,e(this,Xl,"m",du).bind(this)).on($r.MediaDevicesError,e(this,Xl,"m",lu).bind(this)).on($r.ConnectionQualityChanged,e(this,Xl,"m",uu).bind(this)).on($r.DCBufferStatusChanged,e(this,Xl,"m",hu).bind(this))},eu=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}}),this.isChatOnly?this.logger.log("Chat-only session: skipping microphone enable",{source:"LiveKitConnection"}):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)}`))}},tu=function(){const t=Date.now();this.logger.log("Room Disconnected event fired (from LiveKit SDK) - TIMING",{source:"LiveKitConnection",error:{timestamp:t,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 r=Date.now();e(this,Xl,"m",pu).call(this);const s=Date.now();this.logger.log("Room Disconnected handler complete - TIMING",{source:"LiveKitConnection",error:{timestamp:s,cleanupDuration:s-r,totalHandlerDuration:s-t}})},iu=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")},nu=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")},ru=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)},su=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)},au=function(e,t){if("lk.agent.state"in e){const t=e["lk.agent.state"];void 0!==t&&this.emit("agentStateChanged",t)}},ou=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)},cu=function(){this.logger.log("Signal connection established",{source:"LiveKitConnection",error:{roomName:this.room?.name,state:this.room?.state}})},du=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}})},lu=function(e){this.logger.error("Media devices error",{source:"LiveKitConnection",error:{error:e.message,stack:e.stack,roomName:this.room?.name}})},uu=function(e,t){this.logger.log("Connection quality changed",{source:"LiveKitConnection",error:{participant:t.identity,quality:e,roomName:this.room?.name}})},hu=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}})},pu=function(){this.participants.clear(),this.isConnected=!1,this.isPaused=!1,this.hasEmittedConnected=!1};const fu="lk.chat";class vu extends n.EventEmitter{constructor(e=[],t=!1,i=!1){super(),this.room=null,this.tools=[],this.registeredMethods=new Set,this.fallbackMessageIdCounter=0,this.registeredChatTopics=new Set,this.tools=e,this.logger=el(t),this.isChatOnly=i}setRoom(e){this.room=e,e&&this.tools.length>0&&this.registerTools(),e&&this.registerChatStreamHandler(e)}registerChatStreamHandler(e){const t=this.isChatOnly?[fu,"lk.transcription"]:[fu];for(const i of t)if(!this.registeredChatTopics.has(i))try{e.registerTextStreamHandler(i,this.createChatStreamHandler(e)),this.registeredChatTopics.add(i),this.logger.log("Registered chat text-stream handler",{source:"LiveKitToolRegistry",error:{topic:i}})}catch(e){this.logger.error("Failed to register chat text-stream handler",{source:"LiveKitToolRegistry",error:{topic:i,error:e}})}}createChatStreamHandler(e){return async(t,i)=>{const n=e.localParticipant?.identity,r=i.identity===n?"user":"agent",s=t.info.id;let a="";for await(const e of t)a+=e,this.emitChatMessage({id:s,role:r,text:a,isFinal:!1});this.emitChatMessage({id:s,role:r,text:a,isFinal:!0})}}setTools(e){this.tools=Array.isArray(e)?e:[],this.room&&this.registerTools()}registerTools(){if(this.room&&0!==this.tools.length){this.unregisterAllTools();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),t));return JSON.stringify(n)}catch(t){return this.emit("rpcError",e.function_name,t),JSON.stringify({error:t instanceof Error?t.message:String(t)})}})),this.registeredMethods.add(e.function_name));this.emit("toolsRegistered",this.tools)}}unregisterAllTools(){if(this.room){for(const e of this.registeredMethods)try{this.room.unregisterRpcMethod(e)}catch{}this.registeredMethods.clear()}}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,vu.PAYLOAD_PREVIEW_LENGTH)}});const n=JSON.parse(i),r=n.event,s=n.content||n.data||n;switch(this.logger.log("📨 Parsed message structure",{source:"LiveKitToolRegistry",error:{eventType:r,hasContent:!!n.content,hasData:!!n.data,contentType:typeof s,contentPreview:"string"==typeof s?s.substring(0,vu.TEXT_PREVIEW_LENGTH):JSON.stringify(s).substring(0,vu.TEXT_PREVIEW_LENGTH)}}),r){case"answer":this.logger.log("✅ Emitting answerReceived event",{source:"LiveKitToolRegistry",error:{eventData:s.substring(0,vu.TEXT_PREVIEW_LENGTH),participant:t}}),this.emit("answerReceived",s);break;case"transcription":this.logger.log("✅ Emitting transcriptionReceived event (from data)",{source:"LiveKitToolRegistry",error:{eventData:s.substring(0,vu.TEXT_PREVIEW_LENGTH),participant:t}}),this.emit("transcriptionReceived",s);break;default:this.logger.log("⚡ Emitting customEvent",{source:"LiveKitToolRegistry",error:{eventType:r,eventData:"string"==typeof s?s.substring(0,vu.TEXT_PREVIEW_LENGTH):JSON.stringify(s).substring(0,vu.TEXT_PREVIEW_LENGTH),participant:t}}),this.emit("customEvent",r,s,{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,vu.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"}});const n=i?"agent":"user";for(const r of e)r.text&&(i?(this.logger.log("✅ Emitting answerReceived event (from LiveKit)",{source:"LiveKitToolRegistry",error:{text:r.text.substring(0,vu.TEXT_PREVIEW_LENGTH),final:r.final,textLength:r.text.length,participant:t}}),this.emit("answerReceived",r.text)):(this.logger.log("✅ Emitting transcriptionReceived event (from LiveKit)",{source:"LiveKitToolRegistry",error:{text:r.text.substring(0,vu.TEXT_PREVIEW_LENGTH),final:r.final,textLength:r.text.length,participant:t}}),this.emit("transcriptionReceived",r.text)),this.emitMessageReceived({id:r.id,role:n,text:r.text,isFinal:r.final??!1}))}catch(i){this.logger.error("❌ Error processing transcription",{source:"LiveKitToolRegistry",error:{message:i instanceof Error?i.message:String(i),transcriptionsCount:e.length,participant:t}})}}buildReceivedMessage(e){let t=e.id;return t||(this.fallbackMessageIdCounter+=1,t=`msg-${this.fallbackMessageIdCounter}`),{id:t,role:e.role,text:e.text,isFinal:e.isFinal,timestamp:Date.now()}}emitMessageReceived(e){const t=this.buildReceivedMessage(e);this.logger.log("✅ Emitting messageReceived event",{source:"LiveKitToolRegistry",error:{id:t.id,role:t.role,isFinal:t.isFinal,textLength:t.text.length}}),this.emit("messageReceived",t)}emitChatMessage(e){const t=this.buildReceivedMessage(e);this.logger.log("✅ Emitting chatMessageReceived event",{source:"LiveKitToolRegistry",error:{id:t.id,role:t.role,isFinal:t.isFinal,textLength:t.text.length}}),this.emit("chatMessageReceived",t),this.emit("messageReceived",t)}getToolCount(){return this.tools.length}getTools(){return this.tools}cleanup(){for(const e of this.registeredChatTopics)try{this.room?.unregisterTextStreamHandler(e)}catch(t){this.logger.error("Failed to unregister chat text-stream handler",{source:"LiveKitToolRegistry",error:{topic:e,error:t}})}this.registeredChatTopics.clear()}}var ku,yu,bu,Tu,Su,Cu,wu,Eu,Ru,Pu,Iu,Mu,Du,Au,_u,Lu,Ou,xu;vu.TEXT_PREVIEW_LENGTH=100,vu.PAYLOAD_PREVIEW_LENGTH=200;class Nu extends n.EventEmitter{constructor(t,i,n=[],{debug:r=!1,avatarContainerSelector:s,isChatOnly:a=!1}={}){super(),ku.add(this),this.lkUrl=t,this.accessToken=i,this.logger=el(r),this.avatarContainerSelector=s,this.videoElements=new Set,this.logger.log("Initializing LiveKitManager",{source:"LiveKitManager",error:{lkUrl:t,toolsCount:n.length,debug:r}}),this.logger.log("Creating LiveKitConnection module",{source:"LiveKitManager"}),this.connection=new gu(t,i,r,a),this.logger.log("Creating LiveKitAnalytics module",{source:"LiveKitManager"}),this.analytics=new El(r),this.logger.log("Creating LiveKitAudioManager module",{source:"LiveKitManager"}),this.audioManager=new $l(r),this.logger.log("Creating LiveKitToolRegistry module",{source:"LiveKitManager",error:{toolsCount:n.length}}),this.toolRegistry=new vu(n,r,a),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"}),e(this,ku,"m",yu).call(this),this.logger.log("Setting up event forwarding",{source:"LiveKitManager"}),e(this,ku,"m",bu).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 r=Date.now();this.logger.log("LiveKitManager.disconnect() - COMPLETE",{source:"LiveKitManager",error:{timestamp:r,cleanupDuration:r-n,totalDisconnectDuration:r-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();for(const e of this.videoElements)e.remove();this.videoElements.clear()}}ku=new WeakSet,yu=function(){this.connection.on("connected",(()=>{const t=this.connection.room;this.analytics.setRoom(t),this.toolRegistry.setRoom(t),this.audioManager.setRoom(t),this.analytics.setConnectionState(!0,this.connection.callStartTime),this.toolRegistry.registerTools(),this.analytics.startAnalyticsCollection(),e(this,ku,"m",Tu).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",(()=>{e(this,ku,"m",wu).call(this)})),this.connection.on("participantDisconnected",(()=>{e(this,ku,"m",wu).call(this)})),this.audioManager.on("trackSubscribed",(()=>{e(this,ku,"m",wu).call(this)})),this.audioManager.on("trackUnsubscribed",(()=>{e(this,ku,"m",wu).call(this)}))},bu=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("messageReceived",(e=>this.emit("messageReceived",e))),this.toolRegistry.on("chatMessageReceived",(e=>this.emit("chatMessageReceived",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))),this.toolRegistry.on("rpcError",((e,t)=>this.emit("rpcError",e,t)))},Tu=function(){const t=this.connection.room;if(!t)return;const i=[[$r.TrackSubscribed,(t,i,n)=>{this.logger.log("Track subscribed",{source:"LiveKitManager",error:{trackSid:t.sid,trackKind:t.kind,participantIdentity:n.identity,isMuted:i.isMuted}}),this.audioManager.handleTrackSubscribed(t,i,n),t.kind===Us.Kind.Video&&e(this,ku,"m",Su).call(this,t)}],[$r.TrackUnsubscribed,(t,i,n)=>{this.logger.log("Track unsubscribed",{source:"LiveKitManager",error:{trackSid:t.sid,trackKind:t.kind,participantIdentity:n.identity}}),this.audioManager.handleTrackUnsubscribed(t,i,n),t.kind===Us.Kind.Video&&e(this,ku,"m",Cu).call(this,t)}],[$r.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)}],[$r.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)}],[$r.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)}],[$r.AudioPlaybackStatusChanged,e=>{this.logger.log("Audio playback status changed",{source:"LiveKitManager",error:{playing:e,state:e?"started":"stopped"}}),this.analytics.handleAudioPlaybackChanged(e)}],[$r.MediaDevicesError,e=>{this.logger.error("Media devices error",{source:"LiveKitManager",error:{message:e.message,name:e.name}}),this.emit("mediaDevicesError",e)}],[$r.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}),e.kind===Us.Kind.Audio&&e.track instanceof Us&&this.audioManager.handleLocalTrackPublished(e.track,e,t.localParticipant)}],[$r.LocalTrackUnpublished,e=>{this.logger.log("Local track unpublished",{source:"LiveKitManager",error:{trackSid:e.trackSid,trackKind:e.kind}}),e.kind===Us.Kind.Audio&&e.track&&this.audioManager.handleLocalTrackUnsubscribed(e.track,e,t.localParticipant)}]];for(const[e,n]of i)t.on(e,n)},Su=function(e){if(!this.avatarContainerSelector)return;const t=document.querySelector(this.avatarContainerSelector);if(!t)return void this.logger.warn("Avatar container element not found",{source:"LiveKitManager",error:{selector:this.avatarContainerSelector}});const i=e.attach();i instanceof HTMLVideoElement&&(i.autoplay=!0,i.playsInline=!0,i.style.width="100%",i.style.height="100%",i.style.objectFit="cover",t.appendChild(i),this.videoElements.add(i),this.logger.log("Avatar video attached to container",{source:"LiveKitManager",error:{selector:this.avatarContainerSelector,trackSid:e.sid}}))},Cu=function(e){for(const t of e.detach())t instanceof HTMLVideoElement&&(t.remove(),this.videoElements.delete(t))},wu=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 Uu{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 Fu extends Error{constructor(e,t){super(e),this.name="HamsaApiError",this.messageKey=t}}const ju={eu:{API_URL:"https://api.tryhamsa.com",LIVEKIT_URL:"wss://rtc.eu.tryhamsa.com"},uae:{API_URL:"https://api.uae.tryhamsa.com",LIVEKIT_URL:"wss://rtc.uae.tryhamsa.com"}};class Bu extends n.EventEmitter{constructor(e,{region:t="eu",API_URL:i,LIVEKIT_URL:n,debug:r=!1}={}){super(),Eu.add(this),this.liveKitManager=null,this.jobId=null,this.userInitiatedEnd=!1;const s=ju[t];this.liveKitManager=null,this.apiKey=e,this.API_URL=i??s.API_URL,this.LIVEKIT_URL=n??s.LIVEKIT_URL,this.debug=r,this.logger=el(r),this.jobId=null,this.wakeLockManager=new Uu}setVolume(e){this.liveKitManager&&this.liveKitManager.setVolume(e)}getOutputVolume(){return this.liveKitManager?.audioManager.getOutputVolume()??Bu.DEFAULT_OUTPUT_VOLUME}getJobId(){return this.jobId}getInputVolume(){return this.liveKitManager?.audioManager.getInputVolume()??Bu.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}})}sendDTMF(e){const t={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,"*":10,"#":11};if(!(e in t))throw new Error(`Invalid DTMF digit: "${e}". Valid digits are 0-9, *, and #.`);const i=this.liveKitManager?.connection?.room;if(!this.liveKitManager?.isConnected||!i?.localParticipant)throw new Error("Cannot send DTMF: not connected to voice agent. Call start() first.");const n=t[e];this.logger.log("Sending DTMF digit",{source:"HamsaVoiceAgent",error:{digit:e,code:n}}),i.localParticipant.publishDtmf(n,e),this.logger.log("DTMF digit sent successfully",{source:"HamsaVoiceAgent",error:{digit:e,code:n}}),this.emit("dtmfSent",e)}async sendMessage(e){if("string"!=typeof e||0===e.trim().length)throw new Error("Cannot send message: text must be a non-empty string.");const t=this.liveKitManager?.connection?.room;if(!this.liveKitManager?.isConnected||!t?.localParticipant)throw new Error("Cannot send message: not connected to agent. Call start() first.");this.logger.log("Sending chat message",{source:"HamsaVoiceAgent",error:{length:e.length,preview:e.substring(0,50),topic:fu}});try{await t.localParticipant.sendText(e,{topic:fu})}catch(e){throw this.logger.error("Failed to send chat message",{source:"HamsaVoiceAgent",error:e}),this.emit("error",e instanceof Error?e:new Error(String(e))),e}this.logger.log("Chat message sent successfully",{source:"HamsaVoiceAgent"}),this.emit("messageSent",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:t,params:i={},voiceEnablement:n=!1,isChatOnly:r=!1,tools:s=[],userId:a,preferHeadphonesForIosDevices:o=!1,connectionDelay:c,disableWakeLock:d=!1,onAudioData:l,captureAudio:u,avatarContainerSelector:h}){try{this.logger.log("SDK initialized - disconnect debugging enabled",{source:"HamsaVoiceAgent"}),this.userInitiatedEnd=!1,this.logger.log("Starting conversation initialization",{source:"HamsaVoiceAgent",error:{agentId:t,voiceEnablement:n,toolsCount:s?.length??0,hasParams:Object.keys(i).length>0}});const a=await e(this,Eu,"m",Mu).call(this,{voiceAgentId:t,params:i,voiceEnablement:n,tools:s,isChatOnly:r});this.logger.log("Creating LiveKitManager instance",{source:"HamsaVoiceAgent",error:{livekitUrl:this.LIVEKIT_URL,tokenLength:a.length,debug:this.debug}}),this.liveKitManager=new Nu(this.LIVEKIT_URL,a,s,{debug:this.debug,avatarContainerSelector:h,isChatOnly:r}),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"}),u?(this.logger.log("Enabling audio capture via captureAudio options",{source:"HamsaVoiceAgent",error:{source:u.source,format:u.format}}),this.liveKitManager?.audioManager.enableAudioCapture(u)):l&&(this.logger.log("Enabling audio capture via onAudioData",{source:"HamsaVoiceAgent"}),this.liveKitManager?.audioManager.enableAudioCapture({source:"agent",format:"opus-webm",chunkSize:100,callback:l})),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("messageReceived",(e=>{this.emit("messageReceived",e)})).on("chatMessageReceived",(e=>{this.emit("chatMessageReceived",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))).on("toolsRegistered",(e=>this.emit("toolsRegistered",e))).on("rpcError",((e,t)=>this.emit("rpcError",e,t))),this.logger.log("Connecting to LiveKit room",{source:"HamsaVoiceAgent",error:{livekitUrl:this.LIVEKIT_URL}});const o=Date.now();await this.liveKitManager.connect();const c=Date.now()-o;this.logger.log("Connected to LiveKit room",{source:"HamsaVoiceAgent",error:{duration:`${c}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()-o+"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 Fu}}),this.listenerCount("error")>0)if(e instanceof Fu)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 t=Date.now();this.logger.log("end() called - START DISCONNECT TIMING",{source:"HamsaVoiceAgent",error:{timestamp:t,userInitiatedEnd:this.userInitiatedEnd,isConnected:this.liveKitManager?.isConnected??!1,stack:new Error("Stack trace").stack}}),e(this,Eu,"m",Ru).call(this,t).then((()=>{const e=Date.now();this.logger.log("end() completed - END DISCONNECT TIMING",{source:"HamsaVoiceAgent",error:{timestamp:e,totalDuration:e-t}})})).catch((i=>{e(this,Eu,"m",Iu).call(this,i,t)})),e(this,Eu,"m",Pu).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(t=5,i=1e3,n=2){if(!this.jobId)throw new Error("Cannot fetch job details: jobId is not set. Start a conversation first.");const r=`${this.API_URL}/v1/voice-agents/conversation/${this.jobId}`,s={Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},a=new URLSearchParams({jobId:this.jobId});let o=i;const c=async(i=1)=>{try{const e=await fetch(`${r}?${a.toString()}`,{method:"GET",headers:s});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(r){if(i<t)return await e(this,Eu,"m",xu).call(this,o),o*=n,c(i+1);throw new Error(`Failed to fetch job details after ${t} attempts: ${r instanceof Error?r.message:String(r)}`)}};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}}}Eu=new WeakSet,Ru=async function(e){if(!this.liveKitManager)return;this.userInitiatedEnd=!0;const t=Date.now();this.logger.log("Calling liveKitManager.disconnect()",{source:"HamsaVoiceAgent",error:{timestamp:t,timeSinceEndCalled:t-e}}),await this.liveKitManager.disconnect();const i=Date.now();this.logger.log("liveKitManager.disconnect() completed",{source:"HamsaVoiceAgent",error:{timestamp:i,disconnectCallDuration:i-t}}),this.emit("callEnded");const n=Date.now();this.logger.log("callEnded event emitted",{source:"HamsaVoiceAgent",error:{timestamp:n,totalTimeInEndMethod:n-e}})},Pu=function(){this.wakeLockManager?.isActive()&&this.wakeLockManager.release().catch((e=>{}))},Iu=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 Fu)this.emit("error",e);else{const t=e instanceof Error?e.message:String(e);this.emit("error",new Error(`Failed to end call: ${t}`))}},Mu=async function(t){const{voiceAgentId:i,params:n,voiceEnablement:r,tools:s,isChatOnly:a}=t,o={Authorization:`Token ${this.apiKey}`,"Content-Type":"application/json"},c=await e(this,Eu,"m",Au).call(this,i,n,o,a),d=c.liveKitAccessToken,l=e(this,Eu,"m",Lu).call(this,d,c.jobId,i);return await e(this,Eu,"m",_u).call(this,{voiceAgentId:i,params:n,voiceEnablement:r,tools:s,headers:o,jobIdFromToken:l,tokenData:c,isChatOnly:a}),this.jobId=l,d},Du=function(e,t,i=!1){try{const e=JSON.parse(t);if(e.message)throw new Fu(e.message,e.messageKey)}catch(e){if(e instanceof Fu)throw e}const n=i?`${e.status} ${e.statusText} - ${t}`:t;throw new Fu(n)},Au=async function(t,i,n,r){this.logger.log("Fetching participant token from API",{source:"HamsaVoiceAgent",error:{voiceAgentId:t,apiUrl:this.API_URL,paramsCount:Object.keys(i).length}});const s=Date.now(),a=await fetch(`${this.API_URL}/v1/voice-agents/room/participant-token`,{method:"POST",headers:n,body:JSON.stringify({voiceAgentId:t,params:i,isChatOnly:r})}),o=Date.now()-s;if(this.logger.log("Received API response for participant token",{source:"HamsaVoiceAgent",error:{status:a.status,ok:a.ok,duration:`${o}ms`}}),!a.ok){const t=await a.text();this.logger.error("API request failed for participant token",{source:"HamsaVoiceAgent",error:{status:a.status,statusText:a.statusText,errorText:t}}),e(this,Eu,"m",Du).call(this,a,t,!0)}const c=await a.json();if(!c?.success||!c?.data?.liveKitAccessToken)throw this.logger.error("Invalid token response structure",{source:"HamsaVoiceAgent",error:{success:c?.success,hasToken:!!c?.data?.liveKitAccessToken}}),new Error("Failed to get LiveKit access token");return this.logger.log("Successfully received LiveKit access token",{source:"HamsaVoiceAgent",error:{tokenLength:c.data.liveKitAccessToken.length,hasJobId:!!c.data.jobId,jobId:c.data.jobId}}),c.data},_u=async function(t){const{voiceAgentId:i,params:n,voiceEnablement:r,tools:s,headers:a,jobIdFromToken:o,tokenData:c,isChatOnly:d}=t,l=s?.length>0?e(this,Eu,"m",Ou).call(this,s):[],u={tools:l,voiceEnablement:r,voiceAgentId:i,params:n,jobId:o??c.jobId??i,channelType:d?"Chat Agent":"Web",isChatOnly:d};this.logger.log("Initializing conversation with API",{source:"HamsaVoiceAgent",error:{voiceAgentId:i,toolsCount:l.length,voiceEnablement:r,jobId:u.jobId,channelType:u.channelType,isChatOnly:d}});const h=Date.now(),p=await fetch(`${this.API_URL}/v1/voice-agents/room/conversation-init`,{method:"POST",headers:a,body:JSON.stringify(u),redirect:"follow"}),m=Date.now()-h;if(this.logger.log("Received conversation init response",{source:"HamsaVoiceAgent",error:{status:p.status,ok:p.ok,duration:`${m}ms`}}),!p.ok){const t=await p.text();this.logger.error("Conversation initialization failed",{source:"HamsaVoiceAgent",error:{status:p.status,statusText:p.statusText,errorText:t}}),e(this,Eu,"m",Du).call(this,p,t,!1)}this.logger.log("Conversation initialized successfully",{source:"HamsaVoiceAgent"})},Lu=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 r("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 r(`Invalid token specified: missing part #${i+1}`);let a;try{a=s(n)}catch(e){throw new r(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(a)}catch(e){throw new r(`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},Ou=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}})))},xu=function(e){return new Promise((t=>setTimeout(t,e)))},Bu.DEFAULT_OUTPUT_VOLUME=0,Bu.DEFAULT_INPUT_VOLUME=0,exports.HamsaApiError=Fu,exports.HamsaVoiceAgent=Bu,exports.RpcError=Id,exports.default=Bu;
2
2
  //# sourceMappingURL=index.cjs.js.map