@staylift-tech/conv-widget 0.0.3 → 0.0.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.
@@ -1 +1 @@
1
- import{t,d as e,p as i,H as n,c as o,h as c}from"./p-DnOZjbwA.js";export{S as StayliftOrb,g as getAssetPath,r as render,s as setAssetPath,a as setNonce,b as setPlatformOptions}from"./p-DnOZjbwA.js";function d(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(i){if("default"!==i&&!(i in t)){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})}}))})),Object.freeze(t)}var h=Object.defineProperty,l=(t,e,i)=>((t,e,i)=>e in t?h(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,i);let u=class{constructor(){l(this,"_locking"),l(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let t;this._locks+=1;const e=new Promise((e=>t=()=>{this._locks-=1,e()})),i=this._locking.then((()=>t));return this._locking=this._locking.then((()=>e)),i}};function f(t,e){if(!t)throw Error(e)}function v(t){if("number"!=typeof t)throw Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>2147483647||t<-2147483648)throw Error("invalid int 32: "+t)}function m(t){if("number"!=typeof t)throw Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>4294967295||t<0)throw Error("invalid uint 32: "+t)}function p(t){if("number"!=typeof t)throw Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>34028234663852886e22||t<-34028234663852886e22))throw Error("invalid float 32: "+t)}const y=Symbol("@bufbuild/protobuf/enum-type");function w(t){const e=t[y];return f(e,"missing enum type on enum object"),e}function k(t,e,i){t[y]=T(e,i.map((e=>({no:e.no,name:e.name,localName:t[e.no]}))))}function T(t,e){const i=Object.create(null),n=Object.create(null),s=[];for(const t of e){const e=O(t);s.push(e),i[t.name]=e,n[t.no]=e}return{typeName:t,values:s,findName:t=>i[t],findNumber:t=>n[t]}}function E(t,e){const i={};for(const t of e){const e=O(t);i[e.localName]=e.no,i[e.no]=e.localName}return k(i,t,e),i}function O(t){return"localName"in t?t:Object.assign(Object.assign({},t),{localName:t.name})}class x{equals(t){return this.getType().runtime.util.equals(this.getType(),this,t)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(t,e){const i=this.getType().runtime.bin,n=i.makeReadOptions(e);return i.readMessage(this,n.readerFactory(t),t.byteLength,n),this}fromJson(t,e){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(e);return n.readMessage(i,t,s,this),this}fromJsonString(t,e){let i;try{i=JSON.parse(t)}catch(t){throw Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(t instanceof Error?t.message:t+""))}return this.fromJson(i,e)}toBinary(t){const e=this.getType().runtime.bin,i=e.makeWriteOptions(t),n=i.writerFactory();return e.writeMessage(this,n,i),n.finish()}toJson(t){const e=this.getType().runtime.json,i=e.makeWriteOptions(t);return e.writeMessage(this,i)}toJsonString(t){var e;const i=this.toJson(t);return JSON.stringify(i,null,null!==(e=null==t?void 0:t.prettySpaces)&&void 0!==e?e:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function A(){let t=0,e=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[t,e]}let i=this.buf[this.pos++];if(t|=(15&i)<<28,e=(112&i)>>4,!(128&i))return this.assertBounds(),[t,e];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,!(128&n))return this.assertBounds(),[t,e]}throw Error("invalid varint")}function C(t,e,i){for(let n=0;n<28;n+=7){const s=t>>>n,r=!(s>>>7==0&&0==e);if(i.push(255&(r?128|s:s)),!r)return}const n=t>>>28&15|(7&e)<<4,s=!!(e>>3);if(i.push(255&(s?128|n:n)),s){for(let t=3;t<31;t+=7){const n=e>>>t,s=!(n>>>7==0);if(i.push(255&(s?128|n:n)),!s)return}i.push(e>>>31&1)}}const _=4294967296;function I(t){const e="-"===t[0];e&&(t=t.slice(1));const i=1e6;let n=0,s=0;function r(e,r){const o=Number(t.slice(e,r));s*=i,n=n*i+o,n>=_&&(s+=n/_|0,n%=_)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?P(n,s):j(n,s)}function R(t,e){if(({lo:t,hi:e}=function(t,e){return{lo:t>>>0,hi:e>>>0}}(t,e)),e<=2097151)return _*e+t+"";const i=16777215&(t>>>24|e<<8),n=e>>16&65535;let s=(16777215&t)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),""+o+D(r)+D(s)}function j(t,e){return{lo:0|t,hi:0|e}}function P(t,e){return e=~e,t?t=1+~t:e+=1,j(t,e)}const D=t=>{const e=t+"";return"0000000".slice(e.length)+e};function M(t,e){if(t>=0){for(;t>127;)e.push(127&t|128),t>>>=7;e.push(t)}else{for(let i=0;i<9;i++)e.push(127&t|128),t>>=7;e.push(1)}}function N(){let t=this.buf[this.pos++],e=127&t;if(!(128&t))return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(127&t)<<7,!(128&t))return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(127&t)<<14,!(128&t))return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(127&t)<<21,!(128&t))return this.assertBounds(),e;t=this.buf[this.pos++],e|=(15&t)<<28;for(let e=5;128&t&&e<10;e++)t=this.buf[this.pos++];if(128&t)throw Error("invalid varint");return this.assertBounds(),e>>>0}const U=function(){const t=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof t.getBigInt64&&"function"==typeof t.getBigUint64&&"function"==typeof t.setBigInt64&&"function"==typeof t.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const e=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(t){const n="bigint"==typeof t?t:BigInt(t);if(n>i||n<e)throw Error("int64 invalid: ".concat(t));return n},uParse(t){const e="bigint"==typeof t?t:BigInt(t);if(e>s||e<n)throw Error("uint64 invalid: ".concat(t));return e},enc(e){return t.setBigInt64(0,this.parse(e),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(e){return t.setBigInt64(0,this.uParse(e),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec:(e,i)=>(t.setInt32(0,e,!0),t.setInt32(4,i,!0),t.getBigInt64(0,!0)),uDec:(e,i)=>(t.setInt32(0,e,!0),t.setInt32(4,i,!0),t.getBigUint64(0,!0))}}const e=t=>f(/^-?[0-9]+$/.test(t),"int64 invalid: ".concat(t)),i=t=>f(/^[0-9]+$/.test(t),"uint64 invalid: ".concat(t));return{zero:"0",supported:!1,parse:t=>("string"!=typeof t&&(t=""+t),e(t),t),uParse:t=>("string"!=typeof t&&(t=""+t),i(t),t),enc:t=>("string"!=typeof t&&(t=""+t),e(t),I(t)),uEnc:t=>("string"!=typeof t&&(t=""+t),i(t),I(t)),dec:(t,e)=>function(t,e){let i=j(t,e);const n=2147483648&i.hi;n&&(i=P(i.lo,i.hi));const s=R(i.lo,i.hi);return n?"-"+s:s}(t,e),uDec:(t,e)=>R(t,e)}}();var L,B,F;function V(t,e,i){if(e===i)return!0;if(t==L.BYTES){if(!(e instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(e.length!==i.length)return!1;for(let t=0;t<e.length;t++)if(e[t]!==i[t])return!1;return!0}switch(t){case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return e==i}return!1}function q(t,e){switch(t){case L.BOOL:return!1;case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return 0==e?U.zero:"0";case L.DOUBLE:case L.FLOAT:return 0;case L.BYTES:return new Uint8Array(0);case L.STRING:return"";default:return 0}}function z(t,e){switch(t){case L.BOOL:return!1===e;case L.STRING:return""===e;case L.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return 0==e}}!function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"}(L||(L={})),function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING"}(B||(B={})),function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"}(F||(F={}));class J{constructor(t){this.stack=[],this.textEncoder=null!=t?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let e=0;e<this.chunks.length;e++)t+=this.chunks[e].length;let e=new Uint8Array(t),i=0;for(let t=0;t<this.chunks.length;t++)e.set(this.chunks[t],i),i+=this.chunks[t].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),e=this.stack.pop();if(!e)throw Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,e){return this.uint32((t<<3|e)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(m(t);t>127;)this.buf.push(127&t|128),t>>>=7;return this.buf.push(t),this}int32(t){return v(t),M(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){p(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){m(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){v(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return v(t),M(t=(t<<1^t>>31)>>>0,this.buf),this}sfixed64(t){let e=new Uint8Array(8),i=new DataView(e.buffer),n=U.enc(t);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),i=new DataView(e.buffer),n=U.uEnc(t);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(e)}int64(t){let e=U.enc(t);return C(e.lo,e.hi,this.buf),this}sint64(t){let e=U.enc(t),i=e.hi>>31;return C(e.lo<<1^i,(e.hi<<1|e.lo>>>31)^i,this.buf),this}uint64(t){let e=U.uEnc(t);return C(e.lo,e.hi,this.buf),this}}class W{constructor(t,e){this.varint64=A,this.uint32=N,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=null!=e?e:new TextDecoder}tag(){let t=this.uint32(),e=t>>>3,i=7&t;if(e<=0||i<0||i>5)throw Error("illegal tag: field no "+e+" wire type "+i);return[e,i]}skip(t,e){let i=this.pos;switch(t){case F.Varint:for(;128&this.buf[this.pos++];);break;case F.Bit64:this.pos+=4;case F.Bit32:this.pos+=4;break;case F.LengthDelimited:let i=this.uint32();this.pos+=i;break;case F.StartGroup:for(;;){const[t,i]=this.tag();if(i===F.EndGroup){if(void 0!==e&&t!==e)throw Error("invalid end group tag");break}this.skip(i,t)}break;default:throw Error("cant skip wire type "+t)}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 t=this.uint32();return t>>>1^-(1&t)}int64(){return U.dec(...this.varint64())}uint64(){return U.uDec(...this.varint64())}sint64(){let[t,e]=this.varint64(),i=-(1&t);return t=(t>>>1|(1&e)<<31)^i,e=e>>>1^i,U.dec(t,e)}bool(){let[t,e]=this.varint64();return 0!==t||0!==e}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return U.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return U.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 t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function G(t){const e=t.field.localName,i=Object.create(null);return i[e]=function(t){const e=t.field;if(e.repeated)return[];if(void 0!==e.default)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return q(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(t),[i,()=>i[e]]}let Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),H=[];for(let t=0;t<Q.length;t++)H[Q[t].charCodeAt(0)]=t;H[45]=Q.indexOf("+"),H[95]=Q.indexOf("/");const K={dec(t){let e=3*t.length/4;"="==t[t.length-2]?e-=2:"="==t[t.length-1]&&(e-=1);let i,n=new Uint8Array(e),s=0,r=0,o=0;for(let e=0;e<t.length;e++){if(i=H[t.charCodeAt(e)],void 0===i)switch(t[e]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(t){let e,i="",n=0,s=0;for(let r=0;r<t.length;r++)switch(e=t[r],n){case 0:i+=Q[e>>2],s=(3&e)<<4,n=1;break;case 1:i+=Q[s|e>>4],s=(15&e)<<2,n=2;break;case 2:i+=Q[s|e>>6],i+=Q[63&e],n=0}return n&&(i+=Q[s],i+="=",1==n&&(i+="=")),i}};function Y(t,e,i){X(e,t);const n=e.runtime.bin.makeReadOptions(i),s=function(t,e){if(!e.repeated&&("enum"==e.kind||"scalar"==e.kind)){for(let i=t.length-1;i>=0;--i)if(t[i].no==e.no)return[t[i]];return[]}return t.filter((t=>t.no===e.no))}(t.getType().runtime.bin.listUnknownFields(t),e.field),[r,o]=G(e);for(const t of s)e.runtime.bin.readField(r,n.readerFactory(t.data),e.field,t.wireType,n);return o()}function Z(t,e,i,n){X(e,t);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if($(t,e)){const i=t.getType().runtime.bin.listUnknownFields(t).filter((t=>t.no!=e.field.no));t.getType().runtime.bin.discardUnknownFields(t);for(const e of i)t.getType().runtime.bin.onUnknownField(t,e.no,e.wireType,e.data)}const o=r.writerFactory();let a=e.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[e,i]=c.tag(),n=c.skip(i,e);t.getType().runtime.bin.onUnknownField(t,e,i,n)}}function $(t,e){const i=t.getType();return e.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(t).find((t=>t.no==e.field.no))}function X(t,e){f(t.extendee.typeName==e.getType().typeName,"extension ".concat(t.typeName," can only be applied to message ").concat(t.extendee.typeName))}function tt(t,e){const i=t.localName;if(t.repeated)return e[i].length>0;if(t.oneof)return e[t.oneof.localName].case===i;switch(t.kind){case"enum":case"scalar":return t.opt||t.req?void 0!==e[i]:"enum"==t.kind?e[i]!==t.T.values[0].no:!z(t.T,e[i]);case"message":return void 0!==e[i];case"map":return Object.keys(e[i]).length>0}}function et(t,e){const i=t.localName,n=!t.opt&&!t.req;if(t.repeated)e[i]=[];else if(t.oneof)e[t.oneof.localName]={case:void 0};else switch(t.kind){case"map":e[i]={};break;case"enum":e[i]=n?t.T.values[0].no:void 0;break;case"scalar":e[i]=n?q(t.T,t.L):void 0;break;case"message":e[i]=void 0}}function it(t,e){if(null===t||"object"!=typeof t)return!1;if(!Object.getOwnPropertyNames(x.prototype).every((e=>e in t&&"function"==typeof t[e])))return!1;const i=t.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===e||i.typeName==e.typeName)}function nt(t,e){return it(e)||!t.fieldWrapper?e:t.fieldWrapper.wrapField(e)}const st={ignoreUnknownFields:!1},rt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ot(t){return t?Object.assign(Object.assign({},st),t):st}function at(t){return t?Object.assign(Object.assign({},rt),t):rt}const ct=Symbol(),dt=Symbol();function ht(t){if(null===t)return"null";switch(typeof t){case"object":return Array.isArray(t)?"array":"object";case"string":return t.length>100?"string":'"'.concat(t.split('"').join('\\"'),'"');default:return t+""}}function lt(t,e,i,n,s){let r=i.localName;if(i.repeated){if(f("map"!=i.kind),null===e)return;if(!Array.isArray(e))throw Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e)));const o=t[r];for(const t of e){if(null===t)throw Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(t)));switch(i.kind){case"message":o.push(i.T.fromJson(t,n));break;case"enum":const e=vt(i.T,t,n.ignoreUnknownFields,!0);e!==dt&&o.push(e);break;case"scalar":try{o.push(ft(i.T,t,i.L,!0))}catch(e){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),Error(n)}}}}else if("map"==i.kind){if(null===e)return;if("object"!=typeof e||Array.isArray(e))throw Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e)));const o=t[r];for(const[t,r]of Object.entries(e)){if(null===r)throw Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let a;try{a=ut(i.K,t)}catch(t){let n="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),Error(n)}switch(i.V.kind){case"message":o[a]=i.V.T.fromJson(r,n);break;case"enum":const t=vt(i.V.T,r,n.ignoreUnknownFields,!0);t!==dt&&(o[a]=t);break;case"scalar":try{o[a]=ft(i.V.T,r,B.BIGINT,!0)}catch(t){let n="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),Error(n)}}}}else switch(i.oneof&&(t=t[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const o=i.T;if(null===e&&"google.protobuf.Value"!=o.typeName)return;let a=t[r];it(a)?a.fromJson(e,n):(t[r]=a=o.fromJson(e,n),o.fieldWrapper&&!i.oneof&&(t[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=vt(i.T,e,n.ignoreUnknownFields,!1);switch(c){case ct:et(i,t);break;case dt:break;default:t[r]=c}break;case"scalar":try{const n=ft(i.T,e,i.L,!1);n===ct?et(i,t):t[r]=n}catch(t){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),Error(n)}}}function ut(t,e){if(t===L.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1}return""+ft(t,e,B.BIGINT,!0)}function ft(t,e,i,n){if(null===e)return n?q(t,i):ct;switch(t){case L.DOUBLE:case L.FLOAT:if("NaN"===e)return NaN;if("Infinity"===e)return 1/0;if("-Infinity"===e)return-1/0;if(""===e)break;if("string"==typeof e&&e.trim().length!==e.length)break;if("string"!=typeof e&&"number"!=typeof e)break;const n=Number(e);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return t==L.FLOAT&&p(n),n;case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:let s;if("number"==typeof e?s=e:"string"==typeof e&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),void 0===s)break;return t==L.UINT32||t==L.FIXED32?m(s):v(s),s;case L.INT64:case L.SFIXED64:case L.SINT64:if("number"!=typeof e&&"string"!=typeof e)break;const r=U.parse(e);return i?""+r:r;case L.FIXED64:case L.UINT64:if("number"!=typeof e&&"string"!=typeof e)break;const o=U.uParse(e);return i?""+o:o;case L.BOOL:if("boolean"!=typeof e)break;return e;case L.STRING:if("string"!=typeof e)break;return e;case L.BYTES:if(""===e)return new Uint8Array(0);if("string"!=typeof e)break;return K.dec(e)}throw Error()}function vt(t,e,i,n){if(null===e)return"google.protobuf.NullValue"==t.typeName?0:n?t.values[0].no:ct;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const n=t.findName(e);if(void 0!==n)return n.no;if(i)return dt}throw Error("cannot decode enum ".concat(t.typeName," from JSON: ").concat(ht(e)))}function mt(t){return!(!t.repeated&&"map"!=t.kind&&(t.oneof||"message"==t.kind||t.opt||t.req))}function pt(t,e,i){if("map"==t.kind){f("object"==typeof e&&null!=e);const n={},s=Object.entries(e);switch(t.V.kind){case"scalar":for(const[e,i]of s)n[""+e]=bt(t.V.T,i);break;case"message":for(const[t,e]of s)n[""+t]=e.toJson(i);break;case"enum":const e=t.V.T;for(const[t,r]of s)n[""+t]=gt(e,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(t.repeated){f(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let i=0;i<e.length;i++)n.push(bt(t.T,e[i]));break;case"enum":for(let s=0;s<e.length;s++)n.push(gt(t.T,e[s],i.enumAsInteger));break;case"message":for(let t=0;t<e.length;t++)n.push(e[t].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(t.kind){case"scalar":return bt(t.T,e);case"enum":return gt(t.T,e,i.enumAsInteger);case"message":return nt(t.T,e).toJson(i)}}function gt(t,e,i){var n;if(f("number"==typeof e),"google.protobuf.NullValue"==t.typeName)return null;if(i)return e;const s=t.findNumber(e);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:e}function bt(t,e){switch(t){case L.INT32:case L.SFIXED32:case L.SINT32:case L.FIXED32:case L.UINT32:return f("number"==typeof e),e;case L.FLOAT:case L.DOUBLE:return f("number"==typeof e),Number.isNaN(e)?"NaN":e===1/0?"Infinity":e===-1/0?"-Infinity":e;case L.STRING:return f("string"==typeof e),e;case L.BOOL:return f("boolean"==typeof e),e;case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return f("bigint"==typeof e||"string"==typeof e||"number"==typeof e),""+e;case L.BYTES:return f(e instanceof Uint8Array),K.enc(e)}}const yt=Symbol("@bufbuild/protobuf/unknown-fields"),wt={readUnknownFields:!0,readerFactory:t=>new W(t)},kt={writeUnknownFields:!0,writerFactory:()=>new J};function Tt(t){return t?Object.assign(Object.assign({},wt),t):wt}function St(t){return t?Object.assign(Object.assign({},kt),t):kt}function Et(t,e,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((t=t[i.oneof.localName]).case!=o&&delete t.value,t.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?L.INT32:i.T;let c=At;if("scalar"==i.kind&&i.L>0&&(c=xt),r){let i=t[o];if(n==F.LengthDelimited&&a!=L.STRING&&a!=L.BYTES){let t=e.uint32()+e.pos;for(;e.pos<t;)i.push(c(e,a))}else i.push(c(e,a))}else t[o]=c(e,a);break;case"message":const d=i.T;r?t[o].push(Ot(e,new d,s,i)):it(t[o])?Ot(e,t[o],s,i):(t[o]=Ot(e,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(t[o]=d.fieldWrapper.unwrapField(t[o])));break;case"map":let[h,l]=function(t,e,i){const n=e.uint32(),s=e.pos+n;let r,o;for(;e.pos<s;){const[n]=e.tag();switch(n){case 1:r=At(e,t.K);break;case 2:switch(t.V.kind){case"scalar":o=At(e,t.V.T);break;case"enum":o=e.int32();break;case"message":o=Ot(e,new t.V.T,i,void 0)}}}if(void 0===r&&(r=q(t.K,B.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=""+r),void 0===o)switch(t.V.kind){case"scalar":o=q(t.V.T,B.BIGINT);break;case"enum":o=t.V.T.values[0].no;break;case"message":o=new t.V.T}return[r,o]}(i,e,s);t[o][h]=l}}function Ot(t,e,i,n){const s=e.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(e,t,r?n.no:t.uint32(),i,r),e}function xt(t,e){const i=At(t,e);return"bigint"==typeof i?""+i:i}function At(t,e){switch(e){case L.STRING:return t.string();case L.BOOL:return t.bool();case L.DOUBLE:return t.double();case L.FLOAT:return t.float();case L.INT32:return t.int32();case L.INT64:return t.int64();case L.UINT64:return t.uint64();case L.FIXED64:return t.fixed64();case L.BYTES:return t.bytes();case L.FIXED32:return t.fixed32();case L.SFIXED32:return t.sfixed32();case L.SFIXED64:return t.sfixed64();case L.SINT64:return t.sint64();case L.UINT32:return t.uint32();case L.SINT32:return t.sint32()}}function Ct(t,e,i,n){f(void 0!==e);const s=t.repeated;switch(t.kind){case"scalar":case"enum":let r="enum"==t.kind?L.INT32:t.T;if(s)if(f(Array.isArray(e)),t.packed)!function(t,e,i,n){if(!n.length)return;t.tag(i,F.LengthDelimited).fork();let[,s]=jt(e);for(let e=0;e<n.length;e++)t[s](n[e]);t.join()}(i,r,t.no,e);else for(const n of e)Rt(i,r,t.no,n);else Rt(i,r,t.no,e);break;case"message":if(s){f(Array.isArray(e));for(const s of e)It(i,n,t,s)}else It(i,n,t,e);break;case"map":f("object"==typeof e&&null!=e);for(const[s,r]of Object.entries(e))_t(i,n,t,s,r)}}function _t(t,e,i,n,s){t.tag(i.no,F.LengthDelimited),t.fork();let r=n;switch(i.K){case L.INT32:case L.FIXED32:case L.UINT32:case L.SFIXED32:case L.SINT32:r=Number.parseInt(n);break;case L.BOOL:f("true"==n||"false"==n),r="true"==n}switch(Rt(t,i.K,1,r),i.V.kind){case"scalar":Rt(t,i.V.T,2,s);break;case"enum":Rt(t,L.INT32,2,s);break;case"message":f(void 0!==s),t.tag(2,F.LengthDelimited).bytes(s.toBinary(e))}t.join()}function It(t,e,i,n){const s=nt(i.T,n);i.delimited?t.tag(i.no,F.StartGroup).raw(s.toBinary(e)).tag(i.no,F.EndGroup):t.tag(i.no,F.LengthDelimited).bytes(s.toBinary(e))}function Rt(t,e,i,n){f(void 0!==n);let[s,r]=jt(e);t.tag(i,s)[r](n)}function jt(t){let e=F.Varint;switch(t){case L.BYTES:case L.STRING:e=F.LengthDelimited;break;case L.DOUBLE:case L.FIXED64:case L.SFIXED64:e=F.Bit64;break;case L.FIXED32:case L.SFIXED32:case L.FLOAT:e=F.Bit32}return[e,L[t].toLowerCase()]}function Pt(t){if(void 0===t)return t;if(it(t))return t.clone();if(t instanceof Uint8Array){const e=new Uint8Array(t.byteLength);return e.set(t),e}return t}function Dt(t){return t instanceof Uint8Array?t:new Uint8Array(t)}class Mt{constructor(t,e){this._fields=t,this._normalizer=e}findJsonName(t){if(!this.jsonNames){const t={};for(const e of this.list())t[e.jsonName]=t[e.name]=e;this.jsonNames=t}return this.jsonNames[t]}find(t){if(!this.numbers){const t={};for(const e of this.list())t[e.no]=e;this.numbers=t}return this.numbers[t]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((t,e)=>t.no-e.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const t=this.members;let e;for(const i of this.list())i.oneof?i.oneof!==e&&(e=i.oneof,t.push(e)):t.push(i)}return this.members}}function Nt(t,e){const i=Lt(t);return e?i:zt(qt(i))}const Ut=Lt;function Lt(t){let e=!1;const i=[];for(let n=0;n<t.length;n++){let s=t.charAt(n);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const Bt=new Set(["constructor","toString","toJSON","valueOf"]),Ft=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Vt=t=>"".concat(t,"$"),qt=t=>Ft.has(t)?Vt(t):t,zt=t=>Bt.has(t)?Vt(t):t;class Jt{constructor(t){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=t,this.localName=function(t){return Nt(t,!1)}(t)}addField(t){f(t.oneof===this,"field ".concat(t.name," not one of ").concat(this.name)),this.fields.push(t)}findField(t){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[t]}}const Wt={syntax:"proto3",json:{makeReadOptions:ot,makeWriteOptions:at,readMessage(t,e,i,n){if(null==e||Array.isArray(e)||"object"!=typeof e)throw Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(ht(e)));n=null!=n?n:new t;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(e)){const e=t.fields.findJsonName(o);if(e){if(e.oneof){if(null===a&&"scalar"==e.kind)continue;const i=s.get(e.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(e.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(e.oneof,o)}lt(n,a,e,i,t)}else{let e=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==t.typeName){e=!0;const[t,r]=G(s);lt(t,a,s.field,i,s),Z(n,s,r(),i)}}if(!e&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(t,e){const i=t.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!tt(s,t)){if(s.req)throw"required field not set";if(!e.emitDefaultValues)continue;if(!mt(s))continue}const i=pt(s,s.oneof?t[s.oneof.localName].value:t[s.localName],e);void 0!==i&&(n[e.useProtoFieldName?s.name:s.jsonName]=i)}const r=e.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(t)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&$(t,o)){const i=Y(t,o,e),s=pt(o.field,i,e);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(t){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),n=t instanceof Error?t.message:t+"";throw Error(e+(n.length>0?": ".concat(n):""))}return n},readScalar:(t,e,i)=>ft(t,e,null!=i?i:B.BIGINT,!0),writeScalar(t,e,i){if(void 0!==e)return i||z(t,e)?bt(t,e):void 0},debug:ht},bin:{makeReadOptions:Tt,makeWriteOptions:St,listUnknownFields(t){var e;return null!==(e=t[yt])&&void 0!==e?e:[]},discardUnknownFields(t){delete t[yt]},writeUnknownFields(t,e){const i=t[yt];if(i)for(const t of i)e.tag(t.no,t.wireType).raw(t.data)},onUnknownField(t,e,i,n){const s=t;Array.isArray(s[yt])||(s[yt]=[]),s[yt].push({no:e,wireType:i,data:n})},readMessage(t,e,i,n,s){const r=t.getType(),o=s?e.len:e.pos+i;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!0!==s||c!=F.EndGroup);){const i=r.fields.find(a);if(i)Et(t,e,i,c,n);else{const i=e.skip(c,a);n.readUnknownFields&&this.onUnknownField(t,a,c,i)}}if(s&&(c!=F.EndGroup||a!==i))throw Error("invalid end group tag")},readField:Et,writeMessage(t,e,i){const n=t.getType();for(const s of n.fields.byNumber())if(tt(s,t))Ct(s,s.oneof?t[s.oneof.localName].value:t[s.localName],e,i);else if(s.req)throw Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(t,e),e},writeField(t,e,i,n){void 0!==e&&Ct(t,e,i,n)}},util:Object.assign(Object.assign({},{setEnumType:k,initPartial(t,e){if(void 0===t)return;const i=e.getType();for(const n of i.fields.byMember()){const i=n.localName,s=e,r=t;if(null!=r[i])switch(n.kind){case"oneof":const t=r[i].case;if(void 0===t)continue;const e=n.findField(t);let o=r[i].value;e&&"message"==e.kind&&!it(o,e.T)?o=new e.T(o):e&&"scalar"===e.kind&&e.T===L.BYTES&&(o=Dt(o)),s[i]={case:t,value:o};break;case"scalar":case"enum":let a=r[i];n.T===L.BYTES&&(a=n.repeated?a.map(Dt):Dt(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===L.BYTES)for(const[t,e]of Object.entries(r[i]))s[i][t]=Dt(e);else Object.assign(s[i],r[i]);break;case"message":const t=n.V.T;for(const e of Object.keys(r[i])){let n=r[i][e];t.fieldWrapper||(n=new t(n)),s[i][e]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((t=>it(t,c)?t:new c(t)));else{const t=r[i];s[i]=c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?Dt(t):t:it(t,c)?t:new c(t)}}}},equals:(t,e,i)=>e===i||!(!e||!i)&&t.fields.byMember().every((t=>{const n=e[t.localName],s=i[t.localName];if(t.repeated){if(n.length!==s.length)return!1;switch(t.kind){case"message":return n.every(((e,i)=>t.T.equals(e,s[i])));case"scalar":return n.every(((e,i)=>V(t.T,e,s[i])));case"enum":return n.every(((t,e)=>V(L.INT32,t,s[e])))}throw Error("repeated cannot contain ".concat(t.kind))}switch(t.kind){case"message":let e=n,i=s;return t.T.fieldWrapper&&(void 0===e||it(e)||(e=t.T.fieldWrapper.wrapField(e)),void 0===i||it(i)||(i=t.T.fieldWrapper.wrapField(i))),t.T.equals(e,i);case"enum":return V(L.INT32,n,s);case"scalar":return V(t.T,n,s);case"oneof":if(n.case!==s.case)return!1;const r=t.findField(n.case);if(void 0===r)return!0;switch(r.kind){case"message":return r.T.equals(n.value,s.value);case"enum":return V(L.INT32,n.value,s.value);case"scalar":return V(r.T,n.value,s.value)}throw Error("oneof cannot contain ".concat(r.kind));case"map":const o=Object.keys(n).concat(Object.keys(s));switch(t.V.kind){case"message":const e=t.V.T;return o.every((t=>e.equals(n[t],s[t])));case"enum":return o.every((t=>V(L.INT32,n[t],s[t])));case"scalar":const i=t.V.T;return o.every((t=>V(i,n[t],s[t])))}}})),clone(t){const e=t.getType(),i=new e,n=i;for(const i of e.fields.byMember()){const e=t[i.localName];let s;if(i.repeated)s=e.map(Pt);else if("map"==i.kind){s=n[i.localName];for(const[t,i]of Object.entries(e))s[t]=Pt(i)}else s="oneof"==i.kind?i.findField(e.case)?{case:e.case,value:Pt(e.value)}:{case:void 0}:Pt(e);n[i.localName]=s}for(const i of e.runtime.bin.listUnknownFields(t))e.runtime.bin.onUnknownField(n,i.no,i.wireType,i.data);return i}}),{newFieldList:t=>new Mt(t,(t=>function(t){var e,i,n,s,r,o;const a=[];let c;for(const d of"function"==typeof t?t():t){const t=d;if(t.localName=Nt(d.name,void 0!==d.oneof),t.jsonName=null!==(e=d.jsonName)&&void 0!==e?e:Ut(d.name),t.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(t.L=null!==(n=d.L)&&void 0!==n?n:B.BIGINT),t.delimited=null!==(s=d.delimited)&&void 0!==s&&s,t.req=null!==(r=d.req)&&void 0!==r&&r,t.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(t.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=L.BYTES&&d.T!=L.STRING),void 0!==d.oneof){const e="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==e||(c=new Jt(e)),t.oneof=c,c.addField(t)}a.push(t)}return a}(t))),initFields:t=>{for(const e of t.getType().fields.byMember()){if(e.opt)continue;const i=e.localName,n=t;if(e.repeated)n[i]=[];else switch(e.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=q(e.T,e.L)}}}}),makeMessageType(t,e,i){return function(t,e,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(e){t.util.initFields(this),t.util.initPartial(e,this)}}[r];return Object.setPrototypeOf(o.prototype,new x),Object.assign(o,{runtime:t,typeName:e,fields:t.util.newFieldList(i),fromBinary:(t,e)=>(new o).fromBinary(t,e),fromJson:(t,e)=>(new o).fromJson(t,e),fromJsonString:(t,e)=>(new o).fromJsonString(t,e),equals:(e,i)=>t.util.equals(o,e,i)}),o}(this,t,e,i)},makeEnum:E,makeEnumType:T,getEnumType:w,makeExtension(t,e,i){return function(t,e,i,n){let s;return{typeName:e,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=e.split(".").pop(),i.jsonName="[".concat(e,"]"),s=t.util.newFieldList([i]).list()[0]}return s},runtime:t}}(this,t,e,i)}};class Gt extends x{constructor(t){super(),this.seconds=U.zero,this.nanos=0,Wt.util.initPartial(t,this)}fromJson(t,e){if("string"!=typeof t)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Wt.json.debug(t)));const i=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw Error("cannot decode google.protobuf.Timestamp from JSON: 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 Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=U.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(t){const e=1e3*Number(this.seconds);if(e<Date.parse("0001-01-01T00:00:00Z")||e>Date.parse("9999-12-31T23:59:59Z"))throw Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const t=(""+(this.nanos+1e9)).substring(1);i="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(e).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return Gt.fromDate(new Date)}static fromDate(t){const e=t.getTime();return new Gt({seconds:U.parse(Math.floor(e/1e3)),nanos:e%1e3*1e6})}static fromBinary(t,e){return(new Gt).fromBinary(t,e)}static fromJson(t,e){return(new Gt).fromJson(t,e)}static fromJsonString(t,e){return(new Gt).fromJsonString(t,e)}static equals(t,e){return Wt.util.equals(Gt,t,e)}}Gt.runtime=Wt,Gt.typeName="google.protobuf.Timestamp",Gt.fields=Wt.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const Qt=Wt.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Gt},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ht,repeated:!0},{no:5,name:"events",kind:"message",T:Yt,repeated:!0}])),Ht=Wt.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:Kt,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Kt=Wt.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Gt},{no:3,name:"value",kind:"scalar",T:2}])),Yt=Wt.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:Gt},{no:7,name:"normalized_end_timestamp",kind:"message",T:Gt,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Zt=Wt.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),$t=Wt.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Xt=Wt.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"}]),te=Wt.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ee=Wt.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ie=Wt.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ne=Wt.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"}]),se=Wt.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"}]),re=Wt.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),oe=Wt.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"}]),ae=Wt.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:ce,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:qe}])),ce=Wt.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),de=Wt.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:Wt.getEnumType(Xt),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}])),he=Wt.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:Wt.getEnumType(le)},{no:4,name:"tracks",kind:"message",T:pe,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:de},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Wt.getEnumType(ue)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Wt.getEnumType(ne)},{no:18,name:"kind_details",kind:"enum",T:Wt.getEnumType(fe),repeated:!0}])),le=Wt.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ue=Wt.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"}]),fe=Wt.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),ve=Wt.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),me=Wt.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:ge,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Wt.getEnumType(be)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),pe=Wt.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Wt.getEnumType($t)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:Wt.getEnumType(Xt)},{no:10,name:"layers",kind:"message",T:ge,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:me,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:Wt.getEnumType(ve)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:qe},{no:19,name:"audio_features",kind:"enum",T:Wt.getEnumType(oe),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Wt.getEnumType(Zt)}])),ge=Wt.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Wt.getEnumType(te)},{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}])),be=Wt.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"}]),ye=Wt.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Wt.getEnumType(we)},{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:Oe,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Se,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:xe,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Ae,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Qt,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:_e,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Ie,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Re,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:je,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Ge,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Qe,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:He,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:ke,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),we=Wt.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),ke=Wt.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:Wt.getEnumType(ve)},{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}])),Te=Wt.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Oe,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:_e,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Ie,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Re,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:je,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Ge,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Qe,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:He,oneof:"value"}])),Se=Wt.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Ee,repeated:!0}])),Ee=Wt.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}])),Oe=Wt.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}])),xe=Wt.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Ae=Wt.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:Ce,repeated:!0}])),Ce=Wt.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}])),_e=Wt.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}])),Ie=Wt.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}])),Re=Wt.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),je=Wt.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:Pe,oneof:"value"}])),Pe=Wt.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}])),De=Wt.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Me=Wt.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Wt.getEnumType(Ne)},{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}])),Ne=Wt.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Ue=Wt.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Wt.getEnumType(Le)},{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}])),Le=Wt.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"}]),Be=Wt.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Fe},{no:2,name:"screen",kind:"message",T:Fe},{no:3,name:"resume_connection",kind:"enum",T:Wt.getEnumType(ie)},{no:4,name:"disabled_codecs",kind:"message",T:Ve},{no:5,name:"force_relay",kind:"enum",T:Wt.getEnumType(ie)}])),Fe=Wt.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Wt.getEnumType(ie)}])),Ve=Wt.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ce,repeated:!0},{no:2,name:"publish",kind:"message",T:ce,repeated:!0}])),qe=Wt.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),ze=Wt.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Je=Wt.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Wt.getEnumType(ze)},{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"}),We=Wt.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Ge=Wt.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:Wt.getEnumType(ve)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Je,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:We,oneof:"content_header"}]),{localName:"DataStream_Header"}),Qe=Wt.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"}),He=Wt.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"}),Ke=Wt.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Ye=Wt.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Ze=Wt.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),$e=Wt.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Xe=Wt.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:di,oneof:"message"},{no:2,name:"answer",kind:"message",T:di,oneof:"message"},{no:3,name:"trickle",kind:"message",T:ni,oneof:"message"},{no:4,name:"add_track",kind:"message",T:ii,oneof:"message"},{no:5,name:"mute",kind:"message",T:si,oneof:"message"},{no:6,name:"subscription",kind:"message",T:li,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ui,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:gi,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Ri,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Di,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ui,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:bi,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Li,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:fi,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:vi,oneof:"message"}])),ti=Wt.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:ri,oneof:"message"},{no:2,name:"answer",kind:"message",T:di,oneof:"message"},{no:3,name:"offer",kind:"message",T:di,oneof:"message"},{no:4,name:"trickle",kind:"message",T:ni,oneof:"message"},{no:5,name:"update",kind:"message",T:hi,oneof:"message"},{no:6,name:"track_published",kind:"message",T:ai,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:9,name:"mute",kind:"message",T:si,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:wi,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ki,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Si,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Oi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Ci,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ji,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ci,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:oi,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Bi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:qi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:zi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Wi,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Pi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Yi,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:_i,oneof:"message"}])),ei=Wt.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:ge,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Wt.getEnumType(be)}])),ii=Wt.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:Wt.getEnumType($t)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:Wt.getEnumType(Xt)},{no:9,name:"layers",kind:"message",T:ge,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ei,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:Wt.getEnumType(ve)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Wt.getEnumType(Zt)},{no:17,name:"audio_features",kind:"enum",T:Wt.getEnumType(oe),repeated:!0}])),ni=Wt.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Wt.getEnumType(Ye)},{no:3,name:"final",kind:"scalar",T:8}])),si=Wt.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),ri=Wt.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:ae},{no:2,name:"participant",kind:"message",T:he},{no:3,name:"other_participants",kind:"message",T:he,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:yi,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:Be},{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:Me},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ce,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),oi=Wt.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:yi,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Be},{no:3,name:"server_info",kind:"message",T:Me},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),ai=Wt.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:pe}])),ci=Wt.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),di=Wt.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}}])),hi=Wt.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:he,repeated:!0}])),li=Wt.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:De,repeated:!0}])),ui=Wt.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:Wt.getEnumType(te)},{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}])),fi=Wt.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Wt.getEnumType(oe),repeated:!0}])),vi=Wt.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}])),mi=Wt.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Wt.getEnumType(ne)},{no:3,name:"action",kind:"enum",T:Wt.getEnumType(pi)},{no:4,name:"regions",kind:"message",T:Fi}])),pi=Wt.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),gi=Wt.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:ge,repeated:!0}])),bi=Wt.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}])),yi=Wt.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}])),wi=Wt.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Ee,repeated:!0}])),ki=Wt.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:ae}])),Ti=Wt.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Wt.getEnumType(ee)},{no:3,name:"score",kind:"scalar",T:2}])),Si=Wt.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Ti,repeated:!0}])),Ei=Wt.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:Wt.getEnumType(Ze)}])),Oi=Wt.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Ei,repeated:!0}])),xi=Wt.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Wt.getEnumType(te)},{no:2,name:"enabled",kind:"scalar",T:8}])),Ai=Wt.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:xi,repeated:!0}])),Ci=Wt.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:xi,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Ai,repeated:!0}])),_i=Wt.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Ke,repeated:!0}])),Ii=Wt.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}])),Ri=Wt.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Ii,repeated:!0}])),ji=Wt.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}])),Pi=Wt.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:ae},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:he},{no:4,name:"other_participants",kind:"message",T:he,repeated:!0}])),Di=Wt.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:di},{no:2,name:"subscription",kind:"message",T:li},{no:3,name:"publish_tracks",kind:"message",T:ai,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ni,repeated:!0},{no:5,name:"offer",kind:"message",T:di},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Mi,repeated:!0}])),Mi=Wt.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Ni=Wt.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:Wt.getEnumType(Ye)}])),Ui=Wt.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:Wt.getEnumType($e),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"}])),Li=Wt.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Bi=Wt.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Fi=Wt.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Vi,repeated:!0}])),Vi=Wt.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}])),qi=Wt.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Wt.getEnumType(re)}])),zi=Wt.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Wt.getEnumType(Ji)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:ni,oneof:"request"},{no:5,name:"add_track",kind:"message",T:ii,oneof:"request"},{no:6,name:"mute",kind:"message",T:si,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:bi,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:fi,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:vi,oneof:"request"}])),Ji=Wt.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"}]),Wi=Wt.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Gi=Wt.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}])),Qi=Wt.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:Ue},{no:2,name:"connection_settings",kind:"message",T:Gi},{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:ii,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:di},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:Wt.getEnumType(se)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Di}])),Hi=Wt.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:Wt.getEnumType(Ki)},{no:2,name:"join_request",kind:"scalar",T:12}])),Ki=Wt.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Yi=Wt.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]));function Zi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var $i,Xi,tn,en={exports:{}},nn=en.exports,sn=($i||($i=1,function(t){!function(e,i){t.exports?t.exports=i():e.log=i()}(nn,(function(){var t=function(){},e="undefined",i=typeof window!==e&&typeof window.navigator!==e&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(t,e){var i=t[e];if("function"==typeof i.bind)return i.bind(t);try{return Function.prototype.bind.call(i,t)}catch(e){return function(){return Function.prototype.apply.call(i,t,arguments)}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.call(console.log,console,arguments)),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?t:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===e&&i<this.levels.SILENT)return"No console available for logging"}function d(t){return function(){typeof console!==e&&(c.call(this),this[t].apply(this,arguments))}}function h(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==e&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):t)}(n)||d.apply(this,arguments)}function l(t,i){var o,a,d,l=this,u="loglevel";function f(){var t;if(typeof window!==e&&u){try{t=window.localStorage[u]}catch(t){}if(typeof t===e)try{var i=window.document.cookie,n=encodeURIComponent(u),s=i.indexOf(n+"=");-1!==s&&(t=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(t){}return void 0===l.levels[t]&&(t=void 0),t}}function v(t){var e=t;if("string"==typeof e&&void 0!==l.levels[e.toUpperCase()]&&(e=l.levels[e.toUpperCase()]),"number"==typeof e&&e>=0&&e<=l.levels.SILENT)return e;throw new TypeError("log.setLevel() called with invalid level: "+t)}"string"==typeof t?u+=":"+t:"symbol"==typeof t&&(u=void 0),l.name=t,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=i||h,l.getLevel=function(){return null!=d?d:null!=a?a:o},l.setLevel=function(t,i){return d=v(t),!1!==i&&function(t){var i=(n[t]||"silent").toUpperCase();if(typeof window!==e&&u){try{return void(window.localStorage[u]=i)}catch(t){}try{window.document.cookie=encodeURIComponent(u)+"="+i+";"}catch(t){}}}(d),c.call(l)},l.setDefaultLevel=function(t){a=v(t),f()||l.setLevel(t,!1)},l.resetLevel=function(){d=null,function(){if(typeof window!==e&&u){try{window.localStorage.removeItem(u)}catch(t){}try{window.document.cookie=encodeURIComponent(u)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(t){}}}(),c.call(l)},l.enableAll=function(t){l.setLevel(l.levels.TRACE,t)},l.disableAll=function(t){l.setLevel(l.levels.SILENT,t)},l.rebuild=function(){if(r!==l&&(o=v(r.getLevel())),c.call(l),r===l)for(var t in s)s[t].rebuild()},o=v(r?r.getLevel():"WARN");var m=f();null!=m&&(d=v(m)),c.call(l)}(r=new l).getLogger=function(t){if("symbol"!=typeof t&&"string"!=typeof t||""===t)throw new TypeError("You must supply a name when creating a logger.");var e=s[t];return e||(e=s[t]=new l(t,r.methodFactory)),e};var u=typeof window!==e?window.log:void 0;return r.noConflict=function(){return typeof window!==e&&window.log===r&&(window.log=u),r},r.getLoggers=function(){return s},r.default=r,r}))}(en)),en.exports);!function(t){t[t.trace=0]="trace",t[t.debug=1]="debug",t[t.info=2]="info",t[t.warn=3]="warn",t[t.error=4]="error",t[t.silent=5]="silent"}(Xi||(Xi={})),function(t){t.Default="livekit",t.Room="livekit-room",t.TokenSource="livekit-token-source",t.Participant="livekit-participant",t.Track="livekit-track",t.Publication="livekit-track-publication",t.Engine="livekit-engine",t.Signal="livekit-signal",t.PCManager="livekit-pc-manager",t.PCTransport="livekit-pc-transport",t.E2EE="lk-e2ee"}(tn||(tn={}));let rn=sn.getLogger("livekit");function on(t){const e=sn.getLogger(t);return e.setDefaultLevel(rn.getLevel()),e}Object.values(tn).map((t=>sn.getLogger(t))),rn.setDefaultLevel(Xi.info);const an=sn.getLogger("lk-e2ee"),cn=7e3,dn=[0,300,1200,2700,4800,cn,cn,cn,cn,cn];function hn(t,e,i,n){return new(i||(i=Promise))((function(s,r){function o(t){try{c(n.next(t))}catch(t){r(t)}}function a(t){try{c(n.throw(t))}catch(t){r(t)}}function c(t){t.done?s(t.value):function(t){return t instanceof i?t:new i((function(e){e(t)}))}(t.value).then(o,a)}c((n=n.apply(t,e||[])).next())}))}function ln(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,i=t[Symbol.asyncIterator];return i?i.call(t):(t=function(t){var e="function"==typeof Symbol&&Symbol.iterator,i=e&&t[e],n=0;if(i)return i.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(t),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(i){e[i]=t[i]&&function(e){return new Promise((function(n,s){!function(t,e,i,n){Promise.resolve(n).then((function(e){t({value:e,done:i})}),e)}(n,s,(e=t[i](e)).done,e.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var un,fn={exports:{}},vn=function(){if(un)return fn.exports;un=1;var t,e="object"==typeof Reflect?Reflect:null,i=e&&"function"==typeof e.apply?e.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)};t=e&&"function"==typeof e.ownKeys?e.ownKeys:Object.getOwnPropertySymbols?function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:function(t){return Object.getOwnPropertyNames(t)};var n=Number.isNaN||function(t){return t!=t};function s(){s.init.call(this)}fn.exports=s,fn.exports.once=function(t,e){return new Promise((function(i,n){function s(i){t.removeListener(e,r),n(i)}function r(){"function"==typeof t.removeListener&&t.removeListener("error",s),i([].slice.call(arguments))}v(t,e,r,{once:!0}),"error"!==e&&function(t,e){"function"==typeof t.on&&v(t,"error",e,{once:!0})}(t,s)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function o(t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}function a(t){return void 0===t._maxListeners?s.defaultMaxListeners:t._maxListeners}function c(t,e,i,n){var s,r,c;if(o(i),void 0===(r=t._events)?(r=t._events=Object.create(null),t._eventsCount=0):(void 0!==r.newListener&&(t.emit("newListener",e,i.listener?i.listener:i),r=t._events),c=r[e]),void 0===c)c=r[e]=i,++t._eventsCount;else if("function"==typeof c?c=r[e]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(t))>0&&c.length>s&&!c.warned){c.warned=!0;var d=Error("Possible EventEmitter memory leak detected. "+c.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=t,d.type=e,d.count=c.length,function(t){console&&console.warn&&console.warn(t)}(d)}return t}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 h(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function l(t,e,i){var n=t._events;if(void 0===n)return[];var s=n[e];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(t){for(var e=Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}(s):f(s,s.length)}function u(t){var e=this._events;if(void 0!==e){var i=e[t];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function f(t,e){for(var i=Array(e),n=0;n<e;++n)i[n]=t[n];return i}function v(t,e,i,n){if("function"==typeof t.on)n.once?t.once(e,i):t.on(e,i);else{if("function"!=typeof t.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t);t.addEventListener(e,(function s(r){n.once&&t.removeEventListener(e,s),i(r)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(t){if("number"!=typeof t||t<0||n(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");r=t}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||n(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var s="error"===t,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var a=Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[t];if(void 0===c)return!1;if("function"==typeof c)i(c,this,e);else{var d=c.length,h=f(c,d);for(n=0;n<d;++n)i(h[n],this,e)}return!0},s.prototype.on=s.prototype.addListener=function(t,e){return c(this,t,e,!1)},s.prototype.prependListener=function(t,e){return c(this,t,e,!0)},s.prototype.once=function(t,e){return o(e),this.on(t,h(this,t,e)),this},s.prototype.prependOnceListener=function(t,e){return o(e),this.prependListener(t,h(this,t,e)),this},s.prototype.removeListener=function(t,e){var i,n,s,r,a;if(o(e),void 0===(n=this._events))return this;if(void 0===(i=n[t]))return this;if(i===e||i.listener===e)0==--this._eventsCount?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,i.listener||e));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===e||i[r].listener===e){a=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}(i,s),1===i.length&&(n[t]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",t,a||e)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(t){var e,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[t]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[t]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(e=i[t]))this.removeListener(t,e);else if(void 0!==e)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this},s.prototype.listeners=function(t){return l(this,t,!0)},s.prototype.rawListeners=function(t){return l(this,t,!1)},s.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):u.call(t,e)},s.prototype.listenerCount=u,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]},fn.exports}();let mn=!0,pn=!0;function gn(t,e,i){const n=t.match(e);return n&&n.length>=i&&parseFloat(n[i],10)}function bn(t,e,i){if(!t.RTCPeerConnection)return;const n=t.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(t,n){if(t!==e)return s.apply(this,arguments);const r=t=>{const e=i(t);e&&(n.handleEvent?n.handleEvent(e):n(e))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(n,r),s.call(this,t,r)};const r=n.removeEventListener;n.removeEventListener=function(t,i){if(t!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(i))return r.apply(this,arguments);const n=this._eventMap[e].get(i);return this._eventMap[e].delete(i),0===this._eventMap[e].size&&delete this._eventMap[e],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.call(this,t,n)},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(t){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),t&&this.addEventListener(e,this["_on"+e]=t)},enumerable:!0,configurable:!0})}function yn(t){return"boolean"!=typeof t?Error("Argument type: "+typeof t+". Please use a boolean."):(mn=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function wn(t){return"boolean"!=typeof t?Error("Argument type: "+typeof t+". Please use a boolean."):(pn=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function kn(){if("object"==typeof window){if(mn)return;void 0!==console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Tn(t,e){pn&&console.warn(t+" is deprecated, please use "+e+" instead.")}function Sn(t){return"[object Object]"===Object.prototype.toString.call(t)}function En(t){return Sn(t)?Object.keys(t).reduce((function(e,i){const n=Sn(t[i]),s=n?En(t[i]):t[i];return void 0===s||n&&!Object.keys(s).length?e:Object.assign(e,{[i]:s})}),{}):t}function On(t,e,i){e&&!i.has(e.id)&&(i.set(e.id,e),Object.keys(e).forEach((n=>{n.endsWith("Id")?On(t,t.get(e[n]),i):n.endsWith("Ids")&&e[n].forEach((e=>{On(t,t.get(e),i)}))})))}function xn(t,e,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===e)return s;const r=[];return t.forEach((t=>{"track"===t.type&&t.trackIdentifier===e.id&&r.push(t)})),r.forEach((e=>{t.forEach((i=>{i.type===n&&i.trackId===e.id&&On(t,i,s)}))})),s}const An=kn;function Cn(t,e){const i=t&&t.navigator;if(!i.mediaDevices)return;const n=function(t){if("object"!=typeof t||t.mandatory||t.optional)return t;const e={};return Object.keys(t).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof t[i]?t[i]:{ideal:t[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(t,e){return t?t+e.charAt(0).toUpperCase()+e.slice(1):"deviceId"===e?"sourceId":e};if(void 0!==n.ideal){e.optional=e.optional||[];let t={};"number"==typeof n.ideal?(t[s("min",i)]=n.ideal,e.optional.push(t),t={},t[s("max",i)]=n.ideal,e.optional.push(t)):(t[s("",i)]=n.ideal,e.optional.push(t))}void 0!==n.exact&&"number"!=typeof n.exact?(e.mandatory=e.mandatory||{},e.mandatory[s("",i)]=n.exact):["min","max"].forEach((t=>{void 0!==n[t]&&(e.mandatory=e.mandatory||{},e.mandatory[s(t,i)]=n[t])}))})),t.advanced&&(e.optional=(e.optional||[]).concat(t.advanced)),e},s=function(t,s){if(e.version>=61)return s(t);if((t=JSON.parse(JSON.stringify(t)))&&"object"==typeof t.audio){const e=function(t,e,i){e in t&&!(i in t)&&(t[i]=t[e],delete t[e])};e((t=JSON.parse(JSON.stringify(t))).audio,"autoGainControl","googAutoGainControl"),e(t.audio,"noiseSuppression","googNoiseSuppression"),t.audio=n(t.audio)}if(t&&"object"==typeof t.video){let r=t.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=e.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let e;if(delete t.video.facingMode,"environment"===r.exact||"environment"===r.ideal?e=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(e=["front"]),e)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((t=>"videoinput"===t.kind));let o=i.find((t=>e.some((e=>t.label.toLowerCase().includes(e)))));return!o&&i.length&&e.includes("back")&&(o=i[i.length-1]),o&&(t.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),t.video=n(t.video),An("chrome: "+JSON.stringify(t)),s(t)}))}t.video=n(t.video)}return An("chrome: "+JSON.stringify(t)),s(t)},r=function(t){return e.version>=64?t:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[t.name]||t.name,message:t.message,constraint:t.constraint||t.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(t,e,n){s(t,(t=>{i.webkitGetUserMedia(t,e,(t=>{n&&n(r(t))}))}))}.bind(i),i.mediaDevices.getUserMedia){const t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(e){return s(e,(e=>t(e).then((t=>{if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach((t=>{t.stop()})),new DOMException("","NotFoundError");return t}),(t=>Promise.reject(r(t))))))}}}function _n(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function In(t){if("object"==typeof t&&t.RTCPeerConnection&&!("ontrack"in t.RTCPeerConnection.prototype)){Object.defineProperty(t.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=e=>{e.stream.addEventListener("addtrack",(i=>{let n;n=t.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((t=>t.track&&t.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[e.stream],this.dispatchEvent(s)})),e.stream.getTracks().forEach((i=>{let n;n=t.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((t=>t.track&&t.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[e.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else bn(t,"track",(t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t)))}function Rn(t){if("object"==typeof t&&t.RTCPeerConnection&&!("getSenders"in t.RTCPeerConnection.prototype)&&"createDTMFSender"in t.RTCPeerConnection.prototype){const e=function(t,e){return{track:e,get dtmf(){return void 0===this._dtmf&&(this._dtmf="audio"===e.kind?t.createDTMFSender(e):null),this._dtmf},_pc:t}};if(!t.RTCPeerConnection.prototype.getSenders){t.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(t,n){let s=i.apply(this,arguments);return s||(s=e(this,t),this._senders.push(s)),s};const n=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(t){n.apply(this,arguments);const e=this._senders.indexOf(t);-1!==e&&this._senders.splice(e,1)}}const i=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(t){this._senders=this._senders||[],i.call(this,t),t.getTracks().forEach((t=>{this._senders.push(e(this,t))}))};const n=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(t){this._senders=this._senders||[],n.call(this,t),t.getTracks().forEach((t=>{const e=this._senders.find((e=>e.track===t));e&&this._senders.splice(this._senders.indexOf(e),1)}))}}else if("object"==typeof t&&t.RTCPeerConnection&&"getSenders"in t.RTCPeerConnection.prototype&&"createDTMFSender"in t.RTCPeerConnection.prototype&&t.RTCRtpSender&&!("dtmf"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;t.RTCPeerConnection.prototype.getSenders=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t},Object.defineProperty(t.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&(this._dtmf="audio"===this.track.kind?this._pc.createDTMFSender(this.track):null),this._dtmf}})}}function jn(t){if(!("object"==typeof t&&t.RTCPeerConnection&&t.RTCRtpSender&&t.RTCRtpReceiver))return;if(!("getStats"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t});const i=t.RTCPeerConnection.prototype.addTrack;i&&(t.RTCPeerConnection.prototype.addTrack=function(){const t=i.apply(this,arguments);return t._pc=this,t}),t.RTCRtpSender.prototype.getStats=function(){const t=this;return this._pc.getStats().then((e=>xn(e,t.track,!0)))}}if(!("getStats"in t.RTCRtpReceiver.prototype)){const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t}),bn(t,"track",(t=>(t.receiver._pc=t.srcElement,t))),t.RTCRtpReceiver.prototype.getStats=function(){const t=this;return this._pc.getStats().then((e=>xn(e,t.track,!1)))}}if(!("getStats"in t.RTCRtpSender.prototype)||!("getStats"in t.RTCRtpReceiver.prototype))return;const e=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof t.MediaStreamTrack){const t=arguments[0];let e,i,n;return this.getSenders().forEach((i=>{i.track===t&&(e?n=!0:e=i)})),this.getReceivers().forEach((e=>(e.track===t&&(i?n=!0:i=e),e.track===t))),n||e&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Pn(t){t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((t=>this._shimmedLocalStreams[t][0]))};const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(t,i){if(!i)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=e.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=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(t){this._shimmedLocalStreams=this._shimmedLocalStreams||{},t.getTracks().forEach((t=>{const e=this.getSenders().find((e=>e.track===t));if(e)throw new DOMException("Track already exists.","InvalidAccessError")}));const e=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((t=>-1===e.indexOf(t)));this._shimmedLocalStreams[t.id]=[t].concat(n)};const n=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(t){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[t.id],n.apply(this,arguments)};const s=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(t){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},t&&Object.keys(this._shimmedLocalStreams).forEach((e=>{const i=this._shimmedLocalStreams[e].indexOf(t);-1!==i&&this._shimmedLocalStreams[e].splice(i,1),1===this._shimmedLocalStreams[e].length&&delete this._shimmedLocalStreams[e]})),s.apply(this,arguments)}}function Dn(t,e){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Pn(t);const i=t.RTCPeerConnection.prototype.getLocalStreams;t.RTCPeerConnection.prototype.getLocalStreams=function(){const t=i.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map((t=>this._reverseStreams[t.id]))};const n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(e){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},e.getTracks().forEach((t=>{const e=this.getSenders().find((e=>e.track===t));if(e)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[e.id]){const i=new t.MediaStream(e.getTracks());this._streams[e.id]=i,this._reverseStreams[i.id]=e,e=i}n.call(this,e)};const s=t.RTCPeerConnection.prototype.removeStream;function r(t,e){let i=e.sdp;return Object.keys(t._reverseStreams||[]).forEach((e=>{const n=t._reverseStreams[e];i=i.replace(RegExp(t._streams[n.id].id,"g"),n.id)})),new RTCSessionDescription({type:e.type,sdp:i})}t.RTCPeerConnection.prototype.removeStream=function(t){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.call(this,this._streams[t.id]||t),delete this._reverseStreams[this._streams[t.id]?this._streams[t.id].id:t.id],delete this._streams[t.id]},t.RTCPeerConnection.prototype.addTrack=function(e,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((t=>t===e)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const s=this.getSenders().find((t=>t.track===e));if(s)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(e),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new t.MediaStream([e]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((t=>t.track===e))},["createOffer","createAnswer"].forEach((function(e){const i=t.RTCPeerConnection.prototype[e],n={[e](){const t=arguments;return arguments.length&&"function"==typeof arguments[0]?i.call(this,(e=>{const i=r(this,e);t[0].call(null,i)}),(e=>{t[1]&&t[1].apply(null,e)}),arguments[2]):i.apply(this,arguments).then((t=>r(this,t)))}};t.RTCPeerConnection.prototype[e]=n[e]}));const o=t.RTCPeerConnection.prototype.setLocalDescription;t.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(t,e){let i=e.sdp;return Object.keys(t._reverseStreams||[]).forEach((e=>{const n=t._reverseStreams[e],s=t._streams[n.id];i=i.replace(RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:e.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(t.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(t.RTCPeerConnection.prototype,"localDescription",{get(){const t=a.get.apply(this);return""===t.type?t:r(this,t)}}),t.RTCPeerConnection.prototype.removeTrack=function(t){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!t._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(t._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let e;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((e=>t.track===e))&&(e=this._streams[i])})),e&&(1===e.getTracks().length?this.removeStream(this._reverseStreams[e.id]):e.removeTrack(t.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Mn(t,e){!t.RTCPeerConnection&&t.webkitRTCPeerConnection&&(t.RTCPeerConnection=t.webkitRTCPeerConnection),t.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(e){const i=t.RTCPeerConnection.prototype[e],n={[e](){return arguments[0]=new("addIceCandidate"===e?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};t.RTCPeerConnection.prototype[e]=n[e]}))}function Nn(t,e){bn(t,"negotiationneeded",(t=>{const i=t.target;if(!(e.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return t}))}var Un=Object.freeze({__proto__:null,fixNegotiationNeeded:Nn,shimAddTrackRemoveTrack:Dn,shimAddTrackRemoveTrackWithNative:Pn,shimGetSendersWithDtmf:Rn,shimGetUserMedia:Cn,shimMediaStream:_n,shimOnTrack:In,shimPeerConnection:Mn,shimSenderReceiverGetStats:jn});function Ln(t,e){const i=t&&t.navigator,n=t&&t.MediaStreamTrack;if(i.getUserMedia=function(t,e,n){Tn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(t).then(e,n)},!(e.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const t=function(t,e,i){e in t&&!(i in t)&&(t[i]=t[e],delete t[e])},e=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)),t(i.audio,"autoGainControl","mozAutoGainControl"),t(i.audio,"noiseSuppression","mozNoiseSuppression")),e(i)},n&&n.prototype.getSettings){const e=n.prototype.getSettings;n.prototype.getSettings=function(){const i=e.apply(this,arguments);return t(i,"mozAutoGainControl","autoGainControl"),t(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const e=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),t(i,"autoGainControl","mozAutoGainControl"),t(i,"noiseSuppression","mozNoiseSuppression")),e.call(this,i)}}}}function Bn(t){"object"==typeof t&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Fn(t,e){if("object"!=typeof t||!t.RTCPeerConnection&&!t.mozRTCPeerConnection)return;!t.RTCPeerConnection&&t.mozRTCPeerConnection&&(t.RTCPeerConnection=t.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(e){const i=t.RTCPeerConnection.prototype[e],n={[e](){return arguments[0]=new("addIceCandidate"===e?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};t.RTCPeerConnection.prototype[e]=n[e]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){const[t,s,r]=arguments;return n.call(this,t||null).then((t=>{if(e.version<53&&!s)try{t.forEach((t=>{t.type=i[t.type]||t.type}))}catch(e){if("TypeError"!==e.name)throw e;t.forEach(((e,n)=>{t.set(n,Object.assign({},e,{type:i[e.type]||e.type}))}))}return t})).then(s,r)}}function Vn(t){if("object"!=typeof t||!t.RTCPeerConnection||!t.RTCRtpSender)return;if(t.RTCRtpSender&&"getStats"in t.RTCRtpSender.prototype)return;const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t});const i=t.RTCPeerConnection.prototype.addTrack;i&&(t.RTCPeerConnection.prototype.addTrack=function(){const t=i.apply(this,arguments);return t._pc=this,t}),t.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function qn(t){if("object"!=typeof t||!t.RTCPeerConnection||!t.RTCRtpSender)return;if(t.RTCRtpSender&&"getStats"in t.RTCRtpReceiver.prototype)return;const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t}),bn(t,"track",(t=>(t.receiver._pc=t.srcElement,t))),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function zn(t){t.RTCPeerConnection&&!("removeStream"in t.RTCPeerConnection.prototype)&&(t.RTCPeerConnection.prototype.removeStream=function(t){Tn("removeStream","removeTrack"),this.getSenders().forEach((e=>{e.track&&t.getTracks().includes(e.track)&&this.removeTrack(e)}))})}function Jn(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function Wn(t){if("object"!=typeof t||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.addTransceiver;e&&(t.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let t=arguments[1]&&arguments[1].sendEncodings;void 0===t&&(t=[]),t=[...t];const i=t.length>0;i&&t.forEach((t=>{if("rid"in t&&!/^[a-z0-9]{0,16}$/i.test(t.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in t&&!(parseFloat(t.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in t&&!(parseFloat(t.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=e.apply(this,arguments);if(i){const{sender:e}=n,i=e.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=t,e.sendEncodings=t,this.setParametersPromises.push(e.setParameters(i).then((()=>{delete e.sendEncodings})).catch((()=>{delete e.sendEncodings}))))}return n})}function Gn(t){if("object"!=typeof t||!t.RTCRtpSender)return;const e=t.RTCRtpSender.prototype.getParameters;e&&(t.RTCRtpSender.prototype.getParameters=function(){const t=e.apply(this,arguments);return"encodings"in t||(t.encodings=[].concat(this.sendEncodings||[{}])),t})}function Qn(t){if("object"!=typeof t||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>e.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):e.apply(this,arguments)}}function Hn(t){if("object"!=typeof t||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.createAnswer;t.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>e.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):e.apply(this,arguments)}}var Kn=Object.freeze({__proto__:null,shimAddTransceiver:Wn,shimCreateAnswer:Hn,shimCreateOffer:Qn,shimGetDisplayMedia:function(t,e){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(t.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const t=new DOMException("getDisplayMedia without video constraints is undefined");return t.name="NotFoundError",t.code=8,Promise.reject(t)}return!0===i.video?i.video={mediaSource:e}:i.video.mediaSource=e,t.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Gn,shimGetUserMedia:Ln,shimOnTrack:Bn,shimPeerConnection:Fn,shimRTCDataChannel:Jn,shimReceiverGetStats:qn,shimRemoveStream:zn,shimSenderGetStats:Vn});function Yn(t){if("object"==typeof t&&t.RTCPeerConnection){if("getLocalStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in t.RTCPeerConnection.prototype)){const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addStream=function(t){this._localStreams||(this._localStreams=[]),this._localStreams.includes(t)||this._localStreams.push(t),t.getAudioTracks().forEach((i=>e.call(this,i,t))),t.getVideoTracks().forEach((i=>e.call(this,i,t)))},t.RTCPeerConnection.prototype.addTrack=function(t){for(var i=arguments.length,n=Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach((t=>{this._localStreams?this._localStreams.includes(t)||this._localStreams.push(t):this._localStreams=[t]})),e.apply(this,arguments)}}"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const e=this._localStreams.indexOf(t);if(-1===e)return;this._localStreams.splice(e,1);const i=t.getTracks();this.getSenders().forEach((t=>{i.includes(t.track)&&this.removeTrack(t)}))})}}function Zn(t){if("object"==typeof t&&t.RTCPeerConnection&&("getRemoteStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in t.RTCPeerConnection.prototype))){Object.defineProperty(t.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=t=>{t.streams.forEach((t=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(t))return;this._remoteStreams.push(t);const e=new Event("addstream");e.stream=t,this.dispatchEvent(e)}))})}});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){const t=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((e=>{if(t._remoteStreams||(t._remoteStreams=[]),t._remoteStreams.indexOf(e)>=0)return;t._remoteStreams.push(e);const i=new Event("addstream");i.stream=e,t.dispatchEvent(i)}))}),e.apply(t,arguments)}}}function $n(t){if("object"!=typeof t||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype,i=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(t,e){const n=i.call(this,arguments.length>=2?arguments[2]:arguments[0]);return e?(n.then(t,e),Promise.resolve()):n},e.createAnswer=function(t,e){const i=n.call(this,arguments.length>=2?arguments[2]:arguments[0]);return e?(i.then(t,e),Promise.resolve()):i};let a=function(t,e,i){const n=s.call(this,t);return i?(n.then(e,i),Promise.resolve()):n};e.setLocalDescription=a,a=function(t,e,i){const n=r.call(this,t);return i?(n.then(e,i),Promise.resolve()):n},e.setRemoteDescription=a,a=function(t,e,i){const n=o.call(this,t);return i?(n.then(e,i),Promise.resolve()):n},e.addIceCandidate=a}function Xn(t){const e=t&&t.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=t=>i(ts(t))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(t,i,n){e.mediaDevices.getUserMedia(t).then(i,n)}.bind(e))}function ts(t){return t&&void 0!==t.video?Object.assign({},t,{video:En(t.video)}):t}function es(t){if(!t.RTCPeerConnection)return;const e=t.RTCPeerConnection;t.RTCPeerConnection=function(t,i){if(t&&t.iceServers){const e=[];for(let i=0;i<t.iceServers.length;i++){let n=t.iceServers[i];void 0===n.urls&&n.url?(Tn("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,e.push(n)):e.push(t.iceServers[i])}t.iceServers=e}return new e(t,i)},t.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(t.RTCPeerConnection,"generateCertificate",{get:()=>e.generateCertificate})}function is(t){"object"==typeof t&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ns(t){const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(t){if(t){void 0!==t.offerToReceiveAudio&&(t.offerToReceiveAudio=!!t.offerToReceiveAudio);const e=this.getTransceivers().find((t=>"audio"===t.receiver.track.kind));!1===t.offerToReceiveAudio&&e?"sendrecv"===e.direction?e.setDirection?e.setDirection("sendonly"):e.direction="sendonly":"recvonly"===e.direction&&(e.setDirection?e.setDirection("inactive"):e.direction="inactive"):!0!==t.offerToReceiveAudio||e||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==t.offerToReceiveVideo&&(t.offerToReceiveVideo=!!t.offerToReceiveVideo);const i=this.getTransceivers().find((t=>"video"===t.receiver.track.kind));!1===t.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!==t.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function ss(t){"object"!=typeof t||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var rs,os=Object.freeze({__proto__:null,shimAudioContext:ss,shimCallbacksAPI:$n,shimConstraints:ts,shimCreateOfferLegacy:ns,shimGetUserMedia:Xn,shimLocalStreamsAPI:Yn,shimRTCIceServerUrls:es,shimRemoteStreamsAPI:Zn,shimTrackEventTransceiver:is}),as={exports:{}},cs=(rs||(rs=1,function(t){const e={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split("\n").map((t=>t.trim()))},e.splitSections=function(t){return t.split("\nm=").map(((t,e)=>(e>0?"m="+t:t).trim()+"\r\n"))},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter((t=>0===t.indexOf(i)))},e.parseCandidate=function(t){let e;e=0===t.indexOf("a=candidate:")?t.substring(12).split(" "):t.substring(10).split(" ");const i={foundation:e[0],component:{1:"rtp",2:"rtcp"}[e[1]]||e[1],protocol:e[2].toLowerCase(),priority:parseInt(e[3],10),ip:e[4],address:e[4],port:parseInt(e[5],10),type:e[7]};for(let t=8;t<e.length;t+=2)switch(e[t]){case"raddr":i.relatedAddress=e[t+1];break;case"rport":i.relatedPort=parseInt(e[t+1],10);break;case"tcptype":i.tcpType=e[t+1];break;case"ufrag":i.ufrag=e[t+1],i.usernameFragment=e[t+1];break;default:void 0===i[e[t]]&&(i[e[t]]=e[t+1])}return i},e.writeCandidate=function(t){const e=[];e.push(t.foundation);const i=t.component;e.push("rtp"===i?1:"rtcp"===i?2:i),e.push(t.protocol.toUpperCase()),e.push(t.priority),e.push(t.address||t.ip),e.push(t.port);const n=t.type;return e.push("typ"),e.push(n),"host"!==n&&t.relatedAddress&&t.relatedPort&&(e.push("raddr"),e.push(t.relatedAddress),e.push("rport"),e.push(t.relatedPort)),t.tcpType&&"tcp"===t.protocol.toLowerCase()&&(e.push("tcptype"),e.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(e.push("ufrag"),e.push(t.usernameFragment||t.ufrag)),"candidate:"+e.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let e=t.substring(9).split(" ");const i={payloadType:parseInt(e.shift(),10)};return e=e[0].split("/"),i.name=e[0],i.clockRate=parseInt(e[1],10),i.channels=3===e.length?parseInt(e[2],10):1,i.numChannels=i.channels,i},e.writeRtpMap=function(t){let e=t.payloadType;void 0!==t.preferredPayloadType&&(e=t.preferredPayloadType);const i=t.channels||t.numChannels||1;return"a=rtpmap:"+e+" "+t.name+"/"+t.clockRate+(1!==i?"/"+i:"")+"\r\n"},e.parseExtmap=function(t){const e=t.substring(9).split(" ");return{id:parseInt(e[0],10),direction:e[0].indexOf("/")>0?e[0].split("/")[1]:"sendrecv",uri:e[1],attributes:e.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&"sendrecv"!==t.direction?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+"\r\n"},e.parseFmtp=function(t){const e={};let i;const n=t.substring(t.indexOf(" ")+1).split(";");for(let t=0;t<n.length;t++)i=n[t].trim().split("="),e[i[0].trim()]=i[1];return e},e.writeFmtp=function(t){let e="",i=t.payloadType;if(void 0!==t.preferredPayloadType&&(i=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const n=[];Object.keys(t.parameters).forEach((e=>{n.push(void 0!==t.parameters[e]?e+"="+t.parameters[e]:e)})),e+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return e},e.parseRtcpFb=function(t){const e=t.substring(t.indexOf(" ")+1).split(" ");return{type:e.shift(),parameter:e.join(" ")}},e.writeRtcpFb=function(t){let e="",i=t.payloadType;return void 0!==t.preferredPayloadType&&(i=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach((t=>{e+="a=rtcp-fb:"+i+" "+t.type+(t.parameter&&t.parameter.length?" "+t.parameter:"")+"\r\n"})),e},e.parseSsrcMedia=function(t){const e=t.indexOf(" "),i={ssrc:parseInt(t.substring(7,e),10)},n=t.indexOf(":",e);return n>-1?(i.attribute=t.substring(e+1,n),i.value=t.substring(n+1)):i.attribute=t.substring(e+1),i},e.parseSsrcGroup=function(t){const e=t.substring(13).split(" ");return{semantics:e.shift(),ssrcs:e.map((t=>parseInt(t,10)))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const e=t.substring(14).split(" ");return{algorithm:e[0].toLowerCase(),value:e[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,e){let i="a=setup:"+e+"\r\n";return t.fingerprints.forEach((t=>{i+="a=fingerprint:"+t.algorithm+" "+t.value+"\r\n"})),i},e.parseCryptoLine=function(t){const e=t.substring(9).split(" ");return{tag:parseInt(e[0],10),cryptoSuite:e[1],keyParams:e[2],sessionParams:e.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+("object"==typeof t.keyParams?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+"\r\n"},e.parseCryptoKeyParams=function(t){if(0!==t.indexOf("inline:"))return null;const e=t.substring(7).split("|");return{keyMethod:"inline",keySalt:e[0],lifeTime:e[1],mkiValue:e[2]?e[2].split(":")[0]:void 0,mkiLength:e[2]?e[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const n=e.matchPrefix(t+i,"a=ice-ufrag:")[0],s=e.matchPrefix(t+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let e="a=ice-ufrag:"+t.usernameFragment+"\r\na=ice-pwd:"+t.password+"\r\n";return t.iceLite&&(e+="a=ice-lite\r\n"),e},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=e.splitLines(t)[0].split(" ");i.profile=n[2];for(let s=3;s<n.length;s++){const r=n[s],o=e.matchPrefix(t,"a=rtpmap:"+r+" ")[0];if(o){const n=e.parseRtpMap(o),s=e.matchPrefix(t,"a=fmtp:"+r+" ");switch(n.parameters=s.length?e.parseFmtp(s[0]):{},n.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+r+" ").map(e.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}e.matchPrefix(t,"a=extmap:").forEach((t=>{i.headerExtensions.push(e.parseExtmap(t))}));const s=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach((t=>{s.forEach((e=>{t.rtcpFeedback.find((t=>t.type===e.type&&t.parameter===e.parameter))||t.rtcpFeedback.push(e)}))})),i},e.writeRtpDescription=function(t,i){let n="";n+="m="+t+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((t=>void 0!==t.preferredPayloadType?t.preferredPayloadType:t.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((t=>{n+=e.writeRtpMap(t),n+=e.writeFmtp(t),n+=e.writeRtcpFb(t)}));let s=0;return i.codecs.forEach((t=>{t.maxptime>s&&(s=t.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((t=>{n+=e.writeExtmap(t)})),n},e.parseRtpEncodingParameters=function(t){const i=[],n=e.parseRtpParameters(t),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=e.matchPrefix(t,"a=ssrc:").map((t=>e.parseSsrcMedia(t))).filter((t=>"cname"===t.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=e.matchPrefix(t,"a=ssrc-group:FID").map((t=>t.substring(17).split(" ").map((t=>parseInt(t,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((t=>{if("RTX"===t.name.toUpperCase()&&t.parameters.apt){let e={ssrc:a,codecPayloadType:parseInt(t.parameters.apt,10)};a&&c&&(e.rtx={ssrc:c}),i.push(e),s&&(e=JSON.parse(JSON.stringify(e)),e.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(e))}})),0===i.length&&a&&i.push({ssrc:a});let h=e.matchPrefix(t,"b=");return h.length&&(h=0===h[0].indexOf("b=TIAS:")?parseInt(h[0].substring(7),10):0===h[0].indexOf("b=AS:")?1e3*parseInt(h[0].substring(5),10)*.95-16e3:void 0,i.forEach((t=>{t.maxBitrate=h}))),i},e.parseRtcpParameters=function(t){const i={},n=e.matchPrefix(t,"a=ssrc:").map((t=>e.parseSsrcMedia(t))).filter((t=>"cname"===t.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=e.matchPrefix(t,"a=rtcp-mux");return i.mux=r.length>0,i},e.writeRtcpParameters=function(t){let e="";return t.reducedSize&&(e+="a=rtcp-rsize\r\n"),t.mux&&(e+="a=rtcp-mux\r\n"),void 0!==t.ssrc&&t.cname&&(e+="a=ssrc:"+t.ssrc+" cname:"+t.cname+"\r\n"),e},e.parseMsid=function(t){let i;const n=e.matchPrefix(t,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=e.matchPrefix(t,"a=ssrc:").map((t=>e.parseSsrcMedia(t))).filter((t=>"msid"===t.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},e.parseSctpDescription=function(t){const i=e.parseMLine(t),n=e.matchPrefix(t,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=e.matchPrefix(t,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const t=o[0].substring(10).split(" ");return{port:parseInt(t[0],10),protocol:t[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,e){let i=[];return i="DTLS/SCTP"!==t.protocol?["m="+t.kind+" 9 "+t.protocol+" "+e.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+e.port+"\r\n"]:["m="+t.kind+" 9 "+t.protocol+" "+e.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+e.port+" "+e.protocol+" 65535\r\n"],void 0!==e.maxMessageSize&&i.push("a=max-message-size:"+e.maxMessageSize+"\r\n"),i.join("")},e.generateSessionId=function(){return(""+Math.random()).substr(2,22)},e.writeSessionBoilerplate=function(t,i,n){let s;const r=void 0!==i?i:2;return s=t||e.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},e.getDirection=function(t,i){const n=e.splitLines(t);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return"0"===t.split(" ",2)[1]},e.parseMLine=function(t){const i=e.splitLines(t)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(t){const i=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(t){if("string"!=typeof t||0===t.length)return!1;const i=e.splitLines(t);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},t.exports=e}(as)),as.exports),ds=Zi(cs),hs=d({__proto__:null,default:ds},[cs]);function ls(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;const e=t.RTCIceCandidate;t.RTCIceCandidate=function(t){if("object"==typeof t&&t.candidate&&0===t.candidate.indexOf("a=")&&((t=JSON.parse(JSON.stringify(t))).candidate=t.candidate.substring(2)),t.candidate&&t.candidate.length){const i=new e(t),n=ds.parseCandidate(t.candidate);for(const t in n)t in i||Object.defineProperty(i,t,{value:n[t]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new e(t)},t.RTCIceCandidate.prototype=e.prototype,bn(t,"icecandidate",(e=>(e.candidate&&Object.defineProperty(e,"candidate",{value:new t.RTCIceCandidate(e.candidate),writable:"false"}),e)))}function us(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||bn(t,"icecandidate",(t=>{if(t.candidate){const e=ds.parseCandidate(t.candidate.candidate);"relay"===e.type&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[e.priority>>24])}return t}))}function fs(t,e){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===e.browser&&e.version>=76){const{sdpSemantics:t}=this.getConfiguration();"plan-b"===t&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(t){if(!t||!t.sdp)return!1;const e=ds.splitSections(t.sdp);return e.shift(),e.some((t=>{const e=ds.parseMLine(t);return e&&"application"===e.kind&&-1!==e.protocol.indexOf("SCTP")}))}(arguments[0])){const t=function(t){const e=t.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===e||e.length<2)return-1;const i=parseInt(e[1],10);return i!=i?-1:i}(arguments[0]),i=function(t){let i=65536;return"firefox"===e.browser&&(i=e.version<57?-1===t?16384:2147483637:e.version<60?57===e.version?65535:65536:2147483637),i}(t),n=function(t,i){let n=65536;"firefox"===e.browser&&57===e.version&&(n=65535);const s=ds.matchPrefix(t.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===e.browser&&-1!==i&&(n=2147483637),n}(arguments[0],t);let s;s=0===i&&0===n?1/0:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function vs(t){if(!t.RTCPeerConnection||!("createDataChannel"in t.RTCPeerConnection.prototype))return;function e(t,e){const i=t.send;t.send=function(){const n=arguments[0];if("open"===t.readyState&&e.sctp&&(n.length||n.size||n.byteLength)>e.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+e.sctp.maxMessageSize+" bytes)");return i.apply(t,arguments)}}const i=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){const t=i.apply(this,arguments);return e(t,this),t},bn(t,"datachannel",(t=>(e(t.channel,t.target),t)))}function ms(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=t=>{const e=t.target;if(e._lastConnectionState!==e.connectionState){e._lastConnectionState=e.connectionState;const i=new Event("connectionstatechange",t);e.dispatchEvent(i)}return t},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function ps(t,e){if(!t.RTCPeerConnection)return;if("chrome"===e.browser&&e.version>=71)return;if("safari"===e.browser&&e._safariVersion>=13.1)return;const i=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(e){if(e&&e.sdp&&-1!==e.sdp.indexOf("\na=extmap-allow-mixed")){const i=e.sdp.split("\n").filter((t=>"a=extmap-allow-mixed"!==t.trim())).join("\n");t.RTCSessionDescription&&e instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:e.type,sdp:i}):e.sdp=i}return i.apply(this,arguments)}}function gs(t,e){if(!t.RTCPeerConnection||!t.RTCPeerConnection.prototype)return;const i=t.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===e.browser&&e.version<78||"firefox"===e.browser&&e.version<68||"safari"===e.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function bs(t){if(!t.RTCPeerConnection||!t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype.setLocalDescription;e&&0!==e.length&&(t.RTCPeerConnection.prototype.setLocalDescription=function(){let t=arguments[0]||{};if("object"!=typeof t||t.type&&t.sdp)return e.apply(this,arguments);if(t={type:t.type,sdp:t.sdp},!t.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":t.type="offer";break;default:t.type="answer"}return t.sdp||"offer"!==t.type&&"answer"!==t.type?e.call(this,t):("offer"===t.type?this.createOffer:this.createAnswer).apply(this).then((t=>e.call(this,t)))})}var ys=Object.freeze({__proto__:null,removeExtmapAllowMixed:ps,shimAddIceCandidateNullOrEmpty:gs,shimConnectionState:ms,shimMaxMessageSize:fs,shimParameterlessSetLocalDescription:bs,shimRTCIceCandidate:ls,shimRTCIceCandidateRelayProtocol:us,shimSendThrowTypeError:vs});!function(){let{window:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=kn,n=function(t){const e={browser:null,version:null};if(void 0===t||!t.navigator||!t.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:i}=t;if(i.userAgentData&&i.userAgentData.brands){const t=i.userAgentData.brands.find((t=>"Chromium"===t.brand));if(t)return{browser:"chrome",version:parseInt(t.version,10)}}if(i.mozGetUserMedia)e.browser="firefox",e.version=parseInt(gn(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===t.isSecureContext&&t.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(gn(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!t.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return e.browser="Not a supported browser.",e;e.browser="safari",e.version=parseInt(gn(i.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype,e._safariVersion=gn(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return e}(t),s={browserDetails:n,commonShim:ys,extractVersion:gn,disableLog:yn,disableWarnings:wn,sdp:hs};switch(n.browser){case"chrome":if(!Un||!Mn||!e.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=Un,gs(t,n),bs(t),Cn(t,n),_n(t),Mn(t,n),In(t),Dn(t,n),Rn(t),jn(t),Nn(t,n),ls(t),us(t),ms(t),fs(t,n),vs(t),ps(t,n);break;case"firefox":if(!Kn||!Fn||!e.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Kn,gs(t,n),bs(t),Ln(t,n),Fn(t,n),Bn(t),zn(t),Vn(t),qn(t),Jn(t),Wn(t),Gn(t),Qn(t),Hn(t),ls(t),ms(t),fs(t,n),vs(t);break;case"safari":if(!os||!e.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=os,gs(t,n),bs(t),es(t),ns(t),$n(t),Yn(t),Zn(t),is(t),Xn(t),ss(t),ls(t),us(t),fs(t,n),vs(t),ps(t,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class ws extends Promise{constructor(t){super(t)}catch(t){return super.catch(t)}static reject(t){return super.reject(t)}static all(t){return super.all(t)}static race(t){return super.race(t)}}const ks=/version\/(\d+(\.?_?\d+)+)/i;let Ts;function Ss(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const i=navigator.userAgent.toLowerCase();if(void 0===Ts||e){const t=Es.find((t=>{let{test:e}=t;return e.test(i)}));Ts=null==t?void 0:t.describe(i)}return Ts}const Es=[{test:/firefox|iceweasel|fxios/i,describe:t=>({name:"Firefox",version:Os(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:xs(t)})},{test:/chrom|crios|crmo/i,describe:t=>({name:"Chrome",version:Os(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:xs(t)})},{test:/safari|applewebkit/i,describe:t=>({name:"Safari",version:Os(ks,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:xs(t)})}];function Os(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=e.match(t);return n&&n.length>=i&&n[i]||""}function xs(t){return t.includes("mac os")?Os(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}class As extends Error{constructor(t,e){super(e||"an error has occured"),this.name="LiveKitError",this.code=t}}var Cs,_s,Is,Rs,js,Ps,Ds;!function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout",t[t.WebSocket=6]="WebSocket",t[t.ServiceNotFound=7]="ServiceNotFound"}(Cs||(Cs={}));class Ms extends As{constructor(t,e,i,n){super(1,t),this.name="ConnectionError",this.status=i,this.reason=e,this.context=n,this.reasonName=Cs[e]}static notAllowed(t,e,i){return new Ms(t,Cs.NotAllowed,e,i)}static timeout(t){return new Ms(t,Cs.Timeout)}static leaveRequest(t,e){return new Ms(t,Cs.LeaveRequest,void 0,e)}static internal(t,e){return new Ms(t,Cs.InternalError,void 0,e)}static cancelled(t){return new Ms(t,Cs.Cancelled)}static serverUnreachable(t,e){return new Ms(t,Cs.ServerUnreachable,e)}static websocket(t,e,i){return new Ms(t,Cs.WebSocket,e,i)}static serviceNotFound(t,e){return new Ms(t,Cs.ServiceNotFound,void 0,e)}}class Ns extends As{constructor(t){super(21,null!=t?t:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Us extends As{constructor(t){super(20,null!=t?t:"track is invalid"),this.name="TrackInvalidError"}}class Ls extends As{constructor(t){super(10,null!=t?t:"unsupported server"),this.name="UnsupportedServer"}}class Bs extends As{constructor(t){super(12,null!=t?t:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Fs extends As{constructor(t){super(13,null!=t?t:"unable to negotiate"),this.name="NegotiationError"}}class Vs extends As{constructor(t,e){super(15,t),this.name="PublishTrackError",this.status=e}}class qs extends As{constructor(t,e){super(15,t),this.name="SignalRequestError",this.reason=e,this.reasonName="string"==typeof e?e:Ji[e]}}!function(t){t[t.AlreadyOpened=0]="AlreadyOpened",t[t.AbnormalEnd=1]="AbnormalEnd",t[t.DecodeFailed=2]="DecodeFailed",t[t.LengthExceeded=3]="LengthExceeded",t[t.Incomplete=4]="Incomplete",t[t.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",t[t.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(_s||(_s={}));class zs extends As{constructor(t,e){super(16,t),this.name="DataStreamError",this.reason=e,this.reasonName=_s[e]}}class Js extends As{constructor(t){super(18,t),this.name="SignalReconnectError"}}!function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"}(Is||(Is={})),function(t){t.getFailure=function(e){if(e&&"name"in e)return"NotFoundError"===e.name||"DevicesNotFoundError"===e.name?t.NotFound:"NotAllowedError"===e.name||"PermissionDeniedError"===e.name?t.PermissionDenied:"NotReadableError"===e.name||"TrackStartError"===e.name?t.DeviceInUse:t.Other}}(Is||(Is={}));class Ws{}function Gs(t){return void 0===t?t:"function"==typeof structuredClone?"object"==typeof t&&null!==t?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}Ws.setTimeout=function(){return setTimeout(...arguments)},Ws.setInterval=function(){return setInterval(...arguments)},Ws.clearTimeout=function(){return clearTimeout(...arguments)},Ws.clearInterval=function(){return clearInterval(...arguments)},function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"}(Rs||(Rs={})),function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackCpuConstrained="localTrackCpuConstrained",t.LocalSenderCreated="localSenderCreated",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.TrackCpuConstrained="trackCpuConstrained",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"}(js||(js={})),function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"}(Ps||(Ps={})),function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.CpuConstrained="cpuConstrained",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"}(Ds||(Ds={}));class Qs{constructor(t,e,i,n,s){if("object"==typeof t)this.width=t.width,this.height=t.height,this.aspectRatio=t.aspectRatio,this.encoding={maxBitrate:t.maxBitrate,maxFramerate:t.maxFramerate,priority:t.priority};else{if(void 0===e||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=t,this.height=e,this.aspectRatio=t/e,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Hs=["vp8","h264"],Ks=["vp8","h264","vp9","av1","h265"],Ys=function(t){return!!Hs.find((e=>e===t))};var Zs,$s;!function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"}(Zs||(Zs={})),function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}}($s||($s={}));const Xs={h90:new Qs(160,90,9e4,20),h180:new Qs(320,180,16e4,20),h216:new Qs(384,216,18e4,20),h360:new Qs(640,360,45e4,20),h540:new Qs(960,540,8e5,25),h720:new Qs(1280,720,17e5,30),h1080:new Qs(1920,1080,3e6,30),h1440:new Qs(2560,1440,5e6,30),h2160:new Qs(3840,2160,8e6,30)},tr={h120:new Qs(160,120,7e4,20),h180:new Qs(240,180,125e3,20),h240:new Qs(320,240,14e4,20),h360:new Qs(480,360,33e4,20),h480:new Qs(640,480,5e5,20),h540:new Qs(720,540,6e5,25),h720:new Qs(960,720,13e5,30),h1080:new Qs(1440,1080,23e5,30),h1440:new Qs(1920,1440,38e5,30)},er={h360fps3:new Qs(640,360,2e5,3,"medium"),h360fps15:new Qs(640,360,4e5,15,"medium"),h720fps5:new Qs(1280,720,8e5,5,"medium"),h720fps15:new Qs(1280,720,15e5,15,"medium"),h720fps30:new Qs(1280,720,2e6,30,"medium"),h1080fps15:new Qs(1920,1080,25e5,15,"medium"),h1080fps30:new Qs(1920,1080,5e6,30,"medium"),original:new Qs(0,0,7e6,30,"medium")};function ir(t,e,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=lr(null!=t?t:{}),h=null==e?void 0:e.processor,l=null==i?void 0:i.processor,u=null!=a?a:{};return!0===u.audio&&(u.audio={}),!0===u.video&&(u.video={}),u.audio&&(nr(u.audio,e),null!==(n=(r=u.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||h)&&(u.audio.processor=null!=c?c:h)),u.video&&(nr(u.video,i),null!==(s=(o=u.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(d||l)&&(u.video.processor=null!=d?d:l)),u}function nr(t,e){return Object.keys(e).forEach((i=>{void 0===t[i]&&(t[i]=e[i])})),t}function sr(t){var e,i,n,s;const r={};if(t.video)if("object"==typeof t.video){const i={},s=i,o=t.video;Object.keys(o).forEach((t=>{"resolution"===t?nr(s,o.resolution):s[t]=o[t]})),r.video=i,null!==(e=(n=r.video).deviceId)&&void 0!==e||(n.deviceId={ideal:"default"})}else r.video=!!t.video&&{deviceId:{ideal:"default"}};else r.video=!1;return t.audio?"object"==typeof t.audio?(r.audio=t.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function rr(){var t;const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e){const i=new e({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(t=window.document)||void 0===t?void 0:t.body)){const t=()=>hn(this,void 0,void 0,(function*(){var e;try{"suspended"===i.state&&(yield i.resume())}catch(t){console.warn("Error trying to auto-resume audio context",t)}finally{null===(e=window.document.body)||void 0===e||e.removeEventListener("click",t)}}));i.addEventListener("statechange",(()=>{var e;"closed"===i.state&&(null===(e=window.document.body)||void 0===e||e.removeEventListener("click",t))})),window.document.body.addEventListener("click",t)}return i}}function or(t){return"audioinput"===t?mr.Source.Microphone:"videoinput"===t?mr.Source.Camera:mr.Source.Unknown}function ar(t){return t===mr.Source.Microphone?"audioinput":t===mr.Source.Camera?"videoinput":void 0}function cr(t){return t.split("/")[1].toLowerCase()}function dr(t){const e=[];return t.forEach((t=>{void 0!==t.track&&e.push(new ai({cid:t.track.mediaStreamID,track:t.trackInfo}))})),e}function hr(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?hr(t.track):{})}}function lr(t){const e=Object.assign({},t);let i,n;return"object"==typeof e.audio&&e.audio.processor&&(i=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),"object"==typeof e.video&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:Gs(e)}}function ur(t,e){return t.width*t.height<e.width*e.height}const fr=[];var vr;!function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"}(vr||(vr={}));class mr extends vn.EventEmitter{get streamState(){return this._streamState}setStreamState(t){this._streamState=t}constructor(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=mr.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=rn,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=on(null!==(n=i.loggerName)&&void 0!==n?n:tn.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=e,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=mr.Source.Unknown}get logContext(){var t;return Object.assign(Object.assign({},null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this)),hr(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let e="audio";this.kind===mr.Kind.Video&&(e="video"),0===this.attachedElements.length&&this.kind===mr.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===e&&(fr.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&fr.splice(fr.indexOf(t),1)),t||(t=document.createElement(e))),this.attachedElements.includes(t)||this.attachedElements.push(t),pr(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),n=i.some((t=>"audio"===t.kind));return t.play().then((()=>{this.emit(n?Ds.AudioPlaybackStarted:Ds.VideoPlaybackStarted)})).catch((e=>{"NotAllowedError"===e.name?this.emit(n?Ds.AudioPlaybackFailed:Ds.VideoPlaybackFailed,e):"AbortError"===e.name?rn.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):rn.warn("could not playback ".concat(n?"audio":"video"),e),n&&t&&i.some((t=>"video"===t.kind))&&"NotAllowedError"===e.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(Ds.ElementAttached,t),t}detach(t){try{if(t){gr(this.mediaStreamTrack,t);const e=this.attachedElements.indexOf(t);return e>=0&&(this.attachedElements.splice(e,1),this.recycleElement(t),this.emit(Ds.ElementDetached,t)),t}const e=[];return this.attachedElements.forEach((t=>{gr(this.mediaStreamTrack,t),e.push(t),this.recycleElement(t),this.emit(Ds.ElementDetached,t)})),this.attachedElements=[],e}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(t){t.loggerName&&(this.log=on(t.loggerName)),t.loggerContextCb&&(this.loggerContextCb=t.loggerContextCb)}recycleElement(t){if(t instanceof HTMLAudioElement){let e=!0;t.pause(),fr.forEach((t=>{t.parentElement||(e=!1)})),e&&fr.push(t)}}handleAppVisibilityChanged(){return hn(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==mr.Kind.Video||setTimeout((()=>this.attachedElements.forEach((t=>t.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){_r()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){_r()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function pr(t,e){let i,n;i=e.srcObject instanceof MediaStream?e.srcObject:new MediaStream,n="audio"===t.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(t)||(n.forEach((t=>{i.removeTrack(t)})),i.addTrack(t)),xr()&&e instanceof HTMLVideoElement||(e.autoplay=!0),e.muted=0===i.getAudioTracks().length,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==i&&(e.srcObject=i,(xr()||Er())&&e instanceof HTMLVideoElement&&setTimeout((()=>{e.srcObject=i,e.play().catch((()=>{}))}),0))}function gr(t,e){if(e.srcObject instanceof MediaStream){const i=e.srcObject;i.removeTrack(t),e.srcObject=i.getTracks().length>0?i:null}}!function(t){let e,i,n;!function(t){t.Audio="audio",t.Video="video",t.Unknown="unknown"}(e=t.Kind||(t.Kind={})),function(t){t.Camera="camera",t.Microphone="microphone",t.ScreenShare="screen_share",t.ScreenShareAudio="screen_share_audio",t.Unknown="unknown"}(i=t.Source||(t.Source={})),function(t){t.Active="active",t.Paused="paused",t.Unknown="unknown"}(n=t.StreamState||(t.StreamState={})),t.kindToProto=function(t){switch(t){case e.Audio:return $t.AUDIO;case e.Video:return $t.VIDEO;default:return $t.DATA}},t.kindFromProto=function(t){switch(t){case $t.AUDIO:return e.Audio;case $t.VIDEO:return e.Video;default:return e.Unknown}},t.sourceToProto=function(t){switch(t){case i.Camera:return Xt.CAMERA;case i.Microphone:return Xt.MICROPHONE;case i.ScreenShare:return Xt.SCREEN_SHARE;case i.ScreenShareAudio:return Xt.SCREEN_SHARE_AUDIO;default:return Xt.UNKNOWN}},t.sourceFromProto=function(t){switch(t){case Xt.CAMERA:return i.Camera;case Xt.MICROPHONE:return i.Microphone;case Xt.SCREEN_SHARE:return i.ScreenShare;case Xt.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},t.streamStateFromProto=function(t){switch(t){case Ze.ACTIVE:return n.Active;case Ze.PAUSED:return n.Paused;default:return n.Unknown}}}(mr||(mr={}));const br="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function yr(t){return new ws((e=>Ws.setTimeout(e,t)))}function wr(){return"addTransceiver"in RTCPeerConnection.prototype}function kr(){return"addTrack"in RTCPeerConnection.prototype}function Tr(t){return"av1"===t||"vp9"===t}function Sr(t){return!(!document||Ar())&&(t||(t=document.createElement("audio")),"setSinkId"in t)}function Er(){var t;return"Firefox"===(null===(t=Ss())||void 0===t?void 0:t.name)}function Or(){const t=Ss();return!!t&&"Chrome"===t.name&&"iOS"!==t.os}function xr(){var t;return"Safari"===(null===(t=Ss())||void 0===t?void 0:t.name)}function Ar(){const t=Ss();return"Safari"===(null==t?void 0:t.name)||"iOS"===(null==t?void 0:t.os)}function Cr(){var t,e;return!!_r()&&(null!==(e=null===(t=navigator.userAgentData)||void 0===t?void 0:t.mobile)&&void 0!==e?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function _r(){return"undefined"!=typeof document}function Ir(){return"ReactNative"==navigator.product}function Rr(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function jr(t){return Rr(t)?t.hostname.split(".")[0]:null}function Pr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Dr(){if(!Ir())return;let t=Pr();return t?t.platform:void 0}function Mr(){if(_r())return window.devicePixelRatio;if(Ir()){let t=Pr();if(t)return t.devicePixelRatio}return 1}function Nr(t,e){const i=t.split("."),n=e.split("."),s=Math.min(i.length,n.length);for(let t=0;t<s;++t){const e=parseInt(i[t],10),r=parseInt(n[t],10);if(e>r)return 1;if(e<r)return-1;if(t===s-1&&e===r)return 0}return""===t&&""!==e?-1:""===e?1:i.length==n.length?0:i.length<n.length?-1:1}function Ur(t){for(const e of t)e.target.handleResize(e)}function Lr(t){for(const e of t)e.target.handleVisibilityChanged(e)}let Br=null;const Fr=()=>(Br||(Br=new ResizeObserver(Ur)),Br);let Vr=null;const qr=()=>(Vr||(Vr=new IntersectionObserver(Lr,{root:null,rootMargin:"0px"})),Vr);function zr(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=t,s.height=e;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(t/2,e/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let Jr;function Wr(){if(!Jr){const t=new AudioContext,e=t.createOscillator(),i=t.createGain();i.gain.setValueAtTime(0,0);const n=t.createMediaStreamDestination();if(e.connect(i),i.connect(n),e.start(),[Jr]=n.stream.getAudioTracks(),!Jr)throw Error("Could not get empty media stream audio track");Jr.enabled=!1}return Jr.clone()}class Gr{get isResolved(){return this._isResolved}constructor(t,e){this._isResolved=!1,this.onFinally=e,this.promise=new Promise(((e,i)=>hn(this,void 0,void 0,(function*(){this.resolve=e,this.reject=i,t&&(yield t(e,i))})))).finally((()=>{var t;this._isResolved=!0,null===(t=this.onFinally)||void 0===t||t.call(this)}))}}function Qr(t){if("string"==typeof t||"number"==typeof t)return t;if(Array.isArray(t))return t[0];if(void 0!==t.exact)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(void 0!==t.ideal)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function Hr(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function Kr(t){switch(t.reason){case Cs.LeaveRequest:return t.context;case Cs.Cancelled:return ne.CLIENT_INITIATED;case Cs.NotAllowed:return ne.USER_REJECTED;case Cs.ServerUnreachable:return ne.JOIN_FAILURE;default:return ne.UNKNOWN_REASON}}function Yr(t){return void 0!==t?Number(t):void 0}function Zr(t){return void 0!==t?BigInt(t):void 0}function $r(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function Xr(t){return!!t&&t.kind==mr.Kind.Audio}function to(t){return!!t&&t.kind==mr.Kind.Video}function eo(t){return $r(t)&&to(t)}function io(t){return $r(t)&&Xr(t)}function no(t){return!!t&&!t.isLocal}function so(t){return!!t&&!t.isLocal}function ro(t){return no(t)&&to(t)}function oo(t){return t.endsWith("/")?t:"".concat(t,"/")}function ao(t,e){return t.pathname="".concat(oo(t.pathname)).concat(e),t}function co(t){if("string"==typeof t)return ti.fromJson(JSON.parse(t),{ignoreUnknownFields:!0});if(t instanceof ArrayBuffer)return ti.fromBinary(new Uint8Array(t));throw Error("could not decode websocket message: ".concat(typeof t))}const ho="lk_e2ee";var lo,uo,fo,vo,mo;function po(){return void 0!==window.RTCRtpScriptTransform}!function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"}(lo||(lo={})),function(t){t.KeyRatcheted="keyRatcheted"}(uo||(uo={})),function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"}(fo||(fo={})),function(t){t.Error="cryptorError"}(vo||(vo={})),function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"}(mo||(mo={}));class go extends vn.EventEmitter{constructor(t,e){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=t=>{var e,i;const{kind:n,data:s}=t.data;switch(n){case"error":if(rn.error(s.error.message),s.uuid){const t=this.decryptDataRequests.get(s.uuid);if(null==t?void 0:t.reject){t.reject(s.error);break}const e=this.encryptDataRequests.get(s.uuid);if(null==e?void 0:e.reject){e.reject(s.error);break}}this.emit(fo.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((t=>{this.postKey(t)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((t=>{this.postKey(t)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(e=this.room)||void 0===e?void 0:e.localParticipant.identity))this.emit(fo.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const t=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(fo.ParticipantEncryptionStatusChanged,s.enabled,t)}break;case"ratchetKey":this.keyProvider.emit(lo.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const t=this.decryptDataRequests.get(s.uuid);(null==t?void 0:t.resolve)&&t.resolve(s);break;case"encryptDataResponse":const n=this.encryptDataRequests.get(s.uuid);(null==n?void 0:n.resolve)&&n.resolve(s)}},this.onWorkerError=t=>{rn.error("e2ee worker encountered an error:",{error:t.error}),this.emit(fo.EncryptionError,t.error,void 0)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=e}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(t){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||po()))throw new Ns("tried to setup end-to-end encryption on an unsupported browser");if(rn.info("setting up e2ee"),t!==this.room){this.room=t,this.setupEventListeners(t,this.keyProvider);const e={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:an.getLevel()}};this.worker&&(rn.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(e))}}setParticipantCryptorEnabled(t,e){rn.debug("set e2ee to ".concat(t," for participant ").concat(e)),this.postEnable(t,e)}setSifTrailer(t){t&&0!==t.length?this.postSifTrailer(t):rn.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(Ps.RTPVideoMapUpdate,(t=>{this.postRTPMap(t)}))}setupEventListeners(t,e){t.on(Rs.TrackPublished,((t,e)=>this.setParticipantCryptorEnabled(t.trackInfo.encryption!==ve.NONE,e.identity))),t.on(Rs.ConnectionStateChanged,(e=>{e===Na.Connected&&t.remoteParticipants.forEach((t=>{t.trackPublications.forEach((e=>{this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ve.NONE,t.identity)}))}))})).on(Rs.TrackUnsubscribed,((t,e,i)=>{var n;null===(n=this.worker)||void 0===n||n.postMessage({kind:"removeTransform",data:{participantIdentity:i.identity,trackId:t.mediaStreamID}})})).on(Rs.TrackSubscribed,((t,e,i)=>{this.setupE2EEReceiver(t,i.identity,e.trackInfo)})).on(Rs.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");e.getKeys().forEach((t=>{this.postKey(t)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),t.localParticipant.on(js.LocalSenderCreated,((t,e)=>hn(this,void 0,void 0,(function*(){this.setupE2EESender(e,t)})))),t.localParticipant.on(js.LocalTrackPublished,(t=>{if(!to(t.track)||!Ar())return;const e={kind:"updateCodec",data:{trackId:t.track.mediaStreamID,codec:cr(t.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(e)})),e.on(lo.SetKey,(t=>this.postKey(t))).on(lo.RatchetRequest,((t,e)=>this.postRatchetRequest(t,e)))}encryptData(t){return hn(this,void 0,void 0,(function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const e=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:e,payload:t,participantIdentity:this.room.localParticipant.identity}},n=new Gr;return n.onFinally=()=>{this.encryptDataRequests.delete(e)},this.encryptDataRequests.set(e,n),this.worker.postMessage(i),n.promise}))}handleEncryptedData(t,e,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),r={kind:"decryptDataRequest",data:{uuid:s,payload:t,iv:e,participantIdentity:i,keyIndex:n}},o=new Gr;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(r),o.promise}postRatchetRequest(t,e){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:t,keyIndex:e}})}postKey(t){let{key:e,participantIdentity:i,keyIndex:n}=t;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:e,keyIndex:n}};this.worker.postMessage(r)}postEnable(t,e){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");this.worker.postMessage({kind:"enable",data:{enabled:t,participantIdentity:e}})}postRTPMap(t){var e;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(e=this.room)||void 0===e?void 0:e.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");this.worker.postMessage({kind:"setRTPMap",data:{map:t,participantIdentity:this.room.localParticipant.identity}})}postSifTrailer(t){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:t}})}setupE2EEReceiver(t,e,i){if(t.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(t.receiver,t.mediaStreamID,e,"video"===t.kind?cr(i.mimeType):void 0)}}setupE2EESender(t,e){$r(t)&&e?this.handleSender(e,t.mediaStreamID,void 0):e||rn.warn("early return because sender is not ready")}handleReceiver(t,e,i,n){return hn(this,void 0,void 0,(function*(){if(this.worker){if(po()&&!Or())t.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:e,codec:n});else{if(ho in t&&n)return void this.worker.postMessage({kind:"updateCodec",data:{trackId:e,codec:n,participantIdentity:i}});let s=t.writableStream,r=t.readableStream;if(!s||!r){const e=t.createEncodedStreams();t.writableStream=e.writable,s=e.writable,t.readableStream=e.readable,r=e.readable}this.worker.postMessage({kind:"decode",data:{readableStream:r,writableStream:s,trackId:e,codec:n,participantIdentity:i,isReuse:ho in t}},[r,s])}t[ho]=!0}}))}handleSender(t,e,i){var n;if(!(ho in t)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(po()&&!Or())rn.info("initialize script transform"),t.transform=new RTCRtpScriptTransform(this.worker,{kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:e,codec:i});else{rn.info("initialize encoded streams");const n=t.createEncodedStreams();this.worker.postMessage({kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:e,participantIdentity:this.room.localParticipant.identity,isReuse:!1}},[n.readable,n.writable])}t[ho]=!0}}}class bo{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new bo),this._instance}addFailedConnectionAttempt(t){var e;const i=jr(new URL(t));if(!i)return;let n=null!==(e=this.failedConnectionAttempts.get(i))&&void 0!==e?e:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,yr(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(t){const e=new URL(t),i=e&&jr(e);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(t){const e=new URL(t),i=e&&jr(e);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}bo._instance=null;const yo="default";class wo{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new wo),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=wo.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){rn.debug("awaiting getUserMedia promise");try{t?yield wo.userMediaPromiseMap.get(t):yield Promise.all(wo.userMediaPromiseMap.values())}catch(t){rn.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!xr()||!e.hasDeviceInUse(t))){const e=0===s.filter((e=>e.kind===t)).length||s.some((e=>""===e.label&&(!t||e.kind===t)));if(e){const e={video:"audioinput"!==t&&"audiooutput"!==t,audio:"videoinput"!==t&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(e);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((t=>{t.stop()}))}}return e._previousDevices=s,t&&(s=s.filter((e=>e.kind===t))),s}()}))}normalizeDeviceId(t,e,i){return hn(this,void 0,void 0,(function*(){if(e!==yo)return e;const n=yield this.getDevices(t),s=n.find((t=>t.deviceId===yo));if(!s)return void rn.warn("could not reliably determine default device");const r=n.find((t=>t.deviceId!==yo&&t.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;rn.warn("could not reliably determine default device")}))}hasDeviceInUse(t){return t?wo.userMediaPromiseMap.has(t):wo.userMediaPromiseMap.size>0}}var ko;wo.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],wo.userMediaPromiseMap=new Map,function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"}(ko||(ko={}));class To{constructor(){this.pendingTasks=new Map,this.taskMutex=new u,this.nextTaskIndex=0}run(t){return hn(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ko.WAITING};this.pendingTasks.set(e.id,e);const i=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=ko.RUNNING,yield t()}finally{e.status=ko.COMPLETED,this.pendingTasks.delete(e.id),i()}}))}flush(){return hn(this,void 0,void 0,(function*(){return this.run((()=>hn(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}class So{get readyState(){return this.ws.readyState}constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;if(null===(i=e.signal)||void 0===i?void 0:i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=t;const s=new WebSocket(t,null!==(n=e.protocols)&&void 0!==n?n:[]);s.binaryType="arraybuffer",this.ws=s;const r=function(){let{closeCode:t,reason:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return s.close(t,e)};this.opened=new ws(((t,e)=>{const i=()=>{e(Ms.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{t({readable:new ReadableStream({start(t){s.onmessage=e=>{let{data:i}=e;return t.enqueue(i)},s.onerror=e=>t.error(e)},cancel:r}),writable:new WritableStream({write(t){s.send(t)},abort(){s.close()},close:r}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",i)},s.addEventListener("error",i)})),this.closed=new ws(((t,e)=>{const i=()=>hn(this,void 0,void 0,(function*(){const i=new ws((t=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",(e=>{t(e)}),{once:!0})})),n=yield ws.race([yr(250),i]);n?t(n):e(Ms.websocket("Encountered unspecified websocket error without a timely close event"))}));s.onclose=e=>{let{code:n,reason:r}=e;t({closeCode:n,reason:r}),s.removeEventListener("error",i)},s.addEventListener("error",i)})),e.signal&&(e.signal.onabort=()=>s.close()),this.close=r}}const Eo=["syncState","trickle","offer","answer","simulate","leave"];var Oo;!function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"}(Oo||(Oo={}));class xo{get currentState(){return this.state}get isDisconnected(){return this.state===Oo.DISCONNECTING||this.state===Oo.DISCONNECTED}get isEstablishingConnection(){return this.state===Oo.CONNECTING||this.state===Oo.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Oo.DISCONNECTED,this.log=rn,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=on(null!==(i=e.loggerName)&&void 0!==i?i:tn.Signal),this.loggerContextCb=e.loggerContextCb,this.useJSON=t,this.requestQueue=new To,this.queuedRequests=[],this.closingLock=new u,this.connectionLock=new u,this.state=Oo.DISCONNECTED}get logContext(){var t,e;return null!==(e=null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this))&&void 0!==e?e:{}}join(t,e,i,n){return hn(this,arguments,void 0,(function(t,e,i,n){var s=this;let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){return s.state=Oo.CONNECTING,s.options=i,yield s.connect(t,e,i,n,r)}()}))}reconnect(t,e,i,n){return hn(this,void 0,void 0,(function*(){if(this.options)return this.state=Oo.RECONNECTING,this.clearPingInterval(),yield this.connect(t,e,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath);this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)}))}connect(t,e,i,n){return hn(this,arguments,void 0,(function(t,e,i,n){var s=this;let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){const o=yield s.connectionLock.lock();s.connectOptions=i,s.useV0SignalPath=r;const a=function(){var t;const e=new Ue({sdk:Le.JS,protocol:16,version:"2.17.0"});return Ir()&&(e.os=null!==(t=Dr())&&void 0!==t?t:""),e}(),c=r?function(t,e,i){var n;const s=new URLSearchParams;return s.set("access_token",t),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid)),s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",Ir()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",""+e.protocol),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),i.adaptiveStream&&s.set("adaptive_stream","1"),i.reconnectReason&&s.set("reconnect_reason",""+i.reconnectReason),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type),s}(e,a,i):function(t,e,i){const n=new URLSearchParams;n.set("access_token",t);const s=new Qi({clientInfo:e,connectionSettings:new Gi({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0});i.reconnectReason&&(s.reconnectReason=i.reconnectReason);const r=new Hi({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}(e,a,i),d=""+function(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=function(t,e){const i=new URL(function(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}(t));return e.forEach(((t,e)=>{i.searchParams.set(e,t)})),ao(i,"rtc")}(t,e);return i?n:ao(n,"v1")}(t,c,r),h=""+function(t){return ao(new URL(Hr(t)),"validate")}(d);return new Promise(((t,e)=>hn(s,void 0,void 0,(function*(){var s,r;try{let o=!1;const a=t=>hn(this,void 0,void 0,(function*(){if(o)return;o=!0;const i=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(t instanceof AbortSignal))return e;const i=t.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:e;default:return"toString"in i?""+i:e}}(t instanceof Event?t.currentTarget:t,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then((()=>this.close(i))).catch((t=>{this.log.error(t),this.close()})):this.close(),c(),e(Ms.cancelled(i))}));null==n||n.addEventListener("abort",a);const c=()=>{clearTimeout(l),null==n||n.removeEventListener("abort",a)},l=setTimeout((()=>{a(Ms.timeout("room connection has timed out (signal)"))}),i.websocketTimeout),u=(t,e)=>{this.handleSignalConnected(t,l,e)},f=new URL(d);f.searchParams.has("access_token")&&f.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(f),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new So(d);try{this.ws.closed.then((t=>{var i;this.isEstablishingConnection&&e(Ms.internal("Websocket got closed during a (re)connection attempt: ".concat(t.reason))),1e3!==t.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:t.reason,code:t.closeCode,wasClean:1e3===t.closeCode,state:this.state})),this.state===Oo.CONNECTED&&this.handleOnClose(null!==(i=t.reason)&&void 0!==i?i:"Unexpected WS error"))})).catch((t=>{this.isEstablishingConnection&&e(Ms.internal("Websocket error during a (re)connection attempt: ".concat(t)))}));const n=yield this.ws.opened.catch((t=>hn(this,void 0,void 0,(function*(){if(this.state===Oo.CONNECTED)this.handleWSError(t),e(t);else{this.state=Oo.DISCONNECTED,clearTimeout(l);const i=yield this.handleConnectionError(t,h);e(i)}}))));if(clearTimeout(l),!n)return;const o=n.readable.getReader();this.streamWriter=n.writable.getWriter();const a=yield o.read();if(o.releaseLock(),!a.value)throw Ms.internal("no message received as first message");const c=co(a.value),d=this.validateFirstMessage(c,null!==(s=i.reconnect)&&void 0!==s&&s);if(!d.isValid)return void e(d.error);"join"===(null===(r=c.message)||void 0===r?void 0:r.case)&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}))),u(n,d.shouldProcessFirstMessage?c:void 0),t(d.response)}catch(t){e(t)}finally{c()}}finally{o()}}))))}()}))}startReadingLoop(t,e){return hn(this,void 0,void 0,(function*(){for(e&&this.handleSignalResponse(e);;){this.signalLatency&&(yield yr(this.signalLatency));const{done:e,value:i}=yield t.read();if(e)break;const n=co(i);this.handleSignalResponse(n)}}))}close(){return hn(this,arguments,void 0,(function(){var t=this;let e=!(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([Oo.DISCONNECTING||Oo.DISCONNECTED].includes(t.state))return void t.log.debug("ignoring signal close as it's already in disconnecting state");const n=yield t.closingLock.lock();try{if(t.clearPingInterval(),e&&(t.state=Oo.DISCONNECTING),t.ws){t.ws.close({closeCode:1e3,reason:i});const e=t.ws.closed;t.ws=void 0,t.streamWriter=void 0,yield Promise.race([e,yr(250)])}}catch(e){t.log.debug("websocket error while closing",Object.assign(Object.assign({},t.logContext),{error:e}))}finally{e&&(t.state=Oo.DISCONNECTED),n()}}()}))}sendOffer(t,e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:t.sdp})),this.sendRequest({case:"offer",value:Co(t,e)})}sendAnswer(t,e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:t.sdp})),this.sendRequest({case:"answer",value:Co(t,e)})}sendIceCandidate(t,e){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:t})),this.sendRequest({case:"trickle",value:new ni({candidateInit:JSON.stringify(t),target:e})})}sendMuteTrack(t,e){return this.sendRequest({case:"mute",value:new si({sid:t,muted:e})})}sendAddTrack(t){return this.sendRequest({case:"addTrack",value:t})}sendUpdateLocalMetadata(t,e){return hn(this,arguments,void 0,(function(t,e){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new bi({requestId:s,metadata:t,name:e,attributes:n})}),s}()}))}sendUpdateTrackSettings(t){this.sendRequest({case:"trackSetting",value:t})}sendUpdateSubscription(t){return this.sendRequest({case:"subscription",value:t})}sendSyncState(t){return this.sendRequest({case:"syncState",value:t})}sendUpdateVideoLayers(t,e){return this.sendRequest({case:"updateLayers",value:new gi({trackSid:t,layers:e})})}sendUpdateSubscriptionPermissions(t,e){return this.sendRequest({case:"subscriptionPermission",value:new Ri({allParticipants:t,trackPermissions:e})})}sendSimulateScenario(t){return this.sendRequest({case:"simulate",value:t})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:U.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Li({timestamp:U.parse(Date.now()),rtt:U.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(t,e){return this.sendRequest({case:"updateAudioTrack",value:new fi({trackSid:t,features:e})})}sendLeave(){return this.sendRequest({case:"leave",value:new mi({reason:ne.CLIENT_INITIATED,action:pi.DISCONNECT})})}sendRequest(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(t){const e=Eo.indexOf(t.case)>=0;return rn.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}(t);if(n&&e.state===Oo.RECONNECTING)return void e.queuedRequests.push((()=>hn(e,void 0,void 0,(function*(){yield this.sendRequest(t,!0)}))));if(i||(yield e.requestQueue.flush()),e.signalLatency&&(yield yr(e.signalLatency)),e.isDisconnected)return void e.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));if(!e.streamWriter)return void e.log.error("cannot send signal request before connected, type: ".concat(null==t?void 0:t.case),e.logContext);const s=new Xe({message:t});try{e.useJSON?yield e.streamWriter.write(s.toJsonString()):yield e.streamWriter.write(s.toBinary())}catch(t){e.log.error("error sending signal message",Object.assign(Object.assign({},e.logContext),{error:t}))}}()}))}handleSignalResponse(t){var e,i;const n=t.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const t=Ao(n.value);this.onAnswer&&this.onAnswer(t,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const t=Ao(n.value);this.onOffer&&this.onOffer(t,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){const t=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(t,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(e=n.value.participants)&&void 0!==e?e:[]):"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),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(n.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const t=this.queuedRequests.shift();t&&this.requestQueue.run(t)}}handleOnClose(t){return hn(this,void 0,void 0,(function*(){if(this.state===Oo.DISCONNECTED)return;const e=this.onClose;yield this.close(void 0,t),this.log.debug("websocket connection closed: ".concat(t),Object.assign(Object.assign({},this.logContext),{reason:t})),e&&e(t)}))}handleWSError(t){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:t}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Ws.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&Ws.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Ws.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Ws.clearInterval(this.pingInterval)}handleSignalConnected(t,e,i){this.state=Oo.CONNECTED,clearTimeout(e),this.startPingInterval(),this.startReadingLoop(t.readable.getReader(),i)}validateFirstMessage(t,e){var i,n,s,r,o;return"join"===(null===(i=t.message)||void 0===i?void 0:i.case)?{isValid:!0,response:t.message.value}:this.state===Oo.RECONNECTING&&"leave"!==(null===(n=t.message)||void 0===n?void 0:n.case)?"reconnect"===(null===(s=t.message)||void 0===s?void 0:s.case)?{isValid:!0,response:t.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&"leave"===(null===(r=t.message)||void 0===r?void 0:r.case)?{isValid:!1,error:Ms.leaveRequest("Received leave request while trying to (re)connect",t.message.value.reason)}:e?{isValid:!1,error:Ms.internal("Unexpected first message")}:{isValid:!1,error:Ms.internal("did not receive join response, got ".concat(null===(o=t.message)||void 0===o?void 0:o.case," instead"))}}handleConnectionError(t,e){return hn(this,void 0,void 0,(function*(){try{const i=yield fetch(e);switch(i.status){case 404:return Ms.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield i.text();return Ms.notAllowed(t,i.status)}return t instanceof Ms?t:Ms.internal("Encountered unknown websocket error during connection: ".concat(t),{status:i.status,statusText:i.statusText})}catch(t){return t instanceof Ms?t:Ms.serverUnreachable(t instanceof Error?t.message:"server was not reachable")}}))}}function Ao(t){const e={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=t.type}return e}function Co(t,e){return new di({sdp:t.sdp,type:t.type,id:e})}class _o{constructor(){this.buffer=[],this._totalSize=0}push(t){this.buffer.push(t),this._totalSize+=t.data.byteLength}pop(){const t=this.buffer.shift();return t&&(this._totalSize-=t.data.byteLength),t}getAll(){return this.buffer.slice()}popToSequence(t){for(;this.buffer.length>0&&this.buffer[0].sequence<=t;)this.pop()}alignBufferedAmount(t){for(;this.buffer.length>0&&!(this._totalSize-this.buffer[0].data.byteLength<=t);)this.pop()}get length(){return this.buffer.length}}class Io{constructor(t){this._map=new Map,this._lastCleanup=0,this.ttl=t}set(t,e){const i=Date.now();return i-this._lastCleanup>this.ttl/2&&this.cleanup(),this._map.set(t,{value:e,expiresAt:i+this.ttl}),this}get(t){const e=this._map.get(t);if(e){if(!(e.expiresAt<Date.now()))return e.value;this._map.delete(t)}}has(t){const e=this._map.get(t);return!(!e||e.expiresAt<Date.now()&&(this._map.delete(t),1))}delete(t){return this._map.delete(t)}clear(){this._map.clear()}cleanup(){const t=Date.now();for(const[e,i]of this._map.entries())i.expiresAt<t&&this._map.delete(e);this._lastCleanup=t}get size(){return this.cleanup(),this._map.size}forEach(t){this.cleanup();for(const[e,i]of this._map.entries())i.expiresAt>=Date.now()&&t(i.value,e,this.asValueMap())}map(t){this.cleanup();const e=[],i=this.asValueMap();for(const[n,s]of i.entries())e.push(t(s,n,i));return e}asValueMap(){const t=new Map;for(const[e,i]of this._map.entries())i.expiresAt>=Date.now()&&t.set(e,i.value);return t}}var Ro,jo,Po,Do,Mo,No={},Uo={},Lo={exports:{}};function Bo(){if(Ro)return Lo.exports;Ro=1;var t=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(t){return t.encoding?"rtpmap:%d %s/%s/%s":t.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(t){return null!=t.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(t){return null!=t.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(t){return"extmap:%d"+(t.direction?"/%s":"%v")+(t["encrypt-uri"]?" %s":"%v")+" %s"+(t.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(t){return null!=t.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(t){var e="candidate:%s %d %s %d %s %d typ %s";return e+=null!=t.raddr?" raddr %s rport %d":"%v%v",e+=null!=t.tcptype?" tcptype %s":"%v",null!=t.generation&&(e+=" generation %d"),(e+=null!=t["network-id"]?" network-id %d":"%v")+(null!=t["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(t){var e="ssrc:%d";return null!=t.attribute&&(e+=" %s",null!=t.value&&(e+=":%s")),e}},{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(t){return null!=t.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(t){return t.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(t){return"imageattr:%s %s %s"+(t.dir2?" %s %s":"")}},{name:"simulcast",reg:RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(t){return"simulcast:%s %s"+(t.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(t){return"ts-refclk:%s"+(null!=t.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(t){var e="mediaclk:";return e+=null!=t.id?"id=%s %s":"%v%s",e+=null!=t.mediaClockValue?"=%s":"",(e+=null!=t.rateNumerator?" rate=%s":"")+(null!=t.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(t).forEach((function(e){t[e].forEach((function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")}))})),Lo.exports}function Fo(){return jo||(jo=1,function(t){var e=function(t){return Number(t)+""===t?Number(t):t},i=function(t,i,n){var s=t.name&&t.names;t.push&&!i[t.push]?i[t.push]=[]:s&&!i[t.name]&&(i[t.name]={});var r=t.push?{}:s?i[t.name]:i;!function(t,i,n,s){if(s&&!n)i[s]=e(t[1]);else for(var r=0;r<n.length;r+=1)null!=t[r+1]&&(i[n[r]]=e(t[r+1]))}(n.match(t.reg),r,t.names,t.name),t.push&&i[t.push].push(r)},n=Bo(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(t){var e={},r=[],o=e;return t.split(/(\r\n|\r|\n)/).filter(s).forEach((function(t){var e=t[0],s=t.slice(2);"m"===e&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[e]||[]).length;a+=1){var c=n[e][a];if(c.reg.test(s))return i(c,o,s)}})),e.media=r,e};var r=function(t,i){var n=i.split(/=(.+)/,2);return 2===n.length?t[n[0]]=e(n[1]):1===n.length&&i.length>1&&(t[n[0]]=void 0),t};t.parseParams=function(t){return t.split(/;\s?/).reduce(r,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(t){return(""+t).split(" ").map(Number)},t.parseRemoteCandidates=function(t){for(var i=[],n=t.split(" ").map(e),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},t.parseImageAttributes=function(t){return t.split(" ").map((function(t){return t.substring(1,t.length-1).split(",").reduce(r,{})}))},t.parseSimulcastStreamList=function(t){return t.split(";").map((function(t){return t.split(",").map((function(t){var i,n=!1;return"~"!==t[0]?i=e(t):(i=e(t.substring(1,t.length)),n=!0),{scid:i,paused:n}}))}))}}(Uo)),Uo}function Vo(){if(Do)return Po;Do=1;var t=Bo(),e=/%[sdv%]/g,i=function(t){var i=1,n=arguments,s=n.length;return t.replace(e,(function(t){if(i>=s)return t;var e=n[i];switch(i+=1,t){case"%%":return"%";case"%s":return e+"";case"%d":return Number(e);case"%v":return""}}))},n=function(t,e,n){var s=[t+"="+(e.format instanceof Function?e.format(e.push?n:n[e.name]):e.format)];if(e.names)for(var r=0;r<e.names.length;r+=1)s.push(e.name?n[e.name][e.names[r]]:n[e.names[r]]);else s.push(n[e.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Po=function(e,i){i=i||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(t){null==t.payloads&&(t.payloads="")}));var o=i.innerOrder||r,a=[];return(i.outerOrder||s).forEach((function(i){t[i].forEach((function(t){t.name in e&&null!=e[t.name]?a.push(n(i,t,e)):t.push in e&&null!=e[t.push]&&e[t.push].forEach((function(e){a.push(n(i,t,e))}))}))})),e.media.forEach((function(e){a.push(n("m",t.m[0],e)),o.forEach((function(i){t[i].forEach((function(t){t.name in e&&null!=e[t.name]?a.push(n(i,t,e)):t.push in e&&null!=e[t.push]&&e[t.push].forEach((function(e){a.push(n(i,t,e))}))}))}))})),a.join("\r\n")+"\r\n"},Po}var qo=function(){if(Mo)return No;Mo=1;var t=Fo(),e=Vo(),i=Bo();return No.grammar=i,No.write=e,No.parse=t.parse,No.parseParams=t.parseParams,No.parseFmtpConfig=t.parseFmtpConfig,No.parsePayloads=t.parsePayloads,No.parseRemoteCandidates=t.parseRemoteCandidates,No.parseImageAttributes=t.parseImageAttributes,No.parseSimulcastStreamList=t.parseSimulcastStreamList,No}();function zo(t,e,i){var n,s,r;void 0===e&&(e=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),h=[];function l(){if(void 0!==c){var t=Date.now()-d;if(t+e>=c)return c-t}return e}var u=function(){var e=[].slice.call(arguments),i=this;return new Promise((function(n,s){var c=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!o){var n=t.apply(i,e);a&&a(n),h.forEach((function(t){return(0,t.resolve)(n)})),h=[]}}),l()),c){var u=t.apply(i,e);return a&&a(u),n(u)}h.push({resolve:n,reject:s})}))};return u.cancel=function(t){void 0!==r&&clearTimeout(r),h.forEach((function(e){return(0,e.reject)(t)})),h=[]},u}const Jo="negotiationStarted",Wo="negotiationComplete",Go="rtpVideoPayloadTypes";class Qo extends vn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=rn,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=zo((t=>hn(this,void 0,void 0,(function*(){this.emit(Jo);try{yield this.createAndSendOffer()}catch(e){if(!t)throw e;t(e)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=on(null!==(i=e.loggerName)&&void 0!==i?i:tn.PCTransport),this.loggerOptions=e,this.config=t,this._pc=this.createPC(),this.offerLock=new u}createPC(){const t=new RTCPeerConnection(this.config);return t.onicecandidate=t=>{var e;t.candidate&&(null===(e=this.onIceCandidate)||void 0===e||e.call(this,t.candidate))},t.onicecandidateerror=t=>{var e;null===(e=this.onIceCandidateError)||void 0===e||e.call(this,t)},t.oniceconnectionstatechange=()=>{var e;null===(e=this.onIceConnectionStateChange)||void 0===e||e.call(this,t.iceConnectionState)},t.onsignalingstatechange=()=>{var e;null===(e=this.onSignalingStatechange)||void 0===e||e.call(this,t.signalingState)},t.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,t.connectionState)},t.ondatachannel=t=>{var e;null===(e=this.onDataChannel)||void 0===e||e.call(this,t)},t.ontrack=t=>{var e;null===(e=this.onTrack)||void 0===e||e.call(this,t)},t}get logContext(){var t,e;return Object.assign({},null===(e=(t=this.loggerOptions).loggerContextCb)||void 0===e?void 0:e.call(t))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(t){return hn(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(t);this.pendingCandidates.push(t)}))}setRemoteDescription(t,e){return hn(this,void 0,void 0,(function*(){var i;if("answer"===t.type&&this.latestOfferId>0&&e>0&&e!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:e,latestOfferId:this.latestOfferId})),!1;let n;if("offer"===t.type){let{stereoMids:e,nackMids:i}=function(t){var e;const i=[],n=[],s=qo.parse(null!==(e=t.sdp)&&void 0!==e?e:"");let r=0;return s.media.forEach((t=>{var e;const s=Yo(t.mid);"audio"===t.type&&(t.rtp.some((t=>"opus"===t.codec&&(r=t.payload,!0))),(null===(e=t.rtcpFb)||void 0===e?void 0:e.some((t=>t.payload===r&&"nack"===t.type)))&&n.push(s),t.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(s),!0))))})),{stereoMids:i,nackMids:n}}(t);this.remoteStereoMids=e,this.remoteNackMids=i}else if("answer"===t.type){const e=qo.parse(null!==(i=t.sdp)&&void 0!==i?i:"");e.media.forEach((t=>{const e=Yo(t.mid);"audio"===t.type&&this.trackBitrates.some((i=>{if(!i.transceiver||e!=i.transceiver.mid)return!1;let n=0;if(t.rtp.some((t=>t.codec.toUpperCase()===i.codec.toUpperCase()&&(n=t.payload,!0))),0===n)return!0;let s=!1;for(const e of t.fmtp)if(e.payload===n){e.config=e.config.split(";").filter((t=>!t.includes("maxaveragebitrate"))).join(";"),i.maxbr>0&&(e.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),s=!0;break}return s||i.maxbr>0&&t.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0}))})),n=qo.write(e)}return yield this.setMungedSDP(t,n,!0),this.pendingCandidates.forEach((t=>{this.pc.addIceCandidate(t)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===t.type&&(this.emit(Wo),t.sdp)&&qo.parse(t.sdp).media.forEach((t=>{"video"===t.type&&this.emit(Go,t.rtp)})),!0}))}createAndSendOffer(t){return hn(this,void 0,void 0,(function*(){var e;const i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==t?void 0:t.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const e=this._pc.remoteDescription;if(!(null==t?void 0:t.iceRestart)||!e)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(e)}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(t);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=qo.parse(null!==(e=n.sdp)&&void 0!==e?e:"");if(s.media.forEach((t=>{Ko(t),"audio"===t.type?Ho(t,["all"],[]):"video"===t.type&&this.trackBitrates.some((e=>{if(!t.msid||!e.cid||!t.msid.includes(e.cid))return!1;let i=0;if(t.rtp.some((t=>t.codec.toUpperCase()===e.codec.toUpperCase()&&(i=t.payload,!0))),0===i)return!0;if(Tr(e.codec)&&!xr()&&this.ensureVideoDDExtensionForSVC(t,s),!Tr(e.codec))return!0;const n=Math.round(.7*e.maxbr);for(const e of t.fmtp)if(e.payload===i){e.config.includes("x-google-start-bitrate")||(e.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,qo.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}}))}createAndSetAnswer(){return hn(this,void 0,void 0,(function*(){var t;const e=yield this.pc.createAnswer(),i=qo.parse(null!==(t=e.sdp)&&void 0!==t?t:"");return i.media.forEach((t=>{Ko(t),"audio"===t.type&&Ho(t,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(e,qo.write(i)),e}))}createDataChannel(t,e){return this.pc.createDataChannel(t,e)}addTransceiver(t,e){return this.pc.addTransceiver(t,e)}addTransceiverOfKind(t,e){return this.pc.addTransceiver(t,e)}addTrack(t){if(!this._pc)throw new Bs("PC closed, cannot add track");return this._pc.addTrack(t)}setTrackCodecBitrate(t){this.trackBitrates.push(t)}setConfiguration(t){var e;if(!this._pc)throw new Bs("PC closed, cannot configure");return null===(e=this._pc)||void 0===e?void 0:e.setConfiguration(t)}canRemoveTrack(){var t;return!!(null===(t=this._pc)||void 0===t?void 0:t.removeTrack)}removeTrack(t){var e;return null===(e=this._pc)||void 0===e?void 0:e.removeTrack(t)}getConnectionState(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.connectionState)&&void 0!==e?e:"closed"}getICEConnectionState(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.iceConnectionState)&&void 0!==e?e:"closed"}getSignallingState(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.signalingState)&&void 0!==e?e:"closed"}getTransceivers(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.getTransceivers())&&void 0!==e?e:[]}getSenders(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.getSenders())&&void 0!==e?e:[]}getLocalDescription(){var t;return null===(t=this._pc)||void 0===t?void 0:t.localDescription}getRemoteDescription(){var t;return null===(t=this.pc)||void 0===t?void 0:t.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return hn(this,void 0,void 0,(function*(){var t;if(!this._pc)return;let e="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach((t=>{switch(t.type){case"transport":e=t.selectedCandidatePairId;break;case"candidate-pair":""===e&&t.selected&&(e=t.id),i.set(t.id,t);break;case"remote-candidate":n.set(t.id,"".concat(t.address,":").concat(t.port))}})),""===e)return;const s=null===(t=i.get(e))||void 0===t?void 0:t.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(t,e,i){return hn(this,void 0,void 0,(function*(){if(e){const n=t.sdp;t.sdp=e;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(t):yield this.pc.setLocalDescription(t))}catch(i){this.log.warn("not able to set ".concat(t.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:e})),t.sdp=n}}try{i?yield this.pc.setRemoteDescription(t):yield this.pc.setLocalDescription(t)}catch(e){let n="unknown error";e instanceof Error?n=e.message:"string"==typeof e&&(n=e);const s={error:n,sdp:t.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(t.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Fs(n)}}))}ensureVideoDDExtensionForSVC(t,e){var i,n;if(!(null===(i=t.ext)||void 0===i?void 0:i.some((t=>t.uri===br)))){if(0===this.ddExtID){let t=0;e.media.forEach((e=>{var i;"video"===e.type&&(null===(i=e.ext)||void 0===i||i.forEach((e=>{e.value>t&&(t=e.value)})))})),this.ddExtID=t+1}null===(n=t.ext)||void 0===n||n.push({value:this.ddExtID,uri:br})}}}function Ho(t,e,i){const n=Yo(t.mid);let s=0;t.rtp.some((t=>"opus"===t.codec&&(s=t.payload,!0))),s>0&&(t.rtcpFb||(t.rtcpFb=[]),i.includes(n)&&!t.rtcpFb.some((t=>t.payload===s&&"nack"===t.type))&&t.rtcpFb.push({payload:s,type:"nack"}),(e.includes(n)||1===e.length&&"all"===e[0])&&t.fmtp.some((t=>t.payload===s&&(t.config.includes("stereo=1")||(t.config+=";stereo=1"),!0))))}function Ko(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(4===t.connection.version&&e||6===t.connection.version&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}function Yo(t){return"number"==typeof t?t.toFixed(0):t}const Zo="vp8",$o={audioPreset:$s.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:er.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Zo,backupCodec:!0,preConnectBuffer:!1},Xo={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ta={deviceId:{ideal:"default"},resolution:Xs.h720.resolution},ea={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(t){this._retryDelays=void 0!==t?[...t]:dn}nextRetryDelayInMs(t){if(t.retryCount>=this._retryDelays.length)return null;const e=this._retryDelays[t.retryCount];return t.retryCount<=1?e:e+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},ia={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var na;!function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"}(na||(na={}));class sa{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(t,e,i){var n;this.peerConnectionTimeout=ia.peerConnectionTimeout,this.log=rn,this.updateState=()=>{var t,e;const i=this.state,n=this.requiredTransports.map((t=>t.getConnectionState()));n.every((t=>"connected"===t))?this.state=na.CONNECTED:n.some((t=>"failed"===t))?this.state=na.FAILED:n.some((t=>"connecting"===t))?this.state=na.CONNECTING:n.every((t=>"closed"===t))?this.state=na.CLOSED:n.some((t=>"closed"===t))?this.state=na.CLOSING:n.every((t=>"new"===t))&&(this.state=na.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(na[i]," to ").concat(na[this.state]),this.logContext),null===(t=this.onStateChange)||void 0===t||t.call(this,this.state,this.publisher.getConnectionState(),null===(e=this.subscriber)||void 0===e?void 0:e.getConnectionState()))},this.log=on(null!==(n=i.loggerName)&&void 0!==n?n:tn.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==e,this.isSubscriberConnectionRequired="subscriber-primary"===e,this.publisher=new Qo(t,i),this._mode=e,"publisher-only"!==e&&(this.subscriber=new Qo(t,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=t=>{var e;null===(e=this.onIceCandidate)||void 0===e||e.call(this,t,Ye.SUBSCRIBER)},this.subscriber.onDataChannel=t=>{var e;null===(e=this.onDataChannel)||void 0===e||e.call(this,t)},this.subscriber.onTrack=t=>{var e;null===(e=this.onTrack)||void 0===e||e.call(this,t)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=t=>{var e;null===(e=this.onIceCandidate)||void 0===e||e.call(this,t,Ye.PUBLISHER)},this.publisher.onTrack=t=>{var e;null===(e=this.onTrack)||void 0===e||e.call(this,t)},this.publisher.onOffer=(t,e)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,t,e)},this.state=na.NEW,this.connectionLock=new u,this.remoteOfferLock=new u}get logContext(){var t,e;return Object.assign({},null===(e=(t=this.loggerOptions).loggerContextCb)||void 0===e?void 0:e.call(t))}requirePublisher(){this.isPublisherConnectionRequired=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],this.updateState()}createAndSendPublisherOffer(t){return this.publisher.createAndSendOffer(t)}setPublisherAnswer(t,e){return this.publisher.setRemoteDescription(t,e)}removeTrack(t){return this.publisher.removeTrack(t)}close(){return hn(this,void 0,void 0,(function*(){var t;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const t=this.publisher;for(const e of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(e)}catch(t){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:t}))}}yield Promise.all([this.publisher.close(),null===(t=this.subscriber)||void 0===t?void 0:t.close()]),this.updateState()}))}triggerIceRestart(){return hn(this,void 0,void 0,(function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(t,e){return hn(this,void 0,void 0,(function*(){var i;e===Ye.PUBLISHER?yield this.publisher.addIceCandidate(t):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(t)}))}createSubscriberAnswerFromOffer(t,e){return hn(this,void 0,void 0,(function*(){var i,n,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:t.type,sdp:t.sdp,signalingState:null===(i=this.subscriber)||void 0===i?void 0:""+i.getSignallingState()}));const r=yield this.remoteOfferLock.lock();try{if(!(yield null===(n=this.subscriber)||void 0===n?void 0:n.setRemoteDescription(t,e)))return;return yield null===(s=this.subscriber)||void 0===s?void 0:s.createAndSetAnswer()}finally{r()}}))}updateConfiguration(t,e){var i;this.publisher.setConfiguration(t),null===(i=this.subscriber)||void 0===i||i.setConfiguration(t),e&&this.triggerIceRestart()}ensurePCTransportConnection(t,e){return hn(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,t,e))))}finally{n()}}))}negotiate(t){return hn(this,void 0,void 0,(function*(){return new ws(((e,i)=>hn(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i(new Fs("negotiation timed out"))}),this.peerConnectionTimeout);t.signal.addEventListener("abort",(()=>{clearTimeout(n),i(new Fs("negotiation aborted"))})),this.publisher.once(Jo,(()=>{t.signal.aborted||this.publisher.once(Wo,(()=>{clearTimeout(n),e()}))})),yield this.publisher.negotiate((t=>{clearTimeout(n),i(t instanceof Error?t:Error(t+""))}))}))))}))}addPublisherTransceiver(t,e){return this.publisher.addTransceiver(t,e)}addPublisherTransceiverOfKind(t,e){return this.publisher.addTransceiverOfKind(t,e)}getMidForReceiver(t){const e=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find((e=>e.receiver===t));return null==e?void 0:e.mid}addPublisherTrack(t){return this.publisher.addTrack(t)}createPublisherDataChannel(t,e){return this.publisher.createDataChannel(t,e)}getConnectedAddress(t){return t===Ye.PUBLISHER||t===Ye.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const t=[];return this.isPublisherConnectionRequired&&t.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&t.push(this.subscriber),t}ensureTransportConnected(t,e){return hn(this,arguments,void 0,(function(t,e){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==t.getConnectionState())return new Promise(((t,s)=>hn(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Ws.clearTimeout(r),s(Ms.cancelled("room connection has been cancelled"))};(null==e?void 0:e.signal.aborted)&&i(),null==e||e.signal.addEventListener("abort",i);const r=Ws.setTimeout((()=>{null==e||e.signal.removeEventListener("abort",i),s(Ms.internal("could not establish pc connection"))}),n);for(;this.state!==na.CONNECTED;)if(yield yr(50),null==e?void 0:e.signal.aborted)return void s(Ms.cancelled("room connection has been cancelled"));Ws.clearTimeout(r),null==e||e.signal.removeEventListener("abort",i),t()}))))}()}))}}class ra{static fetchRegionSettings(t,e,i){return hn(this,void 0,void 0,(function*(){const n=yield ra.fetchLock.lock();try{const n=yield fetch("".concat(function(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}(t),"/regions"),{headers:{authorization:"Bearer ".concat(e)},signal:i});if(n.ok){const t=function(t){var e;const i=t.get("Cache-Control");if(i){const t=null===(e=i.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===e?void 0:e[1];if(t)return parseInt(t,10)}}(n.headers),e=t?1e3*t:5e3;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:e}}throw 401===n.status?Ms.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):Ms.internal("Could not fetch region settings: ".concat(n.statusText))}catch(t){throw t instanceof Ms?t:(null==i?void 0:i.aborted)?Ms.cancelled("Region fetching was aborted"):Ms.serverUnreachable("Could not fetch region settings, ".concat(t instanceof Error?"".concat(t.name,": ").concat(t.message):t))}finally{n()}}))}static scheduleRefetch(t,e,i){return hn(this,void 0,void 0,(function*(){const n=ra.settingsTimeouts.get(t.hostname);clearTimeout(n),ra.settingsTimeouts.set(t.hostname,setTimeout((()=>hn(this,void 0,void 0,(function*(){try{const i=yield ra.fetchRegionSettings(t,e);ra.updateCachedRegionSettings(t,e,i)}catch(n){if(n instanceof Ms&&n.reason===Cs.NotAllowed)return void rn.debug("token is not valid, cancelling auto region refresh");rn.debug("auto refetching of region settings failed",{error:n}),ra.scheduleRefetch(t,e,i)}}))),i))}))}static updateCachedRegionSettings(t,e,i){ra.cache.set(t.hostname,i),ra.scheduleRefetch(t,e,i.maxAgeInMs)}static stopRefetch(t){const e=ra.settingsTimeouts.get(t);e&&(clearTimeout(e),ra.settingsTimeouts.delete(t))}static scheduleCleanup(t){let e=ra.connectionTrackers.get(t);e&&(e.cleanupTimeout&&clearTimeout(e.cleanupTimeout),e.cleanupTimeout=setTimeout((()=>{const e=ra.connectionTrackers.get(t);e&&0===e.connectionCount&&(rn.debug("stopping region refetch after disconnect delay",{hostname:t}),ra.stopRefetch(t)),e&&(e.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(t){const e=ra.connectionTrackers.get(t);(null==e?void 0:e.cleanupTimeout)&&(clearTimeout(e.cleanupTimeout),e.cleanupTimeout=void 0)}notifyConnected(){const t=this.serverUrl.hostname;let e=ra.connectionTrackers.get(t);e||(e={connectionCount:0},ra.connectionTrackers.set(t,e)),e.connectionCount++,ra.cancelCleanup(t)}notifyDisconnected(){const t=this.serverUrl.hostname,e=ra.connectionTrackers.get(t);e&&(e.connectionCount=Math.max(0,e.connectionCount-1),0===e.connectionCount&&ra.scheduleCleanup(t))}constructor(t,e){this.attemptedRegions=[],this.serverUrl=new URL(t),this.token=e}updateToken(t){this.token=t}isCloud(){return Rr(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return hn(this,void 0,void 0,(function*(){return ra.fetchRegionSettings(this.serverUrl,this.token,t)}))}getNextBestRegionUrl(t){return hn(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let e=ra.cache.get(this.serverUrl.hostname);(!e||Date.now()-e.updatedAtInMs>e.maxAgeInMs)&&(e=yield this.fetchRegionSettings(t),ra.updateCachedRegionSettings(this.serverUrl,this.token,e));const i=e.regionSettings.regions.filter((t=>!this.attemptedRegions.find((e=>e.url===t.url))));if(i.length>0){const t=i[0];return this.attemptedRegions.push(t),rn.debug("next region: ".concat(t.region)),t.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){ra.updateCachedRegionSettings(this.serverUrl,this.token,t)}}ra.cache=new Map,ra.settingsTimeouts=new Map,ra.connectionTrackers=new Map,ra.fetchLock=new u;class oa extends Error{constructor(t,e,i){super(e),this.code=t,this.message=ca(e,oa.MAX_MESSAGE_BYTES),this.data=i?ca(i,oa.MAX_DATA_BYTES):void 0}static fromProto(t){return new oa(t.code,t.message,t.data)}toProto(){return new Pe({code:this.code,message:this.message,data:this.data})}static builtIn(t,e){return new oa(oa.ErrorCode[t],oa.ErrorMessage[t],e)}}function aa(t){return(new TextEncoder).encode(t).length}function ca(t,e){if(aa(t)<=e)return t;let i=0,n=t.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(t.slice(0,r)).length<=e?i=r:n=r-1}return t.slice(0,i)}oa.MAX_MESSAGE_BYTES=256,oa.MAX_DATA_BYTES=15360,oa.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},oa.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 da=2e3;function ha(t,e){if(!e)return 0;let i,n;return"bytesReceived"in t?(i=t.bytesReceived,n=e.bytesReceived):"bytesSent"in t&&(i=t.bytesSent,n=e.bytesSent),void 0===i||void 0===n||void 0===t.timestamp||void 0===e.timestamp?0:8*(i-n)*1e3/(t.timestamp-e.timestamp)}const la="undefined"!=typeof MediaRecorder,ua=la?MediaRecorder:class{constructor(){throw Error("MediaRecorder is not available in this environment")}};class fa extends ua{constructor(t,e){if(!la)throw Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([t.mediaStreamTrack]),e);const s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),null==n||n.close(),n=void 0},r=t=>{null==n||n.error(t),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),n=void 0};this.byteStream=new ReadableStream({start:t=>{n=t,i=e=>hn(this,void 0,void 0,(function*(){let i;if(e.data.arrayBuffer){const t=yield e.data.arrayBuffer();i=new Uint8Array(t)}else{if(!e.data.byteArray)throw Error("no data available!");i=e.data.byteArray}void 0!==n&&t.enqueue(i)})),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",r)}}class va extends mr{get sender(){return this._sender}set sender(t){this._sender=t}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,e,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=zo((()=>hn(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>hn(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(Ds.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new u,this.pauseUpstreamLock=new u,this.trackChangeLock=new u,this.trackChangeLock.lock().then((e=>hn(this,void 0,void 0,(function*(){try{yield this.setMediaStreamTrack(t,!0)}finally{e()}})))),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==mr.Kind.Video)return;const{width:t,height:e}=this._mediaStreamTrack.getSettings();return t&&e?{width:t,height:e}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var t,e;return null!==(e=null===(t=this.processor)||void 0===t?void 0:t.processedTrack)&&void 0!==e?e:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(t,e){return hn(this,void 0,void 0,(function*(){var i;if(t===this._mediaStreamTrack&&!e)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((t=>{gr(this._mediaStreamTrack,t)})),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([t]),t&&(t.addEventListener("ended",this.handleEnded),t.addEventListener("mute",this.handleTrackMuteEvent),t.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=t.getConstraints()),this.processor&&t){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(pr(t,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:t,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:t)),this.providedByUser||this._mediaStreamTrack===t||this._mediaStreamTrack.stop(),this._mediaStreamTrack=t,t&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((e=>{pr(null!=n?n:t,e)})))}))}waitForDimensions(){return hn(this,arguments,void 0,(function(){var t=this;let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(t.kind===mr.Kind.Audio)throw Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=Ss())||void 0===i?void 0:i.os)&&(yield yr(10));const n=Date.now();for(;Date.now()-n<e;){const e=t.dimensions;if(e)return e;yield yr(50)}throw new Us("unable to get track dimensions after timeout")}()}))}setDeviceId(t){return hn(this,void 0,void 0,(function*(){return this._constraints.deviceId===t&&this._mediaStreamTrack.getSettings().deviceId===Qr(t)||(this._constraints.deviceId=t,!!this.isMuted||(yield this.restartTrack(),Qr(t)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return hn(this,arguments,void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(t.source===mr.Source.ScreenShare)return;const{deviceId:i,groupId:n}=t._mediaStreamTrack.getSettings(),s=t.kind===mr.Kind.Audio?"audioinput":"videoinput";return e?wo.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return hn(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return hn(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(t,e){return hn(this,void 0,void 0,(function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Us("unable to replace an unpublished track");let i,n;return"boolean"==typeof e?i=e:void 0!==e&&(i=e.userProvidedTrack,n=e.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(t),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}}))}restart(t){return hn(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const e=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const{deviceId:e,facingMode:i}=t,n=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const s={audio:!1,video:!1};this.kind===mr.Kind.Video?s.video=!e&&!i||{deviceId:e,facingMode:i}:s.audio=!e||Object.assign({deviceId:e},n),this.attachedElements.forEach((t=>{gr(this.mediaStreamTrack,t)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===mr.Kind.Video&&(yield r.applyConstraints(n)),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=t,this.emit(Ds.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{e()}}))}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?Ds.Muted:Ds.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return hn(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),Cr()&&(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 t;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(t=this.processor)||void 0===t||t.destroy(),this.processor=void 0}pauseUpstream(){return hn(this,void 0,void 0,(function*(){var t;const e=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(Ds.UpstreamPaused,this);const e=Ss();if("Safari"===(null==e?void 0:e.name)&&Nr(e.version,"12.0")<0)throw new Ns("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(null))}finally{e()}}))}resumeUpstream(){return hn(this,void 0,void 0,(function*(){var t;const e=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(Ds.UpstreamResumed,this),"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}}))}getRTCStatsReport(){return hn(this,void 0,void 0,(function*(){var t;if(null===(t=this.sender)||void 0===t?void 0:t.getStats)return yield this.sender.getStats()}))}setProcessor(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield e.trackChangeLock.lock();try{e.log.debug("setting up processor",e.logContext);const s=document.createElement(e.kind),r={kind:e.kind,track:e._mediaStreamTrack,element:s,audioContext:e.audioContext};if(yield t.init(r),e.log.debug("processor initialized",e.logContext),e.processor&&(yield e.internalStopProcessor()),"unknown"===e.kind)throw TypeError("cannot set processor on track of unknown kind");if(pr(e._mediaStreamTrack,s),s.muted=!0,s.play().catch((t=>{t instanceof DOMException&&"AbortError"===t.name?(e.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},e.logContext),{error:t})),setTimeout((()=>{s.play().catch((t=>{e.log.error("failed to play processor element",Object.assign(Object.assign({},e.logContext),{err:t}))}))}),100)):e.log.error("failed to play processor element",Object.assign(Object.assign({},e.logContext),{error:t}))})),e.processor=t,e.processorElement=s,e.processor.processedTrack){for(const t of e.attachedElements)t!==e.processorElement&&i&&(gr(e._mediaStreamTrack,t),pr(e.processor.processedTrack,t));yield null===(n=e.sender)||void 0===n?void 0:n.replaceTrack(e.processor.processedTrack)}e.emit(Ds.TrackProcessorUpdate,e.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return hn(this,arguments,void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield t.trackChangeLock.lock();try{yield t.internalStopProcessor(e)}finally{i()}}()}))}internalStopProcessor(){return hn(this,arguments,void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;t.processor&&(t.log.debug("stopping processor",t.logContext),null===(i=t.processor.processedTrack)||void 0===i||i.stop(),yield t.processor.destroy(),t.processor=void 0,e||(null===(n=t.processorElement)||void 0===n||n.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(Ds.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(la)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new fa(this,{mimeType:t})}this.localTrackRecorder.start(t),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 t;return null===(t=this.localTrackRecorder)||void 0===t?void 0:t.byteStream}getPreConnectBufferMimeType(){var t;return null===(t=this.localTrackRecorder)||void 0===t?void 0:t.mimeType}}class ma extends va{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,e){let i=arguments.length>3?arguments[3]:void 0;super(t,mr.Kind.Audio,e,!(arguments.length>2&&void 0!==arguments[2])||arguments[2],arguments.length>4?arguments[4]:void 0),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>hn(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}t&&this.prevStats&&(this._currentBitrate=ha(t,this.prevStats)),this.prevStats=t})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Ds.AudioTrackFeatureUpdate,this,oe.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Ds.AudioTrackFeatureUpdate,this,oe.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return hn(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===mr.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield t.mute.call(this),this)}finally{e()}}))}unmute(){const t=Object.create(null,{unmute:{get:()=>super.unmute}});return hn(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const e=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Qr(this._constraints.deviceId);return this.source!==mr.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!e||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield t.unmute.call(this),this}finally{e()}}))}restartTrack(t){return hn(this,void 0,void 0,(function*(){let e;if(t){const i=sr({audio:t});"boolean"!=typeof i.audio&&(e=i.audio)}yield this.restart(e)}))}restart(t){const e=Object.create(null,{restart:{get:()=>super.restart}});return hn(this,void 0,void 0,(function*(){const i=yield e.restart.call(this,t);return this.checkForSilence(),i}))}startMonitor(){_r()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),da)))}setProcessor(t){return hn(this,void 0,void 0,(function*(){var e;const i=yield this.trackChangeLock.lock();try{if(!Ir()&&!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};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(i),this.processor=t,this.processor.processedTrack&&(yield null===(e=this.sender)||void 0===e?void 0:e.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(Ds.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(t){this.audioContext=t}getSenderStats(){return hn(this,void 0,void 0,(function*(){var t;if(!(null===(t=this.sender)||void 0===t?void 0:t.getStats))return;let e;return(yield this.sender.getStats()).forEach((t=>{"outbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,packetsSent:t.packetsSent,packetsLost:t.packetsLost,bytesSent:t.bytesSent,timestamp:t.timestamp,roundTripTime:t.roundTripTime,jitter:t.jitter})})),e}))}checkForSilence(){return hn(this,void 0,void 0,(function*(){const t=yield function(t){return hn(this,arguments,void 0,(function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=rr();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([t.mediaStreamTrack])).connect(n),yield yr(e),n.getByteTimeDomainData(s);const r=s.some((t=>128!==t&&0!==t));return i.close(),!r}return!1}()}))}(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(Ds.AudioSilenceDetected)),t}))}}const pa=Object.values(Xs),ga=Object.values(tr),ba=Object.values(er),ya=[Xs.h180,Xs.h360],wa=[tr.h180,tr.h360],ka=["q","h","f"];function Ta(t,e,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;t&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!e||!i)return[{}];o||(o=function(t,e,i,n){const s=function(t,e,i){if(t)return ba;const n=e>i?e/i:i/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?pa:ga}(t,e,i);let{encoding:r}=s[0];const o=Math.max(e,i);for(let t=0;t<s.length;t+=1){const e=s[t];if(r=e.encoding,e.width>=o)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(t,e,i,d),rn.debug("using video encoding",o));const h=o.maxFramerate,l=new Qs(e,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Tr(d)){const t=new xa(c),e=[];if(t.spatial>3)throw Error("unsupported scalabilityMode: ".concat(c));const i=Ss();if(Ar()||Ir()||"Chrome"===(null==i?void 0:i.name)&&Nr(null==i?void 0:i.version,"113")<0){const n="h"==t.suffix?2:3,s=function(t){return t||(t=Ss()),"Safari"===(null==t?void 0:t.name)&&Nr(t.version,"18.3")>0||"iOS"===(null==t?void 0:t.os)&&!!(null==t?void 0:t.osVersion)&&Nr(t.osVersion,"18.3")>0}(i);for(let i=0;i<t.spatial;i+=1)e.push({rid:ka[2-i],maxBitrate:o.maxBitrate/Math.pow(n,i),maxFramerate:l.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,i):void 0});e[0].scalabilityMode=c}else e.push({maxBitrate:o.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:c});return l.encoding.priority&&(e[0].priority=l.encoding.priority,e[0].networkPriority=l.encoding.priority),rn.debug("using svc encoding",{encodings:e}),e}if(!a)return[o];let u,f=[];if(f=t?null!==(s=Oa(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:Sa(t,l):null!==(r=Oa(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:Sa(t,l),f.length>0){const t=f[0];f.length>1&&([,u]=f);const n=Math.max(e,i);if(n>=960&&u)return Ea(e,i,[t,u,l],h);if(n>=480)return Ea(e,i,[t,l],h)}return Ea(e,i,[l])}function Sa(t,e){if(t)return(t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map((e=>{var i,n;return new Qs(Math.floor(t.width/e.scaleResolutionDownBy),Math.floor(t.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(i=t.encoding.maxFramerate)&&void 0!==i?i:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,t.encoding.priority)})))(e);const{width:i,height:n}=e,s=i>n?i/n:n/i;return Math.abs(s-16/9)<Math.abs(s-4/3)?ya:wa}function Ea(t,e,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=ka.length)return;const o={rid:ka[r],scaleResolutionDownBy:Math.max(1,Math.min(t,e)/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},a=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;a&&(o.maxFramerate=a);const c=Er()||0===r;i.encoding.priority&&c&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),s.push(o)})),Ir()&&"ios"===Dr()){let t;s.forEach((e=>{t?e.maxFramerate&&e.maxFramerate>t&&(t=e.maxFramerate):t=e.maxFramerate}));let e=!0;s.forEach((i=>{var n;i.maxFramerate!=t&&(e&&(e=!1,rn.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),rn.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(t)),i.maxFramerate=t)}))}return s}function Oa(t){if(t)return t.sort(((t,e)=>{const{encoding:i}=t,{encoding:n}=e;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 xa{constructor(t){const e=t.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!e)throw Error("invalid scalability mode");if(this.spatial=parseInt(e[1]),this.temporal=parseInt(e[2]),e.length>3)switch(e[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=e[3]}}toString(){var t;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(t=this.suffix)&&void 0!==t?t:"")}}class Aa extends va{get sender(){return this._sender}set sender(t){this._sender=t,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,e){super(t,mr.Kind.Video,e,!(arguments.length>2&&void 0!==arguments[2])||arguments[2],arguments.length>3?arguments[3]:void 0),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>hn(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(t){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}const e=new Map(t.map((t=>[t.rid,t]))),i=t.some((t=>"cpu"===t.qualityLimitationReason));if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(Ds.CpuConstrained)),this.prevStats){let t=0;e.forEach(((e,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);t+=ha(e,s)})),this._currentBitrate=t}this.prevStats=e})),this.senderLock=new u}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(t){var e;if(this.signalClient=t,!_r())return;const i=null===(e=this.sender)||void 0===e?void 0:e.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),da))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((t=>{t.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const t=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return hn(this,void 0,void 0,(function*(){var e,i,n,s;yield t.pauseUpstream.call(this);try{for(var r,o=!0,a=ln(this.simulcastCodecs.values());!(e=(r=yield a.next()).done);o=!0){o=!1;const t=r.value;yield null===(s=t.sender)||void 0===s?void 0:s.replaceTrack(null)}}catch(t){i={error:t}}finally{try{o||e||!(n=a.return)||(yield n.call(a))}finally{if(i)throw i.error}}}))}resumeUpstream(){const t=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return hn(this,void 0,void 0,(function*(){var e,i,n,s;yield t.resumeUpstream.call(this);try{for(var r,o=!0,a=ln(this.simulcastCodecs.values());!(e=(r=yield a.next()).done);o=!0){o=!1;const t=r.value;yield null===(s=t.sender)||void 0===s?void 0:s.replaceTrack(t.mediaStreamTrack)}}catch(t){i={error:t}}finally{try{o||e||!(n=a.return)||(yield n.call(a))}finally{if(i)throw i.error}}}))}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return hn(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==mr.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield t.mute.call(this),this)}finally{e()}}))}unmute(){const t=Object.create(null,{unmute:{get:()=>super.unmute}});return hn(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.source!==mr.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield t.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{e()}}))}setTrackMuted(t){super.setTrackMuted(t);for(const e of this.simulcastCodecs.values())e.mediaStreamTrack.enabled=!t}getSenderStats(){return hn(this,void 0,void 0,(function*(){var t;if(!(null===(t=this.sender)||void 0===t?void 0:t.getStats))return[];const e=[],i=yield this.sender.getStats();return i.forEach((t=>{var n;if("outbound-rtp"===t.type){const s={type:"video",streamId:t.id,frameHeight:t.frameHeight,frameWidth:t.frameWidth,framesPerSecond:t.framesPerSecond,framesSent:t.framesSent,firCount:t.firCount,pliCount:t.pliCount,nackCount:t.nackCount,packetsSent:t.packetsSent,bytesSent:t.bytesSent,qualityLimitationReason:t.qualityLimitationReason,qualityLimitationDurations:t.qualityLimitationDurations,qualityLimitationResolutionChanges:t.qualityLimitationResolutionChanges,rid:null!==(n=t.rid)&&void 0!==n?n:t.id,retransmittedPacketsSent:t.retransmittedPacketsSent,targetBitrate:t.targetBitrate,timestamp:t.timestamp},r=i.get(t.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),e.push(s)}})),e.sort(((t,e)=>{var i,n;return(null!==(i=e.frameWidth)&&void 0!==i?i:0)-(null!==(n=t.frameWidth)&&void 0!==n?n:0)})),e}))}setPublishingQuality(t){const e=[];for(let i=vr.LOW;i<=vr.HIGH;i+=1)e.push(new xi({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(Tr(this.codec),e)}restartTrack(t){return hn(this,void 0,void 0,(function*(){var e,i,n,s;let r;if(t){const e=sr({video:t});"boolean"!=typeof e.video&&(r=e.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var o,a=!0,c=ln(this.simulcastCodecs.values());!(e=(o=yield c.next()).done);a=!0){a=!1;const t=o.value;t.sender&&"closed"!==(null===(s=t.sender.transport)||void 0===s?void 0:s.state)&&(t.mediaStreamTrack=this.mediaStreamTrack.clone(),yield t.sender.replaceTrack(t.mediaStreamTrack))}}catch(t){i={error:t}}finally{try{a||e||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}setProcessor(t){const e=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return hn(this,arguments,void 0,(function(t){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c;if(yield e.setProcessor.call(i,t,n),null===(a=i.processor)||void 0===a?void 0:a.processedTrack)try{for(var d,h=!0,l=ln(i.simulcastCodecs.values());!(s=(d=yield l.next()).done);h=!0){h=!1;const t=d.value;yield null===(c=t.sender)||void 0===c?void 0:c.replaceTrack(i.processor.processedTrack)}}catch(t){r={error:t}}finally{try{h||s||!(o=l.return)||(yield o.call(l))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(t){return hn(this,void 0,void 0,(function*(){if(this.degradationPreference=t,this.sender)try{this.log.debug("setting degradationPreference to ".concat(t),this.logContext);const e=this.sender.getParameters();e.degradationPreference=t,this.sender.setParameters(e)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}}))}addSimulcastTrack(t,e){if(this.simulcastCodecs.has(t))return void this.log.error("".concat(t," already added, skipping adding simulcast codec"),this.logContext);const i={codec:t,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:e};return this.simulcastCodecs.set(t,i),i}setSimulcastTrackSender(t,e){const i=this.simulcastCodecs.get(t);i&&(i.sender=e,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(t){return hn(this,void 0,void 0,(function*(){var e,i,n,s,r,o;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:t,currentCodec:this.codec})),!this.codec&&t.length>0)return yield this.setPublishingLayers(Tr(t[0].codec),t[0].qualities),[];this.subscribedCodecs=t;const a=[];try{for(e=!0,i=ln(t);!(s=(n=yield i.next()).done);e=!0){e=!1;const t=n.value;if(this.codec&&this.codec!==t.codec){const e=this.simulcastCodecs.get(t.codec);if(this.log.debug("try setPublishingCodec for ".concat(t.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:e})),e&&e.sender)e.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(t.codec),this.logContext),yield Ca(e.sender,e.encodings,t.qualities,this.senderLock,Tr(t.codec),this.log,this.logContext));else for(const e of t.qualities)if(e.enabled){a.push(t.codec);break}}else yield this.setPublishingLayers(Tr(t.codec),t.qualities)}}catch(t){r={error:t}}finally{try{e||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return a}))}setPublishingLayers(t,e){return hn(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:e})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield Ca(this.sender,this.encodings,e,this.senderLock,t,this.log,this.logContext)))}))}prioritizePerformance(){return hn(this,void 0,void 0,(function*(){if(!this.sender)throw Error("sender not found");const t=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map(((t,e)=>{var i;return Object.assign(Object.assign({},t),{active:0===e,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===e&&Tr(this.codec)?"L1T3":void 0,maxFramerate:0===e?15:0,maxBitrate:0===e?t.maxBitrate:0})})),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{t()}}))}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return hn(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),Cr()&&this.isInBackground&&this.source===mr.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Ca(t,e,i,n,s,r,o){return hn(this,void 0,void 0,(function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:i,senderEncodings:e}));try{const n=t.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==e.length)return void r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:e}));let c=!1;s&&i.some((t=>t.enabled))&&i.forEach((t=>t.enabled=!0)),a.forEach(((t,n)=>{var s;let a=null!==(s=t.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=_a(a),h=i.find((t=>t.quality===d));h&&t.active!==h.enabled&&(c=!0,t.active=h.enabled,r.debug("setting layer ".concat(h.quality," to ").concat(t.active?"enabled":"disabled"),o),Er()&&(h.enabled?(t.scaleResolutionDownBy=e[n].scaleResolutionDownBy,t.maxBitrate=e[n].maxBitrate,t.maxFrameRate=e[n].maxFrameRate):(t.scaleResolutionDownBy=4,t.maxBitrate=10,t.maxFrameRate=2)))})),c&&(n.encodings=a,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:n.encodings})),yield t.setParameters(n))}finally{a()}}))}function _a(t){switch(t){case"f":default:return vr.HIGH;case"h":return vr.MEDIUM;case"q":return vr.LOW}}function Ia(t,e,i,n){if(!i)return[new ge({quality:vr.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(n){const n=new xa(i[0].scalabilityMode),s=[],r="h"==n.suffix?1.5:2,o="h"==n.suffix?2:3;for(let a=0;a<n.spatial;a+=1)s.push(new ge({quality:Math.min(vr.HIGH,n.spatial-1)-a,width:Math.ceil(t/Math.pow(r,a)),height:Math.ceil(e/Math.pow(r,a)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(o,a)):0,ssrc:0}));return s}return i.map((i=>{var n,s,r;const o=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=_a(null!==(s=i.rid)&&void 0!==s?s:"");return new ge({quality:a,width:Math.ceil(t/o),height:Math.ceil(e/o),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const Ra="_lossy",ja="_reliable",Pa="leave-reconnect";var Da,Ma,Na,Ua;!function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"}(Da||(Da={}));class La extends vn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var e;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=ia.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Da.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=rn,this.reliableDataSequence=1,this.reliableMessageBuffer=new _o,this.reliableReceivedState=new Io(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=t=>hn(this,[t],void 0,(function(t){var e=this;let{channel:i}=t;return function*(){if(i){if(i.label===ja)e.reliableDCSub=i;else{if(i.label!==Ra)return;e.lossyDCSub=i}e.log.debug("on data channel ".concat(i.id,", ").concat(i.label),e.logContext),i.onmessage=e.handleDataMessage}}()})),this.handleDataMessage=t=>hn(this,void 0,void 0,(function*(){var e,i,n,s,r;const o=yield this.dataProcessLock.lock();try{let o;if(t.data instanceof ArrayBuffer)o=t.data;else{if(!(t.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:t.data}));o=yield t.data.arrayBuffer()}const a=ye.fromBinary(new Uint8Array(o));if(a.sequence>0&&""!==a.participantSid){const t=this.reliableReceivedState.get(a.participantSid);if(t&&a.sequence<=t)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}if("speaker"===(null===(e=a.value)||void 0===e?void 0:e.case))this.emit(Ps.ActiveSpeakersUpdate,a.value.value.speakers);else if("encryptedPacket"===(null===(i=a.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);const t=yield null===(n=this.e2eeManager)||void 0===n?void 0:n.handleEncryptedData(a.value.value.encryptedValue,a.value.value.iv,a.participantIdentity,a.value.value.keyIndex),e=Te.fromBinary(t.payload),i=new ye({value:e.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&Ba(i,i.value.value),this.emit(Ps.DataPacketReceived,i,a.value.value.encryptionType)}else"user"===(null===(r=a.value)||void 0===r?void 0:r.case)&&Ba(a,a.value.value),this.emit(Ps.DataPacketReceived,a,ve.NONE)}finally{o()}})),this.handleDataError=t=>{const e=0===t.currentTarget.maxRetransmits?"lossy":"reliable";if(t instanceof ErrorEvent&&t.error){const{error:i}=t.error;this.log.error("DataChannel error on ".concat(e,": ").concat(t.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(e),Object.assign(Object.assign({},this.logContext),{event:t}))},this.handleBufferedAmountLow=t=>{this.updateAndEmitDCBufferStatus(0===t.currentTarget.maxRetransmits?we.LOSSY:we.RELIABLE)},this.handleDisconnect=(t,e)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});null!==n?(t===Pa&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ws.setTimeout((()=>this.attemptReconnect(e).finally((()=>this.reconnectTimeout=void 0))),n)):(t=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up"),this.logContext),this.emit(Ps.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((t,e)=>{this.pcState===Da.Connected&&t();const i=()=>{this.off(Ps.Disconnected,n),t()},n=()=>{this.off(Ps.Restarted,i),e()};this.once(Ps.Restarted,i),this.once(Ps.Disconnected,n)})),this.updateAndEmitDCBufferStatus=t=>{if(t===we.RELIABLE){const e=this.dataChannelForKind(t);e&&this.reliableMessageBuffer.alignBufferedAmount(e.bufferedAmount)}const e=this.isBufferStatusLow(t);void 0!==e&&e!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,e),this.emit(Ps.DCBufferStatusChanged,e,t))},this.isBufferStatusLow=t=>{const e=this.dataChannelForKind(t);if(e)return e.bufferedAmount<=e.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>hn(this,void 0,void 0,(function*(){this.url&&(yield fetch(Hr(this.url),{method:"HEAD"}).then((t=>t.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===Oo.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Oo.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(se.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>hn(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(Hr(this.url),{method:"HEAD"}),yr(4e3).then((()=>Promise.reject()))])}catch(t){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=on(null!==(e=t.loggerName)&&void 0!==e?e:tn.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new xo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new u,this.dataProcessLock=new u,this.dcBufferStatus=new Map([[we.LOSSY,!0],[we.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(Ps.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(Ps.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(Ps.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(Ps.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(Ps.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(Ps.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(Ps.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(Ps.SignalRequestResponse,t)}get logContext(){var t,e,i,n,s,r;return{room:null===(e=null===(t=this.latestJoinResponse)||void 0===t?void 0:t.room)||void 0===e?void 0:e.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:this.participantSid}}join(t,e,i,n){return hn(this,arguments,void 0,(function(t,e,i,n){var s=this;let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){s.url=t,s.token=e,s.signalOpts=i,s.maxJoinAttempts=i.maxRetries;try{s.joinAttempts+=1,s.setupSignalClientCallbacks();const o=yield s.client.join(t,e,i,n,r);return s._isClosed=!1,s.latestJoinResponse=o,s.subscriberPrimary=o.subscriberPrimary,s.pcManager||(yield s.configure(o,!r)),s.subscriberPrimary&&!o.fastPublish||s.negotiate().catch((t=>{rn.error(t,s.logContext)})),s.registerOnLineListener(),s.clientConfiguration=o.clientConfiguration,s.emit(Ps.SignalConnected,o),o}catch(o){if(o instanceof Ms)if(o.reason===Cs.ServerUnreachable){if(s.log.warn("Couldn't connect to server, attempt ".concat(s.joinAttempts," of ").concat(s.maxJoinAttempts),s.logContext),s.joinAttempts<s.maxJoinAttempts)return s.join(t,e,i,n,r)}else if(o.reason===Cs.ServiceNotFound)return s.log.warn("Initial connection failed: ".concat(o.message," – Retrying")),s.join(t,e,i,n,!0);throw o}}()}))}close(){return hn(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Ps.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return hn(this,void 0,void 0,(function*(){var t;yield null===(t=this.pcManager)||void 0===t?void 0:t.close(),this.pcManager=void 0;const e=t=>{t&&(t.close(),t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new _o,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 hn(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(t){if(this.pendingTrackResolvers[t.cid])throw new Us("a track with the same ID has already been published");return new Promise(((e,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[t.cid],i(Ms.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[t.cid]={resolve:t=>{clearTimeout(n),e(t)},reject:()=>{clearTimeout(n),i(Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(t)}))}removeTrack(t){if(t.track&&this.pendingTrackResolvers[t.track.id]){const{reject:e}=this.pendingTrackResolvers[t.track.id];e&&e(),delete this.pendingTrackResolvers[t.track.id]}try{return this.pcManager.removeTrack(t),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(t,e){this.client.sendMuteTrack(t,e)}get dataSubscriberReadyState(){var t;return null===(t=this.reliableDCSub)||void 0===t?void 0:t.readyState}getConnectedServerAddress(){return hn(this,void 0,void 0,(function*(){var t;return null===(t=this.pcManager)||void 0===t?void 0:t.getConnectedAddress()}))}setRegionUrlProvider(t){this.regionUrlProvider=t}configure(t,e){return hn(this,void 0,void 0,(function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==na.NEW)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const s=this.makeRTCConfiguration(t);this.pcManager=new sa(s,e?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(Ps.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(t,e)=>{this.client.sendIceCandidate(t,e)},this.pcManager.onPublisherOffer=(t,e)=>{this.client.sendOffer(t,e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,i,n)=>hn(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(e),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),e===na.CONNECTED){const e=this.pcState===Da.New;this.pcState=Da.Connected,e&&this.emit(Ps.Connected,t)}else e===na.FAILED&&(this.pcState!==Da.Connected&&this.pcState!==Da.Reconnecting||(this.pcState=Da.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?se.RR_SUBSCRIBER_FAILED:se.RR_PUBLISHER_FAILED)));(this.client.isDisconnected||this.client.currentState===Oo.RECONNECTING)&&[na.FAILED,na.CLOSING,na.CLOSED].includes(e)&&!this._isClosed&&this.emit(Ps.Offline)})),this.pcManager.onTrack=t=>{0!==t.streams.length&&this.emit(Ps.MediaTrackAdded,t.track,t.streams[0],t.receiver)},function(t){return void 0!==t&&t>13}(null===(n=t.serverInfo)||void 0===n?void 0:n.protocol)||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=(t,e,i)=>hn(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:t.type,sdp:t.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(t,e))})),this.client.onTrickle=(t,e)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:t,target:e})),this.pcManager.addIceCandidate(t,e))},this.client.onOffer=(t,e,i)=>hn(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=e,!this.pcManager)return;this.midToTrackId=i;const n=yield this.pcManager.createSubscriberAnswerFromOffer(t,e);n&&this.client.sendAnswer(n,e)})),this.client.onLocalTrackPublished=t=>{var e;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:t.cid,track:null===(e=t.track)||void 0===e?void 0:e.sid})),!this.pendingTrackResolvers[t.cid])return void this.log.error("missing track resolver for ".concat(t.cid),Object.assign(Object.assign({},this.logContext),{cid:t.cid}));const{resolve:i}=this.pendingTrackResolvers[t.cid];delete this.pendingTrackResolvers[t.cid],i(t.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(Ps.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(Ps.LocalTrackSubscribed,t)},this.client.onTokenRefresh=t=>{var e;this.token=t,null===(e=this.regionUrlProvider)||void 0===e||e.updateToken(t)},this.client.onRemoteMuteChanged=(t,e)=>{this.emit(Ps.RemoteMute,t,e)},this.client.onSubscribedQualityUpdate=t=>{this.emit(Ps.SubscribedQualityUpdate,t)},this.client.onRoomMoved=t=>{var e;this.participantSid=null===(e=t.participant)||void 0===e?void 0:e.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=t.room),this.emit(Ps.RoomMoved,t)},this.client.onMediaSectionsRequirement=t=>{var e,i;const n={direction:"recvonly"};for(let i=0;i<t.numAudios;i++)null===(e=this.pcManager)||void 0===e||e.addPublisherTransceiverOfKind("audio",n);for(let e=0;e<t.numVideos;e++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("video",n);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",se.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==t?void 0:t.reason})),t.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:t.regions})),t.action){case pi.DISCONNECT:this.emit(Ps.Disconnected,null==t?void 0:t.reason),this.close();break;case pi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Pa);break;case pi.RESUME:this.handleDisconnect(Pa)}}}makeRTCConfiguration(t){var e;const i=Object.assign({},this.rtcConfig);if((null===(e=this.signalOpts)||void 0===e?void 0:e.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),t.iceServers&&!i.iceServers){const e=[];t.iceServers.forEach((t=>{const i={urls:t.urls};t.username&&(i.username=t.username),t.credential&&(i.credential=t.credential),e.push(i)})),i.iceServers=e}return t.clientConfiguration&&t.clientConfiguration.forceRelay===ie.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ra,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ja,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval((()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const t=this.dataChannelForKind(we.LOSSY);t&&(t.bufferedAmountLowThreshold=Math.min(Math.max(this.lossyDataStatByterate/10,8192),262144))}),1e3))}createSender(t,e,i){return hn(this,void 0,void 0,(function*(){if(wr())return yield this.createTransceiverRTCRtpSender(t,e,i);if(kr())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(t.mediaStreamTrack);throw new Bs("Required webRTC APIs not supported on this device")}))}createSimulcastSender(t,e,i,n){return hn(this,void 0,void 0,(function*(){if(wr())return this.createSimulcastTransceiverSender(t,e,i,n);if(kr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(t.mediaStreamTrack);throw new Bs("Cannot stream on this device")}))}createTransceiverRTCRtpSender(t,e,i){return hn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Bs("publisher is closed");const n=[];t.mediaStream&&n.push(t.mediaStream),to(t)&&(t.codec=e.videoCodec);const s={direction:"sendonly",streams:n};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(t,e,i,n){return hn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Bs("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s);if(i.videoCodec)return t.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(t){return hn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Bs("publisher is closed");return this.pcManager.addPublisherTrack(t)}))}attemptReconnect(t){return hn(this,void 0,void 0,(function*(){var e,i,n;if(!this._isClosed)if(this.attemptingReconnect)rn.warn("already attempting reconnect, returning early",this.logContext);else{(null===(e=this.clientConfiguration)||void 0===e?void 0:e.resumeConnection)!==ie.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:na.NEW)!==na.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let e=!0;t instanceof Bs?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof Js||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",se.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(Ps.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(t){try{return this.reconnectPolicy.nextRetryDelayInMs(t)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(t){return hn(this,void 0,void 0,(function*(){var e,i,n;try{if(!this.url||!this.token)throw new Bs("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Ps.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Js;i=yield this.join(null!=t?t:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(t){if(t instanceof Ms&&t.reason===Cs.NotAllowed)throw new Bs("could not reconnect, token might be expired");throw new Js}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(Ps.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Oo.CONNECTED)throw new Js("Signal connection got severed during reconnect");null===(e=this.regionUrlProvider)||void 0===e||e.resetAttempts(),this.emit(Ps.Restarted)}catch(t){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),t}}))}resumeConnection(t){return hn(this,void 0,void 0,(function*(){var e;if(!this.url||!this.token)throw new Bs("could not reconnect, url or token not saved");if(!this.pcManager)throw new Bs("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Ps.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(t){let e="";if(t instanceof Error&&(e=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof Ms&&t.reason===Cs.NotAllowed)throw new Bs("could not reconnect, token might be expired");if(t instanceof Ms&&t.reason===Cs.LeaveRequest)throw t;throw new Js(e)}if(this.emit(Ps.SignalResumed),i){const t=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(t),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Oo.CONNECTED)throw new Js("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(e=this.reliableDC)||void 0===e?void 0:e.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(Ps.Resumed)}))}waitForPCInitialConnection(t,e){return hn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Bs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(e,t)}))}waitForPCReconnected(){return hn(this,void 0,void 0,(function*(){this.pcState=Da.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield yr(2e3),!this.pcManager)throw new Bs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Da.Connected}catch(t){throw this.pcState=Da.Disconnected,Ms.internal("could not establish PC connection, ".concat(t.message))}}))}publishRpcResponse(t,e,i,n){return hn(this,void 0,void 0,(function*(){const s=new ye({destinationIdentities:[t],kind:we.RELIABLE,value:{case:"rpcResponse",value:new je({requestId:e,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,we.RELIABLE)}))}publishRpcAck(t,e){return hn(this,void 0,void 0,(function*(){const i=new ye({destinationIdentities:[t],kind:we.RELIABLE,value:{case:"rpcAck",value:new Re({requestId:e})}});yield this.sendDataPacket(i,we.RELIABLE)}))}sendDataPacket(t,e){return hn(this,void 0,void 0,(function*(){if(yield this.ensurePublisherConnected(e),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const e=function(t){var e,i,n,s,r;if("sipDtmf"!==(null===(e=t.value)||void 0===e?void 0:e.case)&&"metrics"!==(null===(i=t.value)||void 0===i?void 0:i.case)&&"speaker"!==(null===(n=t.value)||void 0===n?void 0:n.case)&&"transcription"!==(null===(s=t.value)||void 0===s?void 0:s.case)&&"encryptedPacket"!==(null===(r=t.value)||void 0===r?void 0:r.case))return new Te({value:t.value})}(t);if(e){const i=yield this.e2eeManager.encryptData(e.toBinary());t.value={case:"encryptedPacket",value:new ke({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}e===we.RELIABLE&&(t.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=t.toBinary(),n=this.dataChannelForKind(e);if(n){if(e===we.RELIABLE)yield this.waitForBufferStatusLow(e),this.reliableMessageBuffer.push({data:i,sequence:t.sequence});else{if(!this.isBufferStatusLow(e))return this.lossyDataDropCount+=1,void(this.lossyDataDropCount%100==0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext));this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(e)}))}resendReliableMessagesForResume(t){return hn(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(we.RELIABLE);const e=this.dataChannelForKind(we.RELIABLE);e&&(this.reliableMessageBuffer.popToSequence(t),this.reliableMessageBuffer.getAll().forEach((t=>{e.send(t.data)}))),this.updateAndEmitDCBufferStatus(we.RELIABLE)}))}waitForBufferStatusLow(t){return new ws(((e,i)=>hn(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(t))e();else{const n=()=>i(new Bs("engine closed"));for(this.once(Ps.Closing,n);!this.dcBufferStatus.get(t);)yield yr(10);this.off(Ps.Closing,n),e()}}))))}ensureDataTransportConnected(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!e.pcManager)throw new Bs("PC manager is closed");const s=i?e.pcManager.subscriber:e.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw Ms.internal("".concat(r," connection not set"));let o=!1;i||e.dataChannelForKind(t,i)||(e.createDataChannels(),o=!0),o||i||e.pcManager.publisher.isICEConnected||"checking"===e.pcManager.publisher.getICEConnectionState()||(o=!0),o&&e.negotiate().catch((t=>{rn.error(t,e.logContext)}));const a=e.dataChannelForKind(t,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+e.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=e.dataChannelForKind(t,i))||void 0===n?void 0:n.readyState))return;yield yr(50)}throw Ms.internal("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))}()}))}ensurePublisherConnected(t){return hn(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(t,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===na.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return hn(this,void 0,void 0,(function*(){return new ws(((t,e)=>hn(this,void 0,void 0,(function*(){if(!this.pcManager)return void e(new Fs("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&e(new Fs("cannot negotiate on closed engine")),this.on(Ps.Closing,n),this.pcManager.publisher.once(Go,(t=>{const e=new Map;t.forEach((t=>{const i=t.codec.toLowerCase();(function(t){return Ks.includes(t)})(i)&&e.set(t.payload,i)})),this.emit(Ps.RTPVideoMapUpdate,e)}));try{yield this.pcManager.negotiate(i),t()}catch(t){t instanceof Fs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",se.RR_UNKNOWN),e(t instanceof Error?t:Error(t+""))}finally{this.off(Ps.Closing,n)}}))))}))}dataChannelForKind(t,e){if(e){if(t===we.LOSSY)return this.lossyDCSub;if(t===we.RELIABLE)return this.reliableDCSub}else{if(t===we.LOSSY)return this.lossyDC;if(t===we.RELIABLE)return this.reliableDC}}sendSyncState(t,e){var i,n,s,r;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const o=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),c=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),d=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getLocalDescription(),h=null===(r=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===r||r,l=[],u=[];t.forEach((t=>{t.isDesired!==h&&l.push(t.trackSid),t.isEnabled||u.push(t.trackSid)})),this.client.sendSyncState(new Di({answer:"publisher-only"===this.pcManager.mode?a?Co({sdp:a.sdp,type:a.type}):void 0:d?Co({sdp:d.sdp,type:d.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?Co({sdp:o.sdp,type:o.type}):void 0:c?Co({sdp:c.sdp,type:c.type}):void 0,subscription:new li({trackSids:l,subscribe:!h,participantTracks:[]}),publishTracks:dr(e),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:u,datachannelReceiveStates:this.reliableReceivedState.map(((t,e)=>new Mi({publisherSid:e,lastSeq:t})))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const t=[],e=(e,i)=>{void 0!==(null==e?void 0:e.id)&&null!==e.id&&t.push(new Ni({label:e.label,id:e.id,target:i}))};return e(this.dataChannelForKind(we.LOSSY),Ye.PUBLISHER),e(this.dataChannelForKind(we.RELIABLE),Ye.PUBLISHER),e(this.dataChannelForKind(we.LOSSY,!0),Ye.SUBSCRIBER),e(this.dataChannelForKind(we.RELIABLE,!0),Ye.SUBSCRIBER),t}clearReconnectTimeout(){this.reconnectTimeout&&Ws.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){_r()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){_r()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(t){var e;const i=null===(e=this.pcManager)||void 0===e?void 0:e.getMidForReceiver(t);if(i){const t=Object.entries(this.midToTrackId).find((t=>{let[e]=t;return e===i}));if(t)return t[1]}}}function Ba(t,e){const i=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=i,e.participantIdentity=i;const n=0!==t.destinationIdentities.length?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=n,e.destinationIdentities=n}class Fa{get info(){return this._info}validateBytesReceived(){if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.bytesReceived<this.totalByteSize)throw new zs("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),_s.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new zs("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),_s.LengthExceeded)}}constructor(t,e,i,n){this.reader=e,this.totalByteSize=i,this._info=t,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class Va extends Fa{handleChunkReceived(t){var e;this.bytesReceived+=t.content.byteLength,this.validateBytesReceived(),null===(e=this.onProgress)||void 0===e||e.call(this,this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0)}[Symbol.asyncIterator](){const t=this.reader.getReader();let e=new Gr,i=null,n=null;if(this.signal){const t=this.signal;n=()=>{var i;null===(i=e.reject)||void 0===i||i.call(e,t.reason)},t.addEventListener("abort",n),i=t}const s=()=>{t.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>hn(this,void 0,void 0,(function*(){var i,n;try{const{done:s,value:r}=yield Promise.race([t.read(),e.promise,null!==(n=null===(i=this.outOfBandFailureRejectingFuture)||void 0===i?void 0:i.promise)&&void 0!==n?n:new Promise((()=>{}))]);return s?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r),{done:!1,value:r.content})}catch(t){throw s(),t}})),return(){return hn(this,void 0,void 0,(function*(){return s(),{done:!0,value:void 0}}))}}}withAbortSignal(t){return this.signal=t,this}readAll(){return hn(this,arguments,void 0,(function(){var t=this;let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s;let r=new Set;const o=e.signal?t.withAbortSignal(e.signal):t;try{for(var a,c=!0,d=ln(o);!(i=(a=yield d.next()).done);c=!0)c=!1,r.add(a.value)}catch(t){n={error:t}}finally{try{c||i||!(s=d.return)||(yield s.call(d))}finally{if(n)throw n.error}}return Array.from(r)}()}))}}class qa extends Fa{constructor(t,e,i,n){super(t,e,i,n),this.receivedChunks=new Map}handleChunkReceived(t){var e;const i=Yr(t.chunkIndex),n=this.receivedChunks.get(i);n&&n.version>t.version||(this.receivedChunks.set(i,t),this.bytesReceived+=t.content.byteLength,this.validateBytesReceived(),null===(e=this.onProgress)||void 0===e||e.call(this,this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0))}[Symbol.asyncIterator](){const t=this.reader.getReader(),e=new TextDecoder("utf-8",{fatal:!0});let i=new Gr,n=null,s=null;if(this.signal){const t=this.signal;s=()=>{var e;null===(e=i.reject)||void 0===e||e.call(i,t.reason)},t.addEventListener("abort",s),n=t}const r=()=>{t.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>hn(this,void 0,void 0,(function*(){var n,s;try{const{done:r,value:o}=yield Promise.race([t.read(),i.promise,null!==(s=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==s?s:new Promise((()=>{}))]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let t;this.handleChunkReceived(o);try{t=e.decode(o.content)}catch(t){throw new zs("Cannot decode datastream chunk ".concat(o.chunkIndex," as text: ").concat(t),_s.DecodeFailed)}return{done:!1,value:t}}}catch(t){throw r(),t}})),return(){return hn(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(t){return this.signal=t,this}readAll(){return hn(this,arguments,void 0,(function(){var t=this;let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s;let r="";const o=e.signal?t.withAbortSignal(e.signal):t;try{for(var a,c=!0,d=ln(o);!(i=(a=yield d.next()).done);c=!0)c=!1,r+=a.value}catch(t){n={error:t}}finally{try{c||i||!(s=d.return)||(yield s.call(d))}finally{if(n)throw n.error}}return r}()}))}}class za{constructor(){this.log=rn,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(t,e){if(this.textStreamHandlers.has(t))throw new zs('A text stream handler for topic "'.concat(t,'" has already been set.'),_s.HandlerAlreadyRegistered);this.textStreamHandlers.set(t,e)}unregisterTextStreamHandler(t){this.textStreamHandlers.delete(t)}registerByteStreamHandler(t,e){if(this.byteStreamHandlers.has(t))throw new zs('A byte stream handler for topic "'.concat(t,'" has already been set.'),_s.HandlerAlreadyRegistered);this.byteStreamHandlers.set(t,e)}unregisterByteStreamHandler(t){this.byteStreamHandlers.delete(t)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(t){var e,i,n,s;const r=Array.from(this.textStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t)),o=Array.from(this.byteStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t));if(r.length>0||o.length>0){const a=new zs("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),_s.AbnormalEnd);for(const[t,n]of o)null===(i=(e=n.outOfBandFailureRejectingFuture).reject)||void 0===i||i.call(e,a),this.byteStreamControllers.delete(t);for(const[t,e]of r)null===(s=(n=e.outOfBandFailureRejectingFuture).reject)||void 0===s||s.call(n,a),this.textStreamControllers.delete(t)}}handleDataStreamPacket(t,e){return hn(this,void 0,void 0,(function*(){switch(t.value.case){case"streamHeader":return this.handleStreamHeader(t.value.value,t.participantIdentity,e);case"streamChunk":return this.handleStreamChunk(t.value.value,e);case"streamTrailer":return this.handleStreamTrailer(t.value.value,e);default:throw Error('DataPacket of value "'.concat(t.value.case,'" is not data stream related!'))}}))}handleStreamHeader(t,e,i){return hn(this,void 0,void 0,(function*(){var n;if("byteHeader"===t.contentHeader.case){const s=this.byteStreamHandlers.get(t.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",t.topic);let r;const o=new Gr;o.promise.catch((t=>{this.log.error(t)}));const a={id:t.streamId,name:null!==(n=t.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Yr(t.timestamp),attributes:t.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(t.streamId))throw new zs("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),_s.AlreadyOpened);this.byteStreamControllers.set(t.streamId,{info:a,controller:r,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:o})}});s(new Va(a,c,Yr(t.totalLength),o),{identity:e})}else if("textHeader"===t.contentHeader.case){const n=this.textStreamHandlers.get(t.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);let s;const r=new Gr;r.promise.catch((t=>{this.log.error(t)}));const o={id:t.streamId,mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Number(t.timestamp),attributes:t.attributes,encryptionType:i},a=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(t.streamId))throw new zs("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),_s.AlreadyOpened);this.textStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:r})}});n(new qa(o,a,Yr(t.totalLength),r),{identity:e})}}))}handleStreamChunk(t,e){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==e?(i.controller.error(new zs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(i.info.encryptionType),_s.EncryptionTypeMismatch)),this.byteStreamControllers.delete(t.streamId)):t.content.length>0&&i.controller.enqueue(t));const n=this.textStreamControllers.get(t.streamId);n&&(n.info.encryptionType!==e?(n.controller.error(new zs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(n.info.encryptionType),_s.EncryptionTypeMismatch)),this.textStreamControllers.delete(t.streamId)):t.content.length>0&&n.controller.enqueue(t))}handleStreamTrailer(t,e){const i=this.textStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==e?i.controller.error(new zs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(i.info.encryptionType),_s.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),t.attributes),i.controller.close(),this.textStreamControllers.delete(t.streamId)));const n=this.byteStreamControllers.get(t.streamId);n&&(n.info.encryptionType!==e?n.controller.error(new zs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(n.info.encryptionType),_s.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),t.attributes),n.controller.close()),this.byteStreamControllers.delete(t.streamId))}}class Ja{constructor(t,e,i){this.writableStream=t,this.defaultWriter=t.getWriter(),this.onClose=i,this.info=e}write(t){return this.defaultWriter.write(t)}close(){return hn(this,void 0,void 0,(function*(){var t;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(t=this.onClose)||void 0===t||t.call(this)}))}}class Wa extends Ja{}class Ga extends Ja{}class Qa{constructor(t,e){this.engine=t,this.log=e}setupEngine(t){this.engine=t}sendText(t,e){return hn(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(t).byteLength,r=null===(i=null==e?void 0:e.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),o=Array(r?r.length+1:1).fill(0),a=(t,i)=>{var n;o[i]=t;const s=o.reduce(((t,e)=>t+e),0);null===(n=null==e?void 0:e.onProgress)||void 0===n||n.call(e,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==e?void 0:e.destinationIdentities,topic:null==e?void 0:e.topic,attachedStreamIds:r,attributes:null==e?void 0:e.attributes});return yield c.write(t),a(1,0),yield c.close(),(null==e?void 0:e.attachments)&&r&&(yield Promise.all(e.attachments.map(((t,i)=>hn(this,void 0,void 0,(function*(){return this._sendFile(r[i],t,{topic:e.topic,mimeType:t.type,onProgress:t=>{a(t,i+1)}})})))))),c.info}))}streamText(t){return hn(this,void 0,void 0,(function*(){var e,i,n;const s=null!==(e=null==t?void 0:t.streamId)&&void 0!==e?e:crypto.randomUUID(),r={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:null==t?void 0:t.totalSize,attributes:null==t?void 0:t.attributes,encryptionType:(null===(n=this.engine.e2eeManager)||void 0===n?void 0:n.isDataChannelEncryptionEnabled)?ve.GCM:ve.NONE},o=new Ge({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:Zr(r.timestamp),totalLength:Zr(null==t?void 0:t.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Je({version:null==t?void 0:t.version,attachedStreamIds:null==t?void 0:t.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?ze.UPDATE:ze.CREATE})}}),a=null==t?void 0:t.destinationIdentities,c=new ye({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,we.RELIABLE);let d=0;const h=this.engine,l=new WritableStream({write(t){return hn(this,void 0,void 0,(function*(){for(const e of function(t){const e=[];let i=(new TextEncoder).encode(t);for(;i.length>15e3;){let t=15e3;for(;t>0;){const e=i[t];if(void 0!==e&&128!=(192&e))break;t--}e.push(i.slice(0,t)),i=i.slice(t)}return i.length>0&&e.push(i),e}(t)){const t=new Qe({content:e,streamId:s,chunkIndex:Zr(d)}),i=new ye({destinationIdentities:a,value:{case:"streamChunk",value:t}});yield h.sendDataPacket(i,we.RELIABLE),d+=1}}))},close(){return hn(this,void 0,void 0,(function*(){const t=new He({streamId:s}),e=new ye({destinationIdentities:a,value:{case:"streamTrailer",value:t}});yield h.sendDataPacket(e,we.RELIABLE)}))},abort(t){console.log("Sink error:",t)}});let u=()=>hn(this,void 0,void 0,(function*(){yield f.close()}));h.once(Ps.Closing,u);const f=new Wa(l,r,(()=>this.engine.off(Ps.Closing,u)));return f}))}sendFile(t,e){return hn(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,t,e),{id:i}}))}_sendFile(t,e,i){return hn(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:t,totalSize:e.size,name:e.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:e.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=e.stream().getReader();for(;;){const{done:t,value:e}=yield r.read();if(t)break;yield s.write(e)}return yield s.close(),s.info}))}streamBytes(t){return hn(this,void 0,void 0,(function*(){var e,i,n,s,r,o;const a=null!==(e=null==t?void 0:t.streamId)&&void 0!==e?e:crypto.randomUUID(),c=null==t?void 0:t.destinationIdentities,d={id:a,mimeType:null!==(i=null==t?void 0:t.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==t?void 0:t.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==t?void 0:t.attributes,size:null==t?void 0:t.totalSize,name:null!==(s=null==t?void 0:t.name)&&void 0!==s?s:"unknown",encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?ve.GCM:ve.NONE},h=new Ge({totalLength:Zr(null!==(o=d.size)&&void 0!==o?o:0),mimeType:d.mimeType,streamId:a,topic:d.topic,timestamp:Zr(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new We({name:d.name})}}),l=new ye({destinationIdentities:c,value:{case:"streamHeader",value:h}});yield this.engine.sendDataPacket(l,we.RELIABLE);let f=0;const v=new u,m=this.engine,p=this.log,g=new WritableStream({write(t){return hn(this,void 0,void 0,(function*(){const e=yield v.lock();let i=0;try{for(;i<t.byteLength;){const e=t.slice(i,i+15e3),n=new ye({destinationIdentities:c,value:{case:"streamChunk",value:new Qe({content:e,streamId:a,chunkIndex:Zr(f)})}});yield m.sendDataPacket(n,we.RELIABLE),f+=1,i+=e.byteLength}}finally{e()}}))},close(){return hn(this,void 0,void 0,(function*(){const t=new He({streamId:a}),e=new ye({destinationIdentities:c,value:{case:"streamTrailer",value:t}});yield m.sendDataPacket(e,we.RELIABLE)}))},abort(t){p.error("Sink error:",t)}});return new Ga(g,d)}))}}class Ha extends mr{constructor(t,e,i,n,s){super(t,i,s),this.sid=e,this.receiver=n}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?Ds.Muted:Ds.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const e=i=>{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",e),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Ds.Ended,this))};t.addEventListener("removetrack",e)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return hn(this,void 0,void 0,(function*(){var t;if(null===(t=this.receiver)||void 0===t?void 0:t.getStats)return yield this.receiver.getStats()}))}setPlayoutDelay(t){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=t: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()),da)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var e;this.timeSyncHandle=requestAnimationFrame((()=>t()));const i=null===(e=this.receiver)||void 0===e?void 0:e.getSynchronizationSources()[0];if(i){const{timestamp:t,rtpTimestamp:e}=i;e&&this.rtpTimestamp!==e&&(this.emit(Ds.TimeSyncUpdate,{timestamp:t,rtpTimestamp:e}),this.rtpTimestamp=e)}};t()}}class Ka extends Ha{constructor(t,e,i,n,s,r){super(t,e,mr.Kind.Audio,i,r),this.monitorReceiver=()=>hn(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const t=yield this.getReceiverStats();t&&this.prevStats&&this.receiver&&(this._currentBitrate=ha(t,this.prevStats)),this.prevStats=t})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(t){var e;for(const i of this.attachedElements)this.audioContext?null===(e=this.gainNode)||void 0===e||e.gain.setTargetAtTime(t,0,.1):i.volume=t;Ir()&&this._mediaStreamTrack._setVolume(t),this.elementVolume=t}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ir())return 1;let t=0;return this.attachedElements.forEach((e=>{e.volume>t&&(t=e.volume)})),t}setSinkId(t){return hn(this,void 0,void 0,(function*(){this.sinkId=t,yield Promise.all(this.attachedElements.map((e=>{if(Sr(e))return e.setSinkId(t)})))}))}attach(t){const e=0===this.attachedElements.length;return t?super.attach(t):t=super.attach(),this.sinkId&&Sr(t)&&t.setSinkId(this.sinkId).catch((t=>{this.log.error("Failed to set sink id on remote audio track",t,this.logContext)})),this.audioContext&&e&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,t),t.volume=0,t.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),t}detach(t){let e;return t?(e=super.detach(t),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(e=super.detach(),this.disconnectWebAudio()),e}setAudioContext(t){this.audioContext=t,t&&this.attachedElements.length>0?this.connectWebAudio(t,this.attachedElements[0]):t||this.disconnectWebAudio()}setWebAudioPlugins(t){this.webAudioPluginNodes=t,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(t,e){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(e.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((t=>{i.connect(t),i=t})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(Ds.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(Ds.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var t,e;null===(t=this.gainNode)||void 0===t||t.disconnect(),null===(e=this.sourceNode)||void 0===e||e.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return hn(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let t;return(yield this.receiver.getStats()).forEach((e=>{"inbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})})),t}))}}class Ya extends Ha{constructor(t,e,i,n,s){super(t,e,mr.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>hn(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const t=yield this.getReceiverStats();t&&this.prevStats&&this.receiver&&(this._currentBitrate=ha(t,this.prevStats)),this.prevStats=t})),this.debouncedHandleResize=zo((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(t){super.setStreamState(t),this.log.debug("setStreamState",t),this.isAdaptiveStream&&t===mr.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(t){super.setMuted(t),this.attachedElements.forEach((e=>{t?gr(this._mediaStreamTrack,e):pr(this._mediaStreamTrack,e)}))}attach(t){if(t?super.attach(t):t=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((e=>e.element===t))){const e=new Za(t);this.observeElementInfo(e)}return t}observeElementInfo(t){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((e=>e===t))?(t.handleResize=()=>{this.debouncedHandleResize()},t.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(t),t.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(t){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const e=this.elementInfos.filter((e=>e===t));for(const t of e)t.stopObserving();this.elementInfos=this.elementInfos.filter((e=>e!==t)),this.updateVisibility(),this.debouncedHandleResize()}detach(t){let e=[];if(t)return this.stopObservingElement(t),super.detach(t);e=super.detach();for(const t of e)this.stopObservingElement(t);return e}getDecoderImplementation(){var t;return null===(t=this.prevStats)||void 0===t?void 0:t.decoderImplementation}getReceiverStats(){return hn(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const t=yield this.receiver.getStats();let e,i="",n=new Map;return t.forEach((t=>{"inbound-rtp"===t.type?(i=t.codecId,e={type:"video",streamId:t.id,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation}):"codec"===t.type&&n.set(t.id,t)})),e&&""!==i&&n.get(i)&&(e.mimeType=n.get(i).mimeType),e}))}stopObservingElement(t){const e=this.elementInfos.filter((e=>e.element===t));for(const t of e)this.stopObservingElementInfo(t)}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return hn(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(t){var e,i;const n=this.elementInfos.reduce(((t,e)=>Math.max(t,e.visibilityChangedAt||0)),0),s=!(null!==(i=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,r=this.elementInfos.some((t=>t.pictureInPicture)),o=this.elementInfos.some((t=>t.visible))&&!s||r;(this.lastVisible!==o||t)&&(!o&&Date.now()-n<100?Ws.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(Ds.VisibilityChanged,o,this)))}updateDimensions(){var t,e;let i=0,n=0;const s=this.getPixelDensity();for(const t of this.elementInfos){const e=t.width()*s,r=t.height()*s;e+r>i+n&&(i=e,n=r)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(e=this.lastDimensions)||void 0===e?void 0:e.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Ds.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var t;const e=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pixelDensity;return"screen"===e?Mr():e||(Mr()>2?2:1)}}class Za{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(t,e){this.onVisibilityChanged=t=>{var e;const{target:i,isIntersecting:n}=t;i===this.element&&(this.isIntersecting=n,this.isPiP=$a(this.element),this.visibilityChangedAt=Date.now(),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this))},this.onEnterPiP=()=>{var t,e,i;null===(e=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===e||e.addEventListener("pagehide",this.onLeavePiP),this.isPiP=$a(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var t;this.isPiP=$a(this.element),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this)},this.element=t,this.isIntersecting=null!=e?e:Xa(t),this.isPiP=_r()&&$a(t),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var t,e,i;this.isIntersecting=Xa(this.element),this.isPiP=$a(this.element),this.element.handleResize=()=>{var t;null===(t=this.handleResize)||void 0===t||t.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,qr().observe(this.element),Fr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(t=window.documentPictureInPicture)||void 0===t||t.addEventListener("enter",this.onEnterPiP),null===(i=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var t,e,i,n,s;null===(t=qr())||void 0===t||t.unobserve(this.element),null===(e=Fr())||void 0===e||e.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function $a(t){var e,i;return document.pictureInPictureElement===t||!!(null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)&&Xa(t,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Xa(t,e){const i=e||window;let n=t.offsetTop,s=t.offsetLeft;const r=t.offsetWidth,o=t.offsetHeight,{hidden:a}=t,{display:c}=getComputedStyle(t);for(;t.offsetParent;)n+=(t=t.offsetParent).offsetTop,s+=t.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&s+r>i.pageXOffset&&!a&&"none"!==c}class tc extends vn.EventEmitter{constructor(t,e,i,n){var s;super(),this.metadataMuted=!1,this.encryption=ve.NONE,this.log=rn,this.handleMuted=()=>{this.emit(Ds.Muted)},this.handleUnmuted=()=>{this.emit(Ds.Unmuted)},this.log=on(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:tn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=e,this.trackName=i,this.source=mr.Source.Unknown}setTrack(t){this.track&&(this.track.off(Ds.Muted,this.handleMuted),this.track.off(Ds.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(Ds.Muted,this.handleMuted),t.on(Ds.Unmuted,this.handleUnmuted))}get logContext(){var t;return Object.assign(Object.assign({},null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this)),hr(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ve.NONE}get audioTrack(){if(Xr(this.track))return this.track}get videoTrack(){if(to(this.track))return this.track}updateInfo(t){this.trackSid=t.sid,this.trackName=t.name,this.source=mr.sourceFromProto(t.source),this.mimeType=t.mimeType,this.kind===mr.Kind.Video&&t.width>0&&(this.dimensions={width:t.width,height:t.height},this.simulcasted=t.simulcast),this.encryption=t.encryption,this.trackInfo=t,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:t}))}}!function(t){!function(t){t.Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed"}(t.SubscriptionStatus||(t.SubscriptionStatus={})),function(t){t.Allowed="allowed",t.NotAllowed="not_allowed"}(t.PermissionStatus||(t.PermissionStatus={}))}(tc||(tc={}));class ec extends tc{get isUpstreamPaused(){var t;return null===(t=this.track)||void 0===t?void 0:t.isUpstreamPaused}constructor(t,e,i,n){super(t,e.sid,e.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Ds.Ended)},this.handleCpuConstrained=()=>{this.track&&to(this.track)&&this.emit(Ds.CpuConstrained,this.track)},this.updateInfo(e),this.setTrack(i)}setTrack(t){this.track&&(this.track.off(Ds.Ended,this.handleTrackEnded),this.track.off(Ds.CpuConstrained,this.handleCpuConstrained)),super.setTrack(t),t&&(t.on(Ds.Ended,this.handleTrackEnded),t.on(Ds.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 hn(this,void 0,void 0,(function*(){var t;return null===(t=this.track)||void 0===t?void 0:t.mute()}))}unmute(){return hn(this,void 0,void 0,(function*(){var t;return null===(t=this.track)||void 0===t?void 0:t.unmute()}))}pauseUpstream(){return hn(this,void 0,void 0,(function*(){var t;yield null===(t=this.track)||void 0===t?void 0:t.pauseUpstream()}))}resumeUpstream(){return hn(this,void 0,void 0,(function*(){var t;yield null===(t=this.track)||void 0===t?void 0:t.resumeUpstream()}))}getTrackFeatures(){var t;if(Xr(this.track)){const e=this.track.getSourceTrackSettings(),i=new Set;return e.autoGainControl&&i.add(oe.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&i.add(oe.TF_ECHO_CANCELLATION),e.noiseSuppression&&i.add(oe.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&i.add(oe.TF_STEREO),(null===(t=this.options)||void 0===t?void 0:t.dtx)||i.add(oe.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(oe.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function ic(t,e){return hn(this,void 0,void 0,(function*(){null!=t||(t={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=lr(t);let o=r.audio,a=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),t.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const t=r.audio.deviceId;r.audio.deviceId={exact:t},i=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:t}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const t=r.video.deviceId;r.video.deviceId={exact:t},i=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:t}})}!0===r.audio?r.audio={deviceId:"default"}:"object"==typeof r.audio&&null!==r.audio&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),!0===r.video?r.video={deviceId:"default"}:"object"!=typeof r.video||r.video.deviceId||(r.video.deviceId="default");const c=sr(ir(r,Xo,ta)),d=navigator.mediaDevices.getUserMedia(c);r.audio&&(wo.userMediaPromiseMap.set("audioinput",d),d.catch((()=>wo.userMediaPromiseMap.delete("audioinput")))),r.video&&(wo.userMediaPromiseMap.set("videoinput",d),d.catch((()=>wo.userMediaPromiseMap.delete("videoinput"))));try{const t=yield d;return yield Promise.all(t.getTracks().map((i=>hn(this,void 0,void 0,(function*(){let r;const o="audio"===i.kind?c.audio:c.video;"boolean"!=typeof o&&(r=o);const a=i.getSettings().deviceId;(null==r?void 0:r.deviceId)&&Qr(r.deviceId)!==a?r.deviceId=a:r||(r={deviceId:a});const d=function(t,e,i){switch(t.kind){case"audio":return new ma(t,e,!1,void 0,i);case"video":return new Aa(t,e,!1,i);default:throw new Us("unsupported track type: ".concat(t.kind))}}(i,r,e);return d.kind===mr.Kind.Video?d.source=mr.Source.Camera:d.kind===mr.Kind.Audio&&(d.source=mr.Source.Microphone),d.mediaStream=t,Xr(d)&&n?yield d.setProcessor(n):to(d)&&s&&(yield d.setProcessor(s)),d})))))}catch(n){if(!i)throw n;return ic(Object.assign(Object.assign({},t),{audio:o,video:a}),e)}}))}!function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"}(Ma||(Ma={}));class nc extends vn.EventEmitter{get logContext(){var t,e;return Object.assign({},null===(e=null===(t=this.loggerOptions)||void 0===t?void 0:t.loggerContextCb)||void 0===e?void 0:e.call(t))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((t=>t.isEncrypted))}get isAgent(){var t;return(null===(t=this.permissions)||void 0===t?void 0:t.agent)||this.kind===ue.AGENT}get isActive(){var t;return(null===(t=this.participantInfo)||void 0===t?void 0:t.state)===le.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,e,i,n,s,r){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ue.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Ma.Unknown,this.log=rn,this.log=on(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:tn.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=t,this.identity=e,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(t){for(const[,e]of this.trackPublications)if(e.source===t)return e}getTrackPublicationByName(t){for(const[,e]of this.trackPublications)if(e.trackName===t)return e}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Gr,this.once(js.Active,(()=>{var t,e;null===(e=null===(t=this.activeFuture)||void 0===t?void 0:t.resolve)||void 0===e||e.call(t),this.activeFuture=void 0}))),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var t;const e=this.getTrackPublication(mr.Source.Camera);return!(null===(t=null==e?void 0:e.isMuted)||void 0===t||t)}get isMicrophoneEnabled(){var t;const e=this.getTrackPublication(mr.Source.Microphone);return!(null===(t=null==e?void 0:e.isMuted)||void 0===t||t)}get isScreenShareEnabled(){return!!this.getTrackPublication(mr.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(""+this.participantInfo.joinedAt)):new Date}updateInfo(t){var e;return!(this.participantInfo&&this.participantInfo.sid===t.sid&&this.participantInfo.version>t.version||(this.identity=t.identity,this.sid=t.sid,this._setName(t.name),this._setMetadata(t.metadata),this._setAttributes(t.attributes),t.state===le.ACTIVE&&(null===(e=this.participantInfo)||void 0===e?void 0:e.state)!==le.ACTIVE&&this.emit(js.Active),t.permission&&this.setPermissions(t.permission),this.participantInfo=t,0))}_setMetadata(t){const e=this.metadata!==t,i=this.metadata;this.metadata=t,e&&this.emit(js.ParticipantMetadataChanged,i)}_setName(t){const e=this.name!==t;this.name=t,e&&this.emit(js.ParticipantNameChanged,t)}_setAttributes(t){const e=function(t,e){var i;void 0===t&&(t={}),void 0===e&&(e={});const n=[...Object.keys(e),...Object.keys(t)],s={};for(const r of n)t[r]!==e[r]&&(s[r]=null!==(i=e[r])&&void 0!==i?i:"");return s}(this.attributes,t);this._attributes=t,Object.keys(e).length>0&&this.emit(js.AttributesChanged,e)}setPermissions(t){var e,i,n,s,r,o;const a=this.permissions,c=t.canPublish!==(null===(e=this.permissions)||void 0===e?void 0:e.canPublish)||t.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||t.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||t.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||t.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((t,e)=>{var i;return t!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[e])}))||t.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=t,c&&this.emit(js.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(js.IsSpeakingChanged,t))}setConnectionQuality(t){const e=this._connectionQuality;this._connectionQuality=function(t){switch(t){case ee.EXCELLENT:return Ma.Excellent;case ee.GOOD:return Ma.Good;case ee.POOR:return Ma.Poor;case ee.LOST:return Ma.Lost;default:return Ma.Unknown}}(t),e!==this._connectionQuality&&this.emit(js.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var t,e;this.activeFuture&&(null===(e=(t=this.activeFuture).reject)||void 0===e||e.call(t,Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(t){this.audioContext=t,this.audioTrackPublications.forEach((e=>Xr(e.track)&&e.track.setAudioContext(t)))}addTrackPublication(t){switch(t.on(Ds.Muted,(()=>{this.emit(js.TrackMuted,t)})),t.on(Ds.Unmuted,(()=>{this.emit(js.TrackUnmuted,t)})),t.track&&(t.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case mr.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case mr.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class sc extends nc{constructor(t,e,i,n,s,r){super(t,e,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=ve.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Gr)},this.handleReconnected=()=>{var t,e;null===(e=null===(t=this.reconnectFuture)||void 0===t?void 0:t.resolve)||void 0===e||e.call(t),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var t,e,i,n,s,r;this.reconnectFuture&&(this.reconnectFuture.promise.catch((t=>this.log.warn(t.message,this.logContext))),null===(e=null===(t=this.reconnectFuture)||void 0===t?void 0:t.reject)||void 0===e||e.call(t,Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(r=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=t=>{var e,i;t.participant&&this.updateInfo(t.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Gr),null===(i=(e=this.signalConnectedFuture).resolve)||void 0===i||i.call(e)},this.handleSignalRequestResponse=t=>{const{requestId:e,reason:i,message:n}=t,s=this.pendingSignalRequests.get(e);s&&(i!==Ji.OK&&s.reject(new qs(n,i)),this.pendingSignalRequests.delete(e))},this.handleDataPacket=t=>{switch(t.value.case){case"rpcResponse":let e=t.value.value,i=null,n=null;"payload"===e.value.case?i=e.value.value:"error"===e.value.case&&(n=oa.fromProto(e.value.value)),this.handleIncomingRpcResponse(e.requestId,i,n);break;case"rpcAck":this.handleIncomingRpcAck(t.value.value.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((t=>function(t){var e,i,n;if(!t.participantSid&&!t.participantIdentity)throw Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ii({participantIdentity:null!==(e=t.participantIdentity)&&void 0!==e?e:"",participantSid:null!==(i=t.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=t.allowAll)&&void 0!==n&&n,trackSids:t.allowedTrackSids||[]})}(t))))},this.onTrackUnmuted=t=>{this.onTrackMuted(t,t.isUpstreamPaused)},this.onTrackMuted=(t,e)=>{void 0===e&&(e=!0),t.sid?this.engine.updateMuteStatus(t.sid,e):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),hr(t)))},this.onTrackUpstreamPaused=t=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),hr(t))),this.onTrackMuted(t,!0)},this.onTrackUpstreamResumed=t=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),hr(t))),this.onTrackMuted(t,t.isMuted)},this.onTrackFeatureUpdate=t=>{const e=this.audioTrackPublications.get(t.sid);e?this.engine.client.sendUpdateLocalAudioTrack(e.trackSid,e.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(t.sid),this.logContext)},this.onTrackCpuConstrained=(t,e)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),hr(e))),this.emit(js.LocalTrackCpuConstrained,t,e)},this.handleSubscribedQualityUpdate=t=>hn(this,void 0,void 0,(function*(){var e,i,n,s;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const r=this.videoTrackPublications.get(t.trackSid);if(!r)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:t.trackSid}));if(!r.videoTrack)return;const o=yield r.videoTrack.setPublishingCodecs(t.subscribedCodecs);try{for(var a,c=!0,d=ln(o);!(e=(a=yield d.next()).done);c=!0){c=!1;const t=a.value;Ys(t)&&(this.log.debug("publish ".concat(t," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),hr(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,t,r.options))}}catch(t){i={error:t}}finally{try{c||e||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}})),this.handleLocalTrackUnpublished=t=>{const e=this.trackPublications.get(t.trackSid);e?this.unpublishTrack(e.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:t.trackSid}))},this.handleTrackEnded=t=>hn(this,void 0,void 0,(function*(){if(t.source===mr.Source.ScreenShare||t.source===mr.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),hr(t))),this.unpublishTrack(t);else if(t.isUserProvided)yield t.mute();else if(io(t)||eo(t))try{if(_r())try{const e=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:t.source===mr.Source.Camera?"camera":"microphone"});if(e&&"denied"===e.state)throw this.log.warn("user has revoked access to ".concat(t.source),Object.assign(Object.assign({},this.logContext),hr(t))),e.onchange=()=>{"denied"!==e.state&&(t.isMuted||t.restartTrack(),e.onchange=null)},Error("GetUserMedia Permission denied")}catch(t){}t.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),hr(t))),io(t)?yield t.restartTrack({deviceId:"default"}):yield t.restartTrack())}catch(e){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),hr(t))),yield t.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==ve.NONE}getTrackPublication(t){const e=super.getTrackPublication(t);if(e)return e}getTrackPublicationByName(t){const e=super.getTrackPublicationByName(t);if(e)return e}setupEngine(t){var e;this.engine=t,this.engine.on(Ps.RemoteMute,((t,e)=>{const i=this.trackPublications.get(t);i&&i.track&&(e?i.mute():i.unmute())})),(null===(e=this.signalConnectedFuture)||void 0===e?void 0:e.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(Ps.Connected,this.handleReconnected).on(Ps.SignalConnected,this.handleSignalConnected).on(Ps.SignalRestarted,this.handleReconnected).on(Ps.SignalResumed,this.handleReconnected).on(Ps.Restarting,this.handleReconnecting).on(Ps.Resuming,this.handleReconnecting).on(Ps.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Ps.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Ps.Closing,this.handleClosing).on(Ps.SignalRequestResponse,this.handleSignalRequestResponse).on(Ps.DataPacketReceived,this.handleDataPacket)}setMetadata(t){return hn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:t})}))}setName(t){return hn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:t})}))}setAttributes(t){return hn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:t})}))}requestMetadataUpdate(t){return hn(this,arguments,void 0,(function(t){var e=this;let{metadata:i,name:n,attributes:s}=t;return function*(){return new ws(((t,r)=>hn(e,void 0,void 0,(function*(){var e,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(e=null!=i?i:this.metadata)&&void 0!==e?e:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:t,reject:t=>{r(t),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((t=>{let[e,i]=t;return this.attributes[e]===i||""===i&&!this.attributes[e]}))))return this.pendingSignalRequests.delete(c),void t();yield yr(50)}r(new qs("Request to update local metadata timed out","TimeoutError"))}catch(t){r(t instanceof Error?t:Error(t+""))}}))))}()}))}setCameraEnabled(t,e,i){return this.setTrackEnabled(mr.Source.Camera,t,e,i)}setMicrophoneEnabled(t,e,i){return this.setTrackEnabled(mr.Source.Microphone,t,e,i)}setScreenShareEnabled(t,e,i){return this.setTrackEnabled(mr.Source.ScreenShare,t,e,i)}setE2EEEnabled(t){return hn(this,void 0,void 0,(function*(){this.encryptionType=t?ve.GCM:ve.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,e,i,n){return hn(this,void 0,void 0,(function*(){var s,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:e})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(t);if(e)if(o)yield o.unmute();else{let e;if(this.pendingPublishing.has(t)){const e=yield this.waitForPendingPublicationOfSource(t);return e||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t})),yield null==e?void 0:e.unmute(),e}this.pendingPublishing.add(t);try{switch(t){case mr.Source.Camera:e=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case mr.Source.Microphone:e=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case mr.Source.ScreenShare:e=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Us(t)}}catch(i){throw null==e||e.forEach((t=>{t.stop()})),i instanceof Error&&this.emit(js.MediaDevicesError,i,ar(t)),this.pendingPublishing.delete(t),i}for(const n of e){const e=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);t===mr.Source.Microphone&&Xr(n)&&e.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{const t=[];for(const i of e)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),hr(i))),t.push(this.publishTrack(i,n));const i=yield Promise.all(t);[o]=i}catch(t){throw null==e||e.forEach((t=>{t.stop()})),t}finally{this.pendingPublishing.delete(t)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(t)&&(o=yield this.waitForPendingPublicationOfSource(t),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t}))),o&&o.track)if(t===mr.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const t=this.getTrackPublication(mr.Source.ScreenShareAudio);t&&t.track&&this.unpublishTrack(t.track)}else yield o.mute();return o}))}enableCameraAndMicrophone(){return hn(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(mr.Source.Camera)&&!this.pendingPublishing.has(mr.Source.Microphone)){this.pendingPublishing.add(mr.Source.Camera),this.pendingPublishing.add(mr.Source.Microphone);try{const t=yield this.createTracks({audio:!0,video:!0});yield Promise.all(t.map((t=>this.publishTrack(t))))}finally{this.pendingPublishing.delete(mr.Source.Camera),this.pendingPublishing.delete(mr.Source.Microphone)}}}))}createTracks(t){return hn(this,void 0,void 0,(function*(){var e,i;null!=t||(t={});const n=ir(t,null===(e=this.roomOptions)||void 0===e?void 0:e.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield ic(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((t=>(Xr(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=mr.Source.Microphone,this.emit(js.AudioStreamAcquired)),to(t)&&(this.cameraError=void 0,t.source=mr.Source.Camera),t)))}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}}))}createScreenTracks(t){return hn(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Ns("getDisplayMedia not supported");void 0!==t.resolution||function(){const t=Ss();return"Safari"===(null==t?void 0:t.name)&&t.version.startsWith("17.")||"iOS"===(null==t?void 0:t.os)&&!!(null==t?void 0:t.osVersion)&&Nr(t.osVersion,"17")>=0}()||(t.resolution=er.h1080fps30.resolution);const e=function(t){var e,i;let n=null===(e=t.video)||void 0===e||e;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=xr()?Object.assign(Object.assign({},n),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:null!==(i=t.audio)&&void 0!==i&&i,video:n,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}(t),i=yield navigator.mediaDevices.getDisplayMedia(e),n=i.getVideoTracks();if(0===n.length)throw new Us("no video track found");const s=new Aa(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=mr.Source.ScreenShare,t.contentHint&&(s.mediaStreamTrack.contentHint=t.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(js.AudioStreamAcquired);const t=new ma(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=mr.Source.ScreenShareAudio,r.push(t)}return r}))}publishTrack(t,e){return hn(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(t,e)}))}publishOrRepublishTrack(t,e){return hn(this,arguments,void 0,(function(t,e){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,o,a;let c,d;if(io(t)&&t.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),$r(t)&&i.pendingPublishPromises.has(t)&&(yield i.pendingPublishPromises.get(t)),t instanceof MediaStreamTrack)c=t.getConstraints();else{let e;switch(c=t.constraints,t.source){case mr.Source.Microphone:e="audioinput";break;case mr.Source.Camera:e="videoinput"}e&&i.activeDeviceMap.has(e)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(e)}))}if(t instanceof MediaStreamTrack)switch(t.kind){case"audio":t=new ma(t,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":t=new Aa(t,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Us("unsupported MediaStreamTrack kind ".concat(t.kind))}else t.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach((e=>{e.track&&e.track===t&&(d=e)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),hr(d))),d;const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),e),l="channelCount"in t.mediaStreamTrack.getSettings()&&2===t.mediaStreamTrack.getSettings().channelCount||2===t.mediaStreamTrack.getConstraints().channelCount,u=null!==(r=h.forceStereo)&&void 0!==r?r:l;u&&(void 0===h.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),hr(t))),void 0===h.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=h.dtx)&&void 0!==o||(h.dtx=!1),null!==(a=h.red)&&void 0!==a||(h.red=!1)),!function(){const t=Ss(),e="17.2";if(t)return"Safari"!==t.name&&"iOS"!==t.os||!!("iOS"===t.os&&t.osVersion&&Nr(t.osVersion,e)>=0)||"Safari"===t.name&&Nr(t.version,e)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),h.simulcast=!1),h.source&&(t.source=h.source);const f=new Promise(((e,n)=>hn(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==Oo.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:hr(t)}));let i=!1;const s=setTimeout((()=>{i=!0,t.stop(),n(new Vs("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(s),i)return;const r=yield this.publish(t,h,u);e(r)}else try{const i=yield this.publish(t,h,u);e(i)}catch(t){n(t)}}catch(t){n(t)}}))));i.pendingPublishPromises.set(t,f);try{return yield f}catch(t){throw t}finally{i.pendingPublishPromises.delete(t)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Gr),this.signalConnectedFuture.promise}hasPermissionsToPublish(t){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),hr(t))),!1;const{canPublish:e,canPublishSources:i}=this.permissions;return!(!e||0!==i.length&&!i.map((t=>function(t){switch(t){case Xt.CAMERA:return mr.Source.Camera;case Xt.MICROPHONE:return mr.Source.Microphone;case Xt.SCREEN_SHARE:return mr.Source.ScreenShare;case Xt.SCREEN_SHARE_AUDIO:return mr.Source.ScreenShareAudio;default:return mr.Source.Unknown}}(t))).includes(t.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),hr(t))),!1)}publish(t,e,i){return hn(this,void 0,void 0,(function*(){var n,s,r,o,a,c,d,h,l,u;if(!this.hasPermissionsToPublish(t))throw new Vs("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>$r(t)&&e.source===t.source))&&t.source!==mr.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),hr(t))),e.stopMicTrackOnMute&&Xr(t)&&(t.stopOnMute=!0),t.source===mr.Source.ScreenShare&&Er()&&(e.simulcast=!1),"av1"!==e.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(xr()||Er())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t)for(const i of t.codecs)if("video/av1"===i.mimeType.toLowerCase()){e=!0;break}return e}()||(e.videoCodec=void 0),"vp9"!==e.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Er())return!1;if(xr()){const t=Ss();if((null==t?void 0:t.version)&&Nr(t.version,"16")<0)return!1;if("iOS"===(null==t?void 0:t.os)&&(null==t?void 0:t.osVersion)&&Nr(t.osVersion,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t)for(const i of t.codecs)if("video/vp9"===i.mimeType.toLowerCase()){e=!0;break}return e}()||(e.videoCodec=void 0),void 0===e.videoCodec&&(e.videoCodec=Zo),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((t=>e.videoCodec===cr(t.mime)))||(e.videoCodec=cr(this.enabledPublishVideoCodecs[0].mime)));const f=e.videoCodec;t.on(Ds.Muted,this.onTrackMuted),t.on(Ds.Unmuted,this.onTrackUnmuted),t.on(Ds.Ended,this.handleTrackEnded),t.on(Ds.UpstreamPaused,this.onTrackUpstreamPaused),t.on(Ds.UpstreamResumed,this.onTrackUpstreamResumed),t.on(Ds.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],m=!(null===(n=e.dtx)||void 0===n||n),p=t.getSourceTrackSettings();p.autoGainControl&&v.push(oe.TF_AUTO_GAIN_CONTROL),p.echoCancellation&&v.push(oe.TF_ECHO_CANCELLATION),p.noiseSuppression&&v.push(oe.TF_NOISE_SUPPRESSION),p.channelCount&&p.channelCount>1&&v.push(oe.TF_STEREO),m&&v.push(oe.TF_NO_DTX),io(t)&&t.hasPreConnectBuffer&&v.push(oe.TF_PRECONNECT_BUFFER);const g=new ii({cid:t.mediaStreamTrack.id,name:e.name,type:mr.kindToProto(t.kind),muted:t.isMuted,source:mr.sourceToProto(t.source),disableDtx:m,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=e.red)||void 0===s||s),stream:null==e?void 0:e.stream,backupCodecPolicy:null==e?void 0:e.backupCodecPolicy,audioFeatures:v});let b;if(t.kind===mr.Kind.Video){let i={width:0,height:0};try{i=yield t.waitForDimensions()}catch(e){const n=null!==(o=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==o?o:Xs.h720.resolution;i={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{dims:i}))}g.width=i.width,g.height=i.height,eo(t)&&(Tr(f)&&(t.source===mr.Source.ScreenShare&&(e.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),hr(t))))),e.scalabilityMode=null!==(a=e.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),g.simulcastCodecs=[new ei({codec:f,cid:t.mediaStreamTrack.id})],!0===e.backupCodec&&(e.backupCodec={codec:Zo}),e.backupCodec&&f!==e.backupCodec.codec&&g.encryption===ve.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new ei({codec:e.backupCodec.codec,cid:""})))),b=Ta(t.source===mr.Source.ScreenShare,g.width,g.height,e),g.layers=Ia(g.width,g.height,b,Tr(e.videoCodec))}else t.kind===mr.Kind.Audio&&(b=[{maxBitrate:null===(c=e.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(h=null===(d=e.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==h?h:"high",networkPriority:null!==(u=null===(l=e.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high"}]);if(!this.engine||this.engine.isClosed)throw new Bs("cannot publish track when not connected");const y=()=>hn(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new Bs("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,e,b),this.emit(js.LocalSenderCreated,t.sender,t),eo(t)&&(null!==(i=e.degradationPreference)&&void 0!==i||(e.degradationPreference=function(t){return t.source===mr.Source.ScreenShare||t.constraints.height&&Qr(t.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(e.degradationPreference)),b)if(Er()&&t.kind===mr.Kind.Audio){let e;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===t.sender){e=i;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(n=b[0])||void 0===n?void 0:n.maxBitrate)?b[0].maxBitrate/1e3:0})}else t.codec&&Tr(t.codec)&&(null===(s=b[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:t.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()}));let w;const k=new Promise(((e,i)=>hn(this,void 0,void 0,(function*(){var n;try{w=yield this.engine.addTrack(g),e(w)}catch(e){t.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(t.sender),yield this.engine.negotiate().catch((e=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{error:e}))}))),i(e)}}))));if(this.enabledPublishVideoCodecs.length>0){const t=yield Promise.all([k,y()]);w=t[0]}else{let i;if(w=yield k,w.codecs.forEach((t=>{void 0===i&&(i=t.mimeType)})),i&&t.kind===mr.Kind.Video){const n=cr(i);n!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{codec:n})),e.videoCodec=n,b=Ta(t.source===mr.Source.ScreenShare,g.width,g.height,e))}yield y()}const T=new ec(t.kind,w,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(T.on(Ds.CpuConstrained,(t=>this.onTrackCpuConstrained(t,T))),T.options=e,t.sid=w.sid,this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:w})),eo(t)?t.startMonitor(this.engine.client):io(t)&&t.startMonitor(),this.addTrackPublication(T),this.emit(js.LocalTrackPublished,T),io(t)&&w.audioFeatures.includes(oe.TF_PRECONNECT_BUFFER)){const e=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(js.LocalTrackSubscribed,(e=>{if(e.trackSid===w.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),hr(t))),t.stopPreConnectBuffer()}})),e){const n=new Promise(((n,s)=>hn(this,void 0,void 0,(function*(){var r,o,a,c,d;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),hr(t)));const f=setTimeout((()=>{s(Error("agent not active within 10 seconds"))}),1e4),v=yield this.waitUntilActiveAgentPresent();clearTimeout(f),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),hr(t)));const m=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[v.identity],attributes:{trackId:T.trackSid,sampleRate:(null!==(c=p.sampleRate)&&void 0!==c?c:"48000")+"",channels:(null!==(d=p.channelCount)&&void 0!==d?d:"1")+""}});try{for(var h,l=!0,u=ln(e);!(r=(h=yield u.next()).done);l=!0){l=!1;const t=h.value;yield m.write(t)}}catch(t){o={error:t}}finally{try{l||r||!(a=u.return)||(yield a.call(u))}finally{if(o)throw o.error}}yield m.close(),n()}catch(t){s(t)}}))));n.then((()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),hr(t)))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{error:e}))}))}}return T}))}get isLocal(){return!0}publishAdditionalCodecForTrack(t,e,i){return hn(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==ve.NONE)return;let s;if(this.trackPublications.forEach((e=>{e.track&&e.track===t&&(s=e)})),!s)throw new Us("track is not published");if(!eo(t))throw new Us("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(t,e,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;e!==i.backupCodec.codec&&rn.warn("requested a different codec than specified as backup",{serverRequested:e,backup:i.backupCodec.codec}),i.videoCodec=e,i.videoEncoding=i.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=t.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=t.dimensions)||void 0===o?void 0:o.height;return t.source===mr.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),Ta(t.source===mr.Source.ScreenShare,c,d,i)}(t,e,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),hr(t)));const a=t.addSimulcastTrack(e,o);if(!a)return;const c=new ii({cid:a.mediaStreamTrack.id,type:mr.kindToProto(t.kind),muted:t.isMuted,source:mr.sourceToProto(t.source),sid:t.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Ia(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Bs("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>hn(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(t,a,r,o),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(e," for track ").concat(t.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))}))}unpublishTrack(t,e){return hn(this,void 0,void 0,(function*(){var i,n;if($r(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),hr(t))),yield e)}const s=this.getPublicationForTrack(t),r=s?hr(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(t=s.track).off(Ds.Muted,this.onTrackMuted),t.off(Ds.Unmuted,this.onTrackUnmuted),t.off(Ds.Ended,this.handleTrackEnded),t.off(Ds.UpstreamPaused,this.onTrackUpstreamPaused),t.off(Ds.UpstreamResumed,this.onTrackUpstreamResumed),t.off(Ds.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===e&&(e=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),e?t.stop():t.stopMonitor();let o=!1;const a=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<na.FAILED&&a)try{for(const t of this.engine.pcManager.publisher.getTransceivers())t.sender===a&&(t.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),eo(t)){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(o=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(t){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:t}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case mr.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case mr.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(js.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(t){return hn(this,void 0,void 0,(function*(){return(yield Promise.all(t.map((t=>this.unpublishTrack(t))))).filter((t=>!!t))}))}republishAllTracks(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){e.republishPromise&&(yield e.republishPromise),e.republishPromise=new ws(((n,s)=>hn(e,void 0,void 0,(function*(){try{const e=[];this.trackPublications.forEach((i=>{i.track&&(t&&(i.options=Object.assign(Object.assign({},i.options),t)),e.push(i))})),yield Promise.all(e.map((t=>hn(this,void 0,void 0,(function*(){const e=t.track;yield this.unpublishTrack(e,!1),!i||e.isMuted||e.source===mr.Source.ScreenShare||e.source===mr.Source.ScreenShareAudio||!io(e)&&!eo(e)||e.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:t.trackSid})),yield e.restartTrack()),yield this.publishOrRepublishTrack(e,t.options,!0)}))))),n()}catch(t){s(t instanceof Error?t:Error(t+""))}finally{this.republishPromise=void 0}})))),yield e.republishPromise}()}))}publishData(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?we.RELIABLE:we.LOSSY;let s=new Oe({participantIdentity:e.identity,payload:t,destinationIdentities:i.destinationIdentities,topic:i.topic});const r=new ye({kind:n,value:{case:"user",value:s}});yield e.engine.sendDataPacket(r,n)}()}))}publishDtmf(t,e){return hn(this,void 0,void 0,(function*(){const i=new ye({kind:we.RELIABLE,value:{case:"sipDtmf",value:new xe({code:t,digit:e})}});yield this.engine.sendDataPacket(i,we.RELIABLE)}))}sendChatMessage(t,e){return hn(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:t,timestamp:Date.now(),attachedFiles:null==e?void 0:e.attachments},n=new ye({value:{case:"chatMessage",value:new _e(Object.assign(Object.assign({},i),{timestamp:U.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,we.RELIABLE),this.emit(js.ChatMessage,i),i}))}editChatMessage(t,e){return hn(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},e),{message:t,editTimestamp:Date.now()}),n=new ye({value:{case:"chatMessage",value:new _e(Object.assign(Object.assign({},i),{timestamp:U.parse(i.timestamp),editTimestamp:U.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,we.RELIABLE),this.emit(js.ChatMessage,i),i}))}sendText(t,e){return hn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(t,e)}))}streamText(t){return hn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(t)}))}sendFile(t,e){return hn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(t,e)}))}streamBytes(t){return hn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(t)}))}performRpc(t){let{destinationIdentity:e,method:i,payload:n,responseTimeout:s=15e3}=t;return new ws(((t,r)=>hn(this,void 0,void 0,(function*(){var o,a,c,d;if(aa(n)>15360)return void r(oa.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(o=this.engine.latestJoinResponse)||void 0===o?void 0:o.serverInfo)||void 0===a?void 0:a.version)&&Nr(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void r(oa.builtIn("UNSUPPORTED_SERVER"));const h=Math.max(s,8e3),l=crypto.randomUUID();yield this.publishRpcRequest(e,l,i,n,h);const u=setTimeout((()=>{this.pendingAcks.delete(l),r(oa.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(f)}),7e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:e});const f=setTimeout((()=>{this.pendingResponses.delete(l),r(oa.builtIn("RESPONSE_TIMEOUT"))}),s);this.pendingResponses.set(l,{resolve:(e,i)=>{clearTimeout(f),this.pendingAcks.has(l)&&(this.log.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?r(i):t(null!=e?e:"")},participantIdentity:e})}))))}registerRpcMethod(t,e){this.rpcHandlers.has(t)&&this.log.warn("you're overriding the RPC handler for method ".concat(t,", in the future this will throw an error")),this.rpcHandlers.set(t,e)}unregisterRpcMethod(t){this.rpcHandlers.delete(t)}setTrackSubscriptionPermissions(t){this.participantTrackPermissions=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],this.allParticipantsAllowedToSubscribe=t,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(t){const e=this.pendingAcks.get(t);e?(e.resolve(),this.pendingAcks.delete(t)):console.error("Ack received for unexpected RPC request",t)}handleIncomingRpcResponse(t,e,i){const n=this.pendingResponses.get(t);n?(n.resolve(e,i),this.pendingResponses.delete(t)):console.error("Response received for unexpected RPC request",t)}publishRpcRequest(t,e,i,n,s){return hn(this,void 0,void 0,(function*(){const r=new ye({destinationIdentities:[t],kind:we.RELIABLE,value:{case:"rpcRequest",value:new Ie({id:e,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,we.RELIABLE)}))}handleParticipantDisconnected(t){for(const[e,{participantIdentity:i}]of this.pendingAcks)i===t&&this.pendingAcks.delete(e);for(const[e,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===t&&(n(null,oa.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(e))}setEnabledPublishCodecs(t){this.enabledPublishVideoCodecs=t.filter((t=>"video"===t.mime.split("/")[0].toLowerCase()))}updateInfo(t){return!!super.updateInfo(t)&&(t.tracks.forEach((t=>{var e,i;const n=this.trackPublications.get(t.sid);if(n){const s=n.isMuted||null!==(i=null===(e=n.track)||void 0===e?void 0:e.isUpstreamPaused)&&void 0!==i&&i;s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),hr(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}})),!0)}setActiveAgent(t){var e,i,n,s;this.firstActiveAgent=t,t&&!this.firstActiveAgent&&(this.firstActiveAgent=t),t?null===(i=null===(e=this.activeAgentFuture)||void 0===e?void 0:e.resolve)||void 0===i||i.call(e,t):null===(s=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Gr),this.activeAgentFuture.promise)}getPublicationForTrack(t){let e;return this.trackPublications.forEach((i=>{const n=i.track;n&&(t instanceof MediaStreamTrack?(io(n)||eo(n))&&n.mediaStreamTrack===t&&(e=i):t===n&&(e=i))})),e}waitForPendingPublicationOfSource(t){return hn(this,void 0,void 0,(function*(){const e=Date.now();for(;Date.now()<e+1e4;){const e=Array.from(this.pendingPublishPromises.entries()).find((e=>{let[i]=e;return i.source===t}));if(e)return e[1];yield yr(20)}}))}}class rc extends tc{constructor(t,e,i,n){super(t,e.sid,e.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=t=>{this.setTrack(void 0),this.emit(Ds.Ended,t)},this.handleVisibilityChange=t=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(t),this.logContext),this.visible=t,this.emitTrackUpdate()},this.handleVideoDimensionsChange=t=>{this.log.debug("adaptivestream video dimensions ".concat(t.width,"x").concat(t.height),this.logContext),this.videoDimensionsAdaptiveStream=t,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(e)}setSubscribed(t){const e=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const n=new li({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new De({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Ds.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(e),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?tc.SubscriptionStatus.Unsubscribed:super.isSubscribed?tc.SubscriptionStatus.Subscribed:tc.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?tc.PermissionStatus.Allowed:tc.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(t){this.isManualOperationAllowed()&&this.requestedDisabled!==!t&&(this.requestedDisabled=!t,this.emitTrackUpdate())}setVideoQuality(t){this.isManualOperationAllowed()&&this.requestedMaxQuality!==t&&(this.requestedMaxQuality=t,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(t){var e,i;this.isManualOperationAllowed()&&((null===(e=this.requestedVideoDimensions)||void 0===e?void 0:e.width)===t.width&&(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)===t.height||(ro(this.track)&&(this.requestedVideoDimensions=t),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(t){this.isManualOperationAllowed()&&ro(this.track)&&this.fps!==t&&(this.fps=t,this.emitTrackUpdate())}get videoQuality(){var t;return null!==(t=this.requestedMaxQuality)&&void 0!==t?t:vr.HIGH}setTrack(t){const e=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==t&&(n&&(n.off(Ds.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Ds.VisibilityChanged,this.handleVisibilityChange),n.off(Ds.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Ds.Unsubscribed,n)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(Ds.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(Ds.VisibilityChanged,this.handleVisibilityChange),t.on(Ds.Ended,this.handleEnded),this.emit(Ds.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(e))}setAllowed(t){const e=this.subscriptionStatus,i=this.permissionStatus;this.allowed=t,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(e)}setSubscriptionError(t){this.emit(Ds.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const e=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):e!==t.muted&&this.emit(t.muted?Ds.Muted:Ds.Unmuted)}emitSubscriptionUpdateIfChanged(t){const e=this.subscriptionStatus;t!==e&&this.emit(Ds.SubscriptionStatusChanged,e,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(Ds.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return ro(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new ui({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===mr.Kind.Video){let e=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(e)ur(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const t=function(t,e){var i;return null===(i=t.layers)||void 0===i?void 0:i.find((t=>t.quality===e))}(this.trackInfo,this.requestedMaxQuality);t&&ur(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream;e?(t.width=Math.ceil(e.width),t.height=Math.ceil(e.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),t.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:vr.HIGH})),t.quality=vr.HIGH)}this.emit(Ds.UpdateSettings,t)}}class oc extends nc{static fromParticipantInfo(t,e,i){return new oc(t,e.sid,e.identity,e.name,e.metadata,e.attributes,i,e.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(t,e,i,n,s,r,o){super(e,i||"",n,s,r,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:ue.STANDARD),this.signalClient=t,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(Ds.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)})),t.on(Ds.UpdateSubscription,(t=>{t.participantTracks.forEach((t=>{t.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(t)})),t.on(Ds.SubscriptionPermissionChanged,(e=>{this.emit(js.TrackSubscriptionPermissionChanged,t,e)})),t.on(Ds.SubscriptionStatusChanged,(e=>{this.emit(js.TrackSubscriptionStatusChanged,t,e)})),t.on(Ds.Subscribed,(e=>{this.emit(js.TrackSubscribed,e,t)})),t.on(Ds.Unsubscribed,(e=>{this.emit(js.TrackUnsubscribed,e,t)})),t.on(Ds.SubscriptionFailed,(e=>{this.emit(js.TrackSubscriptionFailed,t.trackSid,e)}))}getTrackPublication(t){const e=super.getTrackPublication(t);if(e)return e}getTrackPublicationByName(t){const e=super.getTrackPublicationByName(t);if(e)return e}setVolume(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mr.Source.Microphone;this.volumeMap.set(e,t);const i=this.getTrackPublication(e);i&&i.track&&i.track.setVolume(t)}getVolume(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mr.Source.Microphone;const e=this.getTrackPublication(t);return e&&e.track?e.track.getVolume():this.volumeMap.get(t)}addSubscribedMediaTrack(t,e,i,n,s,r){let o,a=this.getTrackPublicationBySid(e);return a||e.startsWith("TR")||this.trackPublications.forEach((e=>{a||t.kind!==""+e.kind||(a=e)})),a?"ended"===t.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),hr(a))),void this.emit(js.TrackSubscriptionFailed,e)):(o="video"===t.kind?new Ya(t,e,n,s):new Ka(t,e,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)&&no(o)&&Xr(o)&&o.setVolume(this.volumeMap.get(a.source)),a):0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:e})),void this.emit(js.TrackSubscriptionFailed,e)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,e,i,n,s,r-1)}),150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(t){return this.trackPublications.get(t)}updateInfo(t){if(!super.updateInfo(t))return!1;const e=new Map,i=new Map;return t.tracks.forEach((t=>{var n,s;let r=this.getTrackPublicationBySid(t.sid);if(r)r.updateInfo(t);else{const e=mr.kindFromProto(t.type);if(!e)return;r=new rc(e,t,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(t),i.set(t.sid,r);const o=Array.from(this.trackPublications.values()).find((t=>t.source===(null==r?void 0:r.source)));o&&r.source!==mr.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:hr(o),newTrack:hr(r)})),this.addTrackPublication(r)}e.set(t.sid,r)})),this.trackPublications.forEach((t=>{e.has(t.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),hr(t))),this.unpublishTrack(t.trackSid,!0))})),i.forEach((t=>{this.emit(js.TrackPublished,t)})),!0}unpublishTrack(t,e){const i=this.trackPublications.get(t);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case mr.Kind.Audio:this.audioTrackPublications.delete(t);break;case mr.Kind.Video:this.videoTrackPublications.delete(t)}e&&this.emit(js.TrackUnpublished,i)}setAudioOutput(t){return hn(this,void 0,void 0,(function*(){this.audioOutput=t;const e=[];this.audioTrackPublications.forEach((i=>{var n;Xr(i.track)&&no(i.track)&&e.push(i.track.setSinkId(null!==(n=t.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(e)}))}emit(t){for(var e=arguments.length,i=Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:t,args:i})),super.emit(t,...i)}}!function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"}(Na||(Na={}));class ac extends vn.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(t){var e,i,n,s,r;if(super(),e=this,this.state=Na.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=rn,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(t,e,i)=>hn(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!wr()&&!kr())throw Ir()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const s=yield this.disconnectLock.lock();if(this.state===Na.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(Na.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:""+n.getServerUrl())!==oo(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Rr(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new ra(t,e):this.regionUrlProvider.updateToken(e),this.regionUrlProvider.fetchRegionSettings().then((t=>{var e;null===(e=this.regionUrlProvider)||void 0===e||e.setServerReportedRegions(t)})).catch((t=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:t}))})));const r=(n,o,a)=>hn(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const h=new AbortController;this.abortController=h,null==s||s();try{if(yield bo.getInstance().getBackOffPromise(t),h.signal.aborted)throw Ms.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=a?a:t,e,i,h),this.abortController=void 0,n()}catch(e){if(this.regionUrlProvider&&e instanceof Ms&&e.reason!==Cs.Cancelled&&e.reason!==Cs.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(t){if(t instanceof Ms&&(401===t.status||t.reason===Cs.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(t)}[Cs.InternalError,Cs.ServerUnreachable,Cs.Timeout].includes(e.reason)&&(this.log.debug("Adding failed connection attempt to back off"),bo.getInstance().addFailedConnectionAttempt(t)),i&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(e.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield r(n,o,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Kr(e)),o(e))}else{let t=ne.UNKNOWN_REASON;e instanceof Ms&&(t=Kr(e)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),o(e)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Gr(((t,e)=>{r(t,e,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(t,e,i,n,s,r)=>hn(this,void 0,void 0,(function*(){var o,a,c;const d=yield i.join(t,e,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal,!s.singlePeerConnection);let h=d.serverInfo;if(h||(h={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=h,this.log.debug("connected to Livekit Server ".concat(Object.entries(h).map((t=>{let[e,i]=t;return"".concat(e,": ").concat(i)})).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!h.version)throw new Ls("unknown server version");return"0.15.1"===h.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=t=>{const e=t.participant;if(this.localParticipant.sid=e.sid,this.localParticipant.identity=e.identity,this.localParticipant.setEnabledPublishCodecs(t.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(t.sifTrailer)}catch(t){this.log.error(t instanceof Error?t.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:t}))}this.handleParticipantUpdates([e,...t.otherParticipants]),t.room&&this.handleRoomUpdate(t.room)},this.attemptConnection=(t,e,i,n)=>hn(this,void 0,void 0,(function*(){var s,r;this.state===Na.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ia),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(t,e,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Rs.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();const e=n.signal.aborted?Ms.cancelled("Signal connection aborted"):Ms.serverUnreachable("could not establish signal connection");throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof Ms&&(e.reason=t.reason,e.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),Ms.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(t){throw yield this.engine.close(),this.recreateEngine(),t}_r()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),_r()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Na.Connected),this.emit(Rs.Connected),bo.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,i=Array(t),n=0;n<t;n++)i[n]=arguments[n];return hn(e,[...i],void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s;const r=yield t.disconnectLock.lock();try{if(t.state===Na.Disconnected)return void t.log.debug("already disconnected",t.logContext);if(t.log.info("disconnect from room",Object.assign({},t.logContext)),t.state===Na.Connecting||t.state===Na.Reconnecting||t.isResuming){const e="Abort connection attempt due to user initiated disconnect";t.log.warn(e,t.logContext),null===(i=t.abortController)||void 0===i||i.abort(e),null===(s=null===(n=t.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,Ms.cancelled("Client initiated disconnect")),t.connectFuture=void 0}t.engine&&(t.engine.client.isDisconnected||(yield t.engine.client.sendLeave()),yield t.engine.close()),t.handleDisconnect(e,ne.CLIENT_INITIATED),t.engine=void 0}finally{r()}}()}))},this.onPageLeave=()=>hn(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>hn(this,void 0,void 0,(function*(){const t=[],e=Ss();if(e&&"iOS"===e.os){const e="livekit-dummy-audio-el";let i=document.getElementById(e);if(!i){i=document.createElement("audio"),i.id=e,i.autoplay=!0,i.hidden=!0;const t=Wr();t.enabled=!0;const n=new MediaStream([t]);i.srcObject=n,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(Rs.Disconnected,(()=>{null==i||i.remove(),i=null}))}t.push(i)}this.remoteParticipants.forEach((e=>{e.audioTrackPublications.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((t=>(t.muted=!1,t.play())))]),this.handleAudioPlaybackStarted()}catch(t){throw this.handleAudioPlaybackFailed(t),t}})),this.startVideo=()=>hn(this,void 0,void 0,(function*(){const t=[];for(const e of this.remoteParticipants.values())e.videoTrackPublications.forEach((e=>{var i;null===(i=e.track)||void 0===i||i.attachedElements.forEach((e=>{t.includes(e)||t.push(e)}))}));yield Promise.all(t.map((t=>t.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((t=>{"NotAllowedError"===t.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const t of this.remoteParticipants.values())this.handleParticipantDisconnected(t.identity,t);this.setAndEmitConnectionState(Na.Reconnecting)&&this.emit(Rs.Reconnecting)},this.handleSignalRestarted=t=>hn(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),Object.assign(Object.assign({},this.logContext),{region:t.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:t.serverRegion}))}catch(t){return}this.setAndEmitConnectionState(Na.Connected),this.emit(Rs.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=t=>{t.forEach((t=>{var e;if(t.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(t);""===t.identity&&(t.identity=null!==(e=this.sidToIdentity.get(t.sid))&&void 0!==e?e:"");let i=this.remoteParticipants.get(t.identity);t.state===le.DISCONNECTED?this.handleParticipantDisconnected(t.identity,i):i=this.getOrCreateParticipant(t.identity,t)}))},this.handleActiveSpeakersUpdate=t=>{const e=[],i={};t.forEach((t=>{if(i[t.sid]=!0,t.sid===this.localParticipant.sid)this.localParticipant.audioLevel=t.level,this.localParticipant.setIsSpeaking(!0),e.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(t.sid);i&&(i.audioLevel=t.level,i.setIsSpeaking(!0),e.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((t=>{i[t.sid]||(t.audioLevel=0,t.setIsSpeaking(!1))})),this.activeSpeakers=e,this.emitWhenConnected(Rs.ActiveSpeakersChanged,e)},this.handleSpeakersChanged=t=>{const e=new Map;this.activeSpeakers.forEach((t=>{const i=this.remoteParticipants.get(t.identity);i&&i.sid!==t.sid||e.set(t.sid,t)})),t.forEach((t=>{let i=this.getRemoteParticipantBySid(t.sid);t.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=t.level,i.setIsSpeaking(t.active),t.active?e.set(t.sid,i):e.delete(t.sid))}));const i=Array.from(e.values());i.sort(((t,e)=>e.audioLevel-t.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(Rs.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const e=this.getRemoteParticipantBySid(t.participantSid);if(!e)return;const i=e.getTrackPublicationBySid(t.trackSid);if(!i||!i.track)return;const n=mr.streamStateFromProto(t.state);i.track.setStreamState(n),n!==i.track.streamState&&(e.emit(js.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Rs.TrackStreamStateChanged,i,i.track.streamState,e))}))},this.handleSubscriptionPermissionUpdate=t=>{const e=this.getRemoteParticipantBySid(t.participantSid);if(!e)return;const i=e.getTrackPublicationBySid(t.trackSid);i&&i.setAllowed(t.allowed)},this.handleSubscriptionError=t=>{const e=Array.from(this.remoteParticipants.values()).find((e=>e.trackPublications.has(t.trackSid)));if(!e)return;const i=e.getTrackPublicationBySid(t.trackSid);i&&i.setSubscriptionError(t.err)},this.handleDataPacket=(t,e)=>{const i=this.remoteParticipants.get(t.participantIdentity);if("user"===t.value.case)this.handleUserPacket(i,t.value.value,t.kind,e);else if("transcription"===t.value.case)this.handleTranscription(i,t.value.value);else if("sipDtmf"===t.value.case)this.handleSipDtmf(i,t.value.value);else if("chatMessage"===t.value.case)this.handleChatMessage(i,t.value.value);else if("metrics"===t.value.case)this.handleMetrics(t.value.value,i);else if("streamHeader"===t.value.case||"streamChunk"===t.value.case||"streamTrailer"===t.value.case)this.handleDataStream(t,e);else if("rpcRequest"===t.value.case){const e=t.value.value;this.handleIncomingRpcRequest(t.participantIdentity,e.id,e.method,e.payload,e.responseTimeoutMs,e.version)}},this.handleUserPacket=(t,e,i,n)=>{this.emit(Rs.DataReceived,e.payload,t,i,e.topic,n),null==t||t.emit(js.DataReceived,e.payload,i,n)},this.handleSipDtmf=(t,e)=>{this.emit(Rs.SipDTMFReceived,e,t),null==t||t.emit(js.SipDTMFReceived,e)},this.handleTranscription=(t,e)=>{const i=e.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(e.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(e.trackId),s=function(t,e){return t.segments.map((t=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=t;var c;const d=null!==(c=e.get(i))&&void 0!==c?c:Date.now(),h=Date.now();return a?e.delete(i):e.set(i,d),{id:i,text:n,startTime:Number.parseInt(""+r),endTime:Number.parseInt(""+o),final:a,language:s,firstReceivedTime:d,lastReceivedTime:h}}))}(e,this.transcriptionReceivedTimes);null==n||n.emit(Ds.TranscriptionReceived,s),null==i||i.emit(js.TranscriptionReceived,s,n),this.emit(Rs.TranscriptionReceived,s,i,n)},this.handleChatMessage=(t,e)=>{const i=function(t){const{id:e,timestamp:i,message:n,editTimestamp:s}=t;return{id:e,timestamp:Number.parseInt(""+i),editTimestamp:s?Number.parseInt(""+s):void 0,message:n}}(e);this.emit(Rs.ChatMessage,i,t)},this.handleMetrics=(t,e)=>{this.emit(Rs.MetricsReceived,t,e)},this.handleDataStream=(t,e)=>{this.incomingDataStreamManager.handleDataStreamPacket(t,e)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Rs.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:t})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Rs.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Rs.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Rs.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>hn(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=Ss())||void 0===t?void 0:t.os)&&(yield this.selectDefaultDevices()),this.emit(Rs.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const e=this.roomInfo;this.roomInfo=t,e&&e.metadata!==t.metadata&&this.emitWhenConnected(Rs.RoomMetadataChanged,t.metadata),(null==e?void 0:e.activeRecording)!==t.activeRecording&&this.emitWhenConnected(Rs.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=t=>{t.updates.forEach((t=>{if(t.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(t.quality);const e=this.getRemoteParticipantBySid(t.participantSid);e&&e.setConnectionQuality(t.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(Rs.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(Rs.ParticipantNameChanged,t,this.localParticipant)},this.onLocalAttributesChanged=t=>{this.emit(Rs.ParticipantAttributesChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(Rs.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(Rs.TrackUnmuted,t,this.localParticipant)},this.onTrackProcessorUpdate=t=>{var e;null===(e=null==t?void 0:t.onPublish)||void 0===e||e.call(t,this)},this.onLocalTrackPublished=t=>hn(this,void 0,void 0,(function*(){var e,i,n,s,r,o;null===(e=t.track)||void 0===e||e.on(Ds.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.on(Ds.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=t.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(Rs.LocalTrackPublished,t,this.localParticipant),io(t.track)&&(yield t.track.checkForSilence())&&this.emit(Rs.LocalAudioSilenceDetected,t);const a=yield null===(o=t.track)||void 0===o?void 0:o.getDeviceId(!1),c=ar(t.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(Rs.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=t=>{var e,i;null===(e=t.track)||void 0===e||e.off(Ds.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.off(Ds.Restarted,this.onLocalTrackRestarted),this.emit(Rs.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>hn(this,void 0,void 0,(function*(){const e=yield t.getDeviceId(!1),i=ar(t.source);i&&e&&e!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(e," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,e),this.emit(Rs.ActiveDeviceChanged,i,e))})),this.onLocalConnectionQualityChanged=t=>{this.emit(Rs.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=(t,e)=>{this.emit(Rs.MediaDevicesError,t,e)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(Rs.ParticipantPermissionsChanged,t,this.localParticipant)},this.onLocalChatMessageSent=t=>{this.emit(Rs.ChatMessage,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},ea),t),this.log=on(null!==(i=this.options.loggerName)&&void 0!==i?i:tn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Xo),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ta),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},$o),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new za,this.outgoingDataStreamManager=new Qa(this.engine,this.log),this.disconnectLock=new u,this.localParticipant=new sc("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Qr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Qr(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Qr(this.options.audioOutput.deviceId)).catch((t=>this.log.warn("Could not set audio output: ".concat(t.message),this.logContext))),_r()){const t=new AbortController;null===(r=null===(s=navigator.mediaDevices)||void 0===s?void 0:s.addEventListener)||void 0===r||r.call(s,"devicechange",this.handleDeviceChange,{signal:t.signal}),ac.cleanupRegistry&&ac.cleanupRegistry.register(this,(()=>{t.abort()}))}}registerTextStreamHandler(t,e){return this.incomingDataStreamManager.registerTextStreamHandler(t,e)}unregisterTextStreamHandler(t){return this.incomingDataStreamManager.unregisterTextStreamHandler(t)}registerByteStreamHandler(t,e){return this.incomingDataStreamManager.registerByteStreamHandler(t,e)}unregisterByteStreamHandler(t){return this.incomingDataStreamManager.unregisterByteStreamHandler(t)}registerRpcMethod(t,e){if(this.rpcHandlers.has(t))throw Error("RPC handler already registered for method ".concat(t,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(t,e)}unregisterRpcMethod(t){this.rpcHandlers.delete(t)}setE2EEEnabled(t){return hn(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(t)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(t,this.localParticipant.identity)}))}setupE2EE(){var t;const e=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=e):this.e2eeManager=new go(i,e),this.e2eeManager.on(fo.ParticipantEncryptionStatusChanged,((t,e)=>{(function(t){return t.isLocal})(e)&&(this.isE2EEEnabled=t),this.emit(Rs.ParticipantEncryptionStatusChanged,t,e)})),this.e2eeManager.on(fo.EncryptionError,((t,e)=>{const i=e?this.getParticipantByIdentity(e):void 0;this.emit(Rs.EncryptionError,t,i)})),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get logContext(){var t;return{room:this.name,roomID:null===(t=this.roomInfo)||void 0===t?void 0:t.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var t,e;return null!==(e=null===(t=this.roomInfo)||void 0===t?void 0:t.activeRecording)&&void 0!==e&&e}getSid(){return this.state===Na.Disconnected?ws.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?ws.resolve(this.roomInfo.sid):new ws(((t,e)=>{const i=e=>{""!==e.sid&&(this.engine.off(Ps.RoomUpdate,i),t(e.sid))};this.engine.on(Ps.RoomUpdate,i),this.once(Rs.Disconnected,(()=>{this.engine.off(Ps.RoomUpdate,i),e(new Bs("Room disconnected before room server id was available"))}))}))}get name(){var t,e;return null!==(e=null===(t=this.roomInfo)||void 0===t?void 0:t.name)&&void 0!==e?e:""}get metadata(){var t;return null===(t=this.roomInfo)||void 0===t?void 0:t.metadata}get numParticipants(){var t,e;return null!==(e=null===(t=this.roomInfo)||void 0===t?void 0:t.numParticipants)&&void 0!==e?e:0}get numPublishers(){var t,e;return null!==(e=null===(t=this.roomInfo)||void 0===t?void 0:t.numPublishers)&&void 0!==e?e:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new La(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Ps.ParticipantUpdate,this.handleParticipantUpdates).on(Ps.RoomUpdate,this.handleRoomUpdate).on(Ps.SpeakersChanged,this.handleSpeakersChanged).on(Ps.StreamStateChanged,this.handleStreamStateUpdate).on(Ps.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Ps.SubscriptionError,this.handleSubscriptionError).on(Ps.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Ps.MediaTrackAdded,((t,e,i)=>{this.onTrackAdded(t,e,i)})).on(Ps.Disconnected,(t=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t)})).on(Ps.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Ps.DataPacketReceived,this.handleDataPacket).on(Ps.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Na.SignalReconnecting)&&this.emit(Rs.SignalReconnecting)})).on(Ps.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Na.Connected)&&this.emit(Rs.Reconnected)})).on(Ps.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Na.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Ps.Restarting,this.handleRestarting).on(Ps.SignalRestarted,this.handleSignalRestarted).on(Ps.Offline,(()=>{this.setAndEmitConnectionState(Na.Reconnecting)&&this.emit(Rs.Reconnecting)})).on(Ps.DCBufferStatusChanged,((t,e)=>{this.emit(Rs.DCBufferStatusChanged,t,e)})).on(Ps.LocalTrackSubscribed,(t=>{const e=this.localParticipant.getTrackPublications().find((e=>{let{trackSid:i}=e;return i===t}));e?(this.localParticipant.emit(js.LocalTrackSubscribed,e),this.emitWhenConnected(Rs.LocalTrackSubscribed,e,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})).on(Ps.RoomMoved,(t=>{this.log.debug("room moved",t),t.room&&this.handleRoomUpdate(t.room),this.remoteParticipants.forEach(((t,e)=>{this.handleParticipantDisconnected(e,t)})),this.emit(Rs.Moved,t.room.name),this.handleParticipantUpdates(t.participant?[t.participant,...t.otherParticipants]:t.otherParticipants)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return wo.getInstance().getDevices(t,e)}prepareConnection(t,e){return hn(this,void 0,void 0,(function*(){if(this.state===Na.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(Rr(new URL(t))&&e){this.regionUrlProvider=new ra(t,e);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Na.Disconnected&&(this.regionUrl=i,yield fetch(Hr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Hr(t),{method:"HEAD"})}catch(t){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:t}))}}}))}getParticipantByIdentity(t){return this.localParticipant.identity===t?this.localParticipant:this.remoteParticipants.get(t)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(t,e){return hn(this,void 0,void 0,(function*(){let i,n=()=>hn(this,void 0,void 0,(function*(){}));switch(t){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Ui({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Ui({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Ui({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Ui({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=()=>hn(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ui({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>hn(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ui({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 Ui({scenario:{case:"switchCandidateProtocol",value:"force-tls"===t?2:1}}),n=()=>hn(this,void 0,void 0,(function*(){const t=this.engine.client.onLeave;t&&t(new mi({reason:ne.CLIENT_INITIATED,action:pi.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===e||"number"!=typeof e)throw Error("subscriber-bandwidth requires a number as argument");i=new Ui({scenario:{case:"subscriberBandwidth",value:Zr(e)}});break;case"leave-full-reconnect":i=new Ui({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(t){return this.localParticipant.activeDeviceMap.get(t)}switchActiveDevice(t,e){return hn(this,arguments,void 0,(function(t,e){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,o,a,c,d,h;let l=!0,u=!1;const f=n?{exact:e}:e;if("audioinput"===t){u=0===i.localParticipant.audioTrackPublications.size;const e=null!==(s=i.getActiveDevice(t))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=f;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((t=>t.source===mr.Source.Microphone));try{l=(yield Promise.all(n.map((t=>{var e;return null===(e=t.audioTrack)||void 0===e?void 0:e.setDeviceId(f)})))).every((t=>!0===t))}catch(t){throw i.options.audioCaptureDefaults.deviceId=e,t}const r=n.some((t=>{var e,i;return null!==(i=null===(e=t.track)||void 0===e?void 0:e.isMuted)&&void 0!==i&&i}));l&&r&&(u=!0)}else if("videoinput"===t){u=0===i.localParticipant.videoTrackPublications.size;const e=null!==(r=i.getActiveDevice(t))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=f;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((t=>t.source===mr.Source.Camera));try{l=(yield Promise.all(n.map((t=>{var e;return null===(e=t.videoTrack)||void 0===e?void 0:e.setDeviceId(f)})))).every((t=>!0===t))}catch(t){throw i.options.videoCaptureDefaults.deviceId=e,t}const s=n.some((t=>{var e,i;return null!==(i=null===(e=t.track)||void 0===e?void 0:e.isMuted)&&void 0!==i&&i}));l&&s&&(u=!0)}else if("audiooutput"===t){if(u=!0,!Sr()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(e=null!==(o=yield wo.getInstance().normalizeDeviceId("audiooutput",e))&&void 0!==o?o:""),null!==(a=(h=i.options).audioOutput)&&void 0!==a||(h.audioOutput={});const n=null!==(c=i.getActiveDevice(t))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=e;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(e)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((t=>t.setAudioOutput({deviceId:e}))))}catch(t){throw i.options.audioOutput.deviceId=n,t}}return u&&(i.localParticipant.activeDeviceMap.set(t,e),i.emit(Rs.ActiveDeviceChanged,t,e)),l}()}))}setupLocalParticipantEvents(){this.localParticipant.on(js.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(js.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(js.AttributesChanged,this.onLocalAttributesChanged).on(js.TrackMuted,this.onLocalTrackMuted).on(js.TrackUnmuted,this.onLocalTrackUnmuted).on(js.LocalTrackPublished,this.onLocalTrackPublished).on(js.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(js.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(js.MediaDevicesError,this.onMediaDevicesError).on(js.AudioStreamAcquired,this.startAudio).on(js.ChatMessage,this.onLocalChatMessageSent).on(js.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var t;null===(t=this.engine)||void 0===t||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,e,i){if(this.state===Na.Connecting||this.state===Na.Reconnecting){const n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:t.id,mediaStreamId:e.id,tracksInStream:e.getTracks().map((t=>t.id))}),this.onTrackAdded(t,e,i),s()},s=()=>{this.off(Rs.Reconnected,n),this.off(Rs.Connected,n),this.off(Rs.Disconnected,s)};return this.once(Rs.Reconnected,n),this.once(Rs.Connected,n),void this.once(Rs.Disconnected,s)}if(this.state===Na.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===t.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(t){const e=t.split("|");return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}(e.id),s=n[0];let r=n[1],o=t.id;if(r&&r.startsWith("TR")&&(o=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find((t=>t.sid===s));if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);if(!o.startsWith("TR")){const t=this.engine.getTrackIdForReceiver(i);if(!t)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(s),this.logContext);o=t}let c;o.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(s,", streamId: ").concat(r,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:s,streamId:r,trackId:o})),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=a.addSubscribedMediaTrack(t,o,e,i,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit(Rs.EncryptionError,Error("Encrypted ".concat(d.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],e=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.state!==Na.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach((t=>{t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid)}))})),this.localParticipant.trackPublications.forEach((e=>{var i,n,s;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop()):null===(s=e.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(js.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(js.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(js.AttributesChanged,this.onLocalAttributesChanged).off(js.TrackMuted,this.onLocalTrackMuted).off(js.TrackUnmuted,this.onLocalTrackUnmuted).off(js.LocalTrackPublished,this.onLocalTrackPublished).off(js.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(js.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(js.MediaDevicesError,this.onMediaDevicesError).off(js.AudioStreamAcquired,this.startAudio).off(js.ChatMessage,this.onLocalChatMessageSent).off(js.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),_r()&&(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(Na.Disconnected),this.emit(Rs.Disconnected,e)}}}handleParticipantDisconnected(t,e){var i;this.remoteParticipants.delete(t),e&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(t),e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid,!0)})),this.emit(Rs.ParticipantDisconnected,e),e.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(e.identity))}handleIncomingRpcRequest(t,e,i,n,s,r){return hn(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(t,e),1!==r)return void(yield this.engine.publishRpcResponse(t,e,null,oa.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(t,e,null,oa.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:e,callerIdentity:t,payload:n,responseTimeout:s});aa(r)>15360?(a=oa.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=r}catch(t){t instanceof oa?a=t:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),t),a=oa.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(t,e,c,a)}))}selectDefaultDevices(){return hn(this,void 0,void 0,(function*(){var t,e,i;const n=wo.getInstance().previousDevices,s=yield wo.getInstance().getDevices(void 0,!1),r=Ss();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let t of s){const e=n.find((e=>e.deviceId===t.deviceId));e&&""!==e.label&&e.kind===t.kind&&e.label!==t.label&&"default"===this.getActiveDevice(t.kind)&&this.emit(Rs.ActiveDeviceChanged,t.kind,t.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let r of o){const o=or(r),a=this.localParticipant.getTrackPublication(o);if(a&&(null===(t=a.track)||void 0===t?void 0:t.isUserProvided))continue;const c=s.filter((t=>t.kind===r)),d=this.getActiveDevice(r);d===(null===(e=n.filter((t=>t.kind===r))[0])||void 0===e?void 0:e.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(r,c[0].deviceId):"audioinput"===r&&!Ar()||"videoinput"===r||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(r)))||"audiooutput"===r&&Ar()||(yield this.switchActiveDevice(r,c[0].deviceId))}}))}acquireAudioContext(){return hn(this,void 0,void 0,(function*(){var t,e;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!==(t=rr())&&void 0!==t?t:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((t=>t.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),yr(200)])}catch(t){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:t}))}const i="running"===(null===(e=this.audioContext)||void 0===e?void 0:e.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Rs.AudioPlaybackStatusChanged,i))}))}createParticipant(t,e){var i;let n;return n=e?oc.fromParticipantInfo(this.engine.client,e,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new oc(this.engine.client,"",t,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((t=>this.log.warn("Could not set audio output: ".concat(t.message),this.logContext))),n}getOrCreateParticipant(t,e){if(this.remoteParticipants.has(t)){const i=this.remoteParticipants.get(t);return e&&i.updateInfo(e)&&this.sidToIdentity.set(e.sid,e.identity),i}const i=this.createParticipant(t,e);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(e.sid,e.identity),this.emitWhenConnected(Rs.ParticipantConnected,i),i.on(js.TrackPublished,(t=>{this.emitWhenConnected(Rs.TrackPublished,t,i)})).on(js.TrackSubscribed,((t,e)=>{t.kind===mr.Kind.Audio?(t.on(Ds.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(Ds.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===mr.Kind.Video&&(t.on(Ds.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(Ds.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Rs.TrackSubscribed,t,e,i)})).on(js.TrackUnpublished,(t=>{this.emit(Rs.TrackUnpublished,t,i)})).on(js.TrackUnsubscribed,((t,e)=>{this.emit(Rs.TrackUnsubscribed,t,e,i)})).on(js.TrackMuted,(t=>{this.emitWhenConnected(Rs.TrackMuted,t,i)})).on(js.TrackUnmuted,(t=>{this.emitWhenConnected(Rs.TrackUnmuted,t,i)})).on(js.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(Rs.ParticipantMetadataChanged,t,i)})).on(js.ParticipantNameChanged,(t=>{this.emitWhenConnected(Rs.ParticipantNameChanged,t,i)})).on(js.AttributesChanged,(t=>{this.emitWhenConnected(Rs.ParticipantAttributesChanged,t,i)})).on(js.ConnectionQualityChanged,(t=>{this.emitWhenConnected(Rs.ConnectionQualityChanged,t,i)})).on(js.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(Rs.ParticipantPermissionsChanged,t,i)})).on(js.TrackSubscriptionStatusChanged,((t,e)=>{this.emitWhenConnected(Rs.TrackSubscriptionStatusChanged,t,e,i)})).on(js.TrackSubscriptionFailed,((t,e)=>{this.emit(Rs.TrackSubscriptionFailed,t,i,e)})).on(js.TrackSubscriptionPermissionChanged,((t,e)=>{this.emitWhenConnected(Rs.TrackSubscriptionPermissionChanged,t,e,i)})).on(js.Active,(()=>{this.emitWhenConnected(Rs.ParticipantActive,i),i.kind===ue.AGENT&&this.localParticipant.setActiveAgent(i)})),e&&i.updateInfo(e),i}sendSyncState(){const t=Array.from(this.remoteParticipants.values()).reduce(((t,e)=>(t.push(...e.getTrackPublications()),t)),[]),e=this.localParticipant.getTrackPublications();this.engine.sendSyncState(t,e)}updateSubscriptions(){for(const t of this.remoteParticipants.values())for(const e of t.videoTrackPublications.values())e.isSubscribed&&so(e)&&e.emitTrackUpdate()}getRemoteParticipantBySid(t){const e=this.sidToIdentity.get(t);if(e)return this.remoteParticipants.get(e)}registerConnectionReconcile(){this.clearConnectionReconcile();let t=0;this.connectionReconcileInterval=Ws.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?t=0:(t++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:t,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),t>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ne.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ws.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(Rs.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((t=>{let[e,i]=t;this.emit(e,...i)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var e=arguments.length,i=Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];if(this.state===Na.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===Na.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){return hn(this,void 0,void 0,(function*(){var e,i,n,s;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new ae({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:U.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new he({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Rs.SignalConnected),this.emit(Rs.Connected),this.setAndEmitConnectionState(Na.Connected),r.video){const t=new ec(mr.Kind.Video,new pe({source:Xt.CAMERA,sid:""+Math.floor(1e4*Math.random()),type:$t.AUDIO,name:"video-dummy"}),new Aa(r.useRealTracks&&(null===(e=window.navigator.mediaDevices)||void 0===e?void 0:e.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:zr(160*(null!==(i=o.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(t),this.localParticipant.emit(js.LocalTrackPublished,t)}if(r.audio){const t=new ec(mr.Kind.Audio,new pe({source:Xt.MICROPHONE,sid:""+Math.floor(1e4*Math.random()),type:$t.AUDIO}),new ma(r.useRealTracks&&(null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Wr(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(js.LocalTrackPublished,t)}for(let t=0;t<o.count-1;t+=1){let e=new he({sid:""+Math.floor(1e4*Math.random()),identity:"simulated-".concat(t),state:le.ACTIVE,tracks:[],joinedAt:U.parse(Date.now())});const i=this.getOrCreateParticipant(e.identity,e);if(o.video){const n=zr(160*(null!==(s=o.aspectRatios[t%o.aspectRatios.length])&&void 0!==s?s:1),160,!1,!0),r=new pe({source:Xt.CAMERA,sid:""+Math.floor(1e4*Math.random()),type:$t.AUDIO});i.addSubscribedMediaTrack(n,r.sid,new MediaStream([n]),new RTCRtpReceiver),e.tracks=[...e.tracks,r]}if(o.audio){const t=Wr(),n=new pe({source:Xt.MICROPHONE,sid:""+Math.floor(1e4*Math.random()),type:$t.AUDIO});i.addSubscribedMediaTrack(t,n.sid,new MediaStream([t]),new RTCRtpReceiver),e.tracks=[...e.tracks,n]}i.updateInfo(e)}}))}emit(t){for(var e=arguments.length,i=Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];if(t!==Rs.ActiveSpeakersChanged&&t!==Rs.TranscriptionReceived){const e=cc(i).filter((t=>void 0!==t));t!==Rs.TrackSubscribed&&t!==Rs.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:e})),this.log.debug("room event ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:e}))}return super.emit(t,...i)}}function cc(t){return t.map((t=>{if(t)return Array.isArray(t)?cc(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t}))}function dc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return t+""}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}ac.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((t=>{t()})),function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"}(Ua||(Ua={})),new TextEncoder,new TextDecoder;class hc extends Error{constructor(t,e){var i;super(t,e),dc(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}function lc(){return lc=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)({}).hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},lc.apply(null,arguments)}dc(hc,"code","ERR_JOSE_GENERIC"),dc(class extends hc{constructor(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(t,{cause:{claim:i,reason:n,payload:e}}),dc(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),dc(this,"claim",void 0),dc(this,"reason",void 0),dc(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=e}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),dc(class extends hc{constructor(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(t,{cause:{claim:i,reason:n,payload:e}}),dc(this,"code","ERR_JWT_EXPIRED"),dc(this,"claim",void 0),dc(this,"reason",void 0),dc(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=e}},"code","ERR_JWT_EXPIRED"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED"),dc(class extends hc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),dc(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID"),dc(class extends hc{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),dc(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY"),dc(class extends hc{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),dc(this,Symbol.asyncIterator,void 0),dc(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS"),dc(class extends hc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),dc(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT"),dc(class extends hc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),dc(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const uc=new Uint8Array(0);class fc{static getFullOptions(t){return lc({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},t)}constructor(t,e){var i=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(t){"connected"!==i.status&&"connecting"!==i.status||(i.updateStatus("disconnecting"),await i.handleEndSession(),i.updateStatus("disconnected"),i.options.onDisconnect&&i.options.onDisconnect(t))},this.onMessage=async function(t){switch(t.type){case"interruption":return void i.handleInterruption(t);case"agent_response":return void i.handleAgentResponse(t);case"user_transcript":return void i.handleUserTranscript(t);case"internal_tentative_agent_response":return void i.handleTentativeAgentResponse(t);case"client_tool_call":try{await i.handleClientToolCall(t)}catch(e){i.onError("Unexpected error in client tool call handling: "+(e instanceof Error?e.message:e+""),{clientToolName:t.client_tool_call.tool_name,toolCallId:t.client_tool_call.tool_call_id})}return;case"audio":return void i.handleAudio(t);case"vad_score":return void i.handleVadScore(t);case"ping":return void i.connection.sendMessage({type:"pong",event_id:t.ping_event.event_id});case"mcp_tool_call":return void i.handleMCPToolCall(t);case"mcp_connection_status":return void i.handleMCPConnectionStatus(t);case"agent_tool_request":return void i.handleAgentToolRequest(t);case"agent_tool_response":return void i.handleAgentToolResponse(t);case"conversation_initiation_metadata":return void i.handleConversationMetadata(t);case"asr_initiation_metadata":return void i.handleAsrInitiationMetadata(t);case"agent_chat_response_part":return void i.handleAgentChatResponsePart(t);case"error":return void i.handleErrorEvent(t);default:return void(i.options.onDebug&&i.options.onDebug(t))}},this.setVolume=({volume:t})=>{this.volume=t},this.options=t,this.connection=e,this.options.onConnect&&this.options.onConnect({conversationId:e.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange((t=>this.updateMode(t))),this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}async handleEndSession(){this.connection.close()}updateMode(t){t!==this.mode&&(this.mode=t,this.options.onModeChange&&this.options.onModeChange({mode:t}))}updateStatus(t){t!==this.status&&(this.status=t,this.options.onStatusChange&&this.options.onStatusChange({status:t}))}updateCanSendFeedback(){const t=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==t&&(this.canSendFeedback=t,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:t}))}handleInterruption(t){t.interruption_event&&(this.lastInterruptTimestamp=t.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:t.interruption_event.event_id}))}handleAgentResponse(t){this.options.onMessage&&this.options.onMessage({source:"ai",role:"agent",message:t.agent_response_event.agent_response})}handleUserTranscript(t){this.options.onMessage&&this.options.onMessage({source:"user",role:"user",message:t.user_transcription_event.user_transcript})}handleTentativeAgentResponse(t){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:t.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(t){this.options.onVadScore&&this.options.onVadScore({vadScore:t.vad_score_event.vad_score})}async handleClientToolCall(t){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,t.client_tool_call.tool_name))try{var e;const i=null!=(e=await this.options.clientTools[t.client_tool_call.tool_name](t.client_tool_call.parameters))?e:"Client tool execution successful.",n="object"==typeof i?JSON.stringify(i):i+"";this.connection.sendMessage({type:"client_tool_result",tool_call_id:t.client_tool_call.tool_call_id,result:n,is_error:!1})}catch(e){this.onError("Client tool execution failed with following error: "+(null==e?void 0:e.message),{clientToolName:t.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:t.client_tool_call.tool_call_id,result:"Client tool execution failed: "+(null==e?void 0:e.message),is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(t.client_tool_call);this.onError(`Client tool with name ${t.client_tool_call.tool_name} is not defined on client`,{clientToolName:t.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:t.client_tool_call.tool_call_id,result:`Client tool with name ${t.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(t){}handleMCPToolCall(t){this.options.onMCPToolCall&&this.options.onMCPToolCall(t.mcp_tool_call)}handleMCPConnectionStatus(t){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(t.mcp_connection_status)}handleAgentToolRequest(t){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(t.agent_tool_request)}handleAgentToolResponse(t){"end_call"===t.agent_tool_response.tool_name&&this.endSessionWithDetails({reason:"agent",context:new CloseEvent("end_call",{reason:"Agent ended the call"})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(t.agent_tool_response)}handleConversationMetadata(t){this.options.onConversationMetadata&&this.options.onConversationMetadata(t.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(t){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(t.asr_initiation_metadata_event)}handleAgentChatResponsePart(t){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(t.text_response_part)}handleErrorEvent(t){const e=t.error_event.error_type,i=t.error_event.message||t.error_event.reason||"Unknown error";"max_duration_exceeded"!==e?this.onError("Server error: "+i,{errorType:e,code:t.error_event.code,debugMessage:t.error_event.debug_message,details:t.error_event.details}):this.endSessionWithDetails({reason:"error",message:i,context:new Event("max_duration_exceeded")})}onError(t,e){console.error(t,e),this.options.onError&&this.options.onError(t,e)}getId(){return this.connection.conversationId}isOpen(){return"connected"===this.status}setMicMuted(t){this.connection.setMicMuted(t)}getInputByteFrequencyData(){return uc}getOutputByteFrequencyData(){return uc}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(t){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:t?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(0===this.lastFeedbackEventId?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")}sendContextualUpdate(t){this.connection.sendMessage({type:"contextual_update",text:t})}sendUserMessage(t){this.connection.sendMessage({type:"user_message",text:t})}sendUserActivity(){this.connection.sendMessage({type:"user_activity"})}sendMCPToolApprovalResult(t,e){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:t,is_approved:e})}}class vc{constructor(t={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=t.onDebug}debug(t){this.onDebug&&this.onDebug(t)}onMessage(t){this.onMessageCallback=t;const e=this.queue;this.queue=[],e.length>0&&queueMicrotask((()=>{e.forEach(t)}))}onDisconnect(t){this.onDisconnectCallback=t;const e=this.disconnectionDetails;e&&queueMicrotask((()=>{t(e)}))}onModeChange(t){this.onModeChangeCallback=t}updateMode(t){var e;null==(e=this.onModeChangeCallback)||e.call(this,t)}disconnect(t){var e;this.disconnectionDetails||(this.disconnectionDetails=t,null==(e=this.onDisconnectCallback)||e.call(this,t))}handleMessage(t){this.onMessageCallback?this.onMessageCallback(t):this.queue.push(t)}}function mc(t){const[e,i]=t.split("_");if(!["pcm","ulaw"].includes(e))throw Error("Invalid format: "+t);const n=Number.parseInt(i);if(Number.isNaN(n))throw Error("Invalid sample rate: "+i);return{format:e,sampleRate:n}}const pc="0.13.0";function gc(t){return!!t.type}const bc="conversation_initiation_client_data";function yc(t){var e;const i={type:bc};var n,s,r,o,a,c,d,h;return t.overrides&&(i.conversation_config_override={agent:{prompt:null==(n=t.overrides.agent)?void 0:n.prompt,first_message:null==(s=t.overrides.agent)?void 0:s.firstMessage,language:null==(r=t.overrides.agent)?void 0:r.language},tts:{voice_id:null==(o=t.overrides.tts)?void 0:o.voiceId,speed:null==(a=t.overrides.tts)?void 0:a.speed,stability:null==(c=t.overrides.tts)?void 0:c.stability,similarity_boost:null==(d=t.overrides.tts)?void 0:d.similarityBoost},conversation:{text_only:null==(h=t.overrides.conversation)?void 0:h.textOnly}}),t.customLlmExtraBody&&(i.custom_llm_extra_body=t.customLlmExtraBody),t.dynamicVariables&&(i.dynamic_variables=t.dynamicVariables),t.userId&&(i.user_id=t.userId),null!=(e=t.overrides)&&e.client&&(i.source_info={source:t.overrides.client.source,version:t.overrides.client.version}),i}class wc extends Error{constructor(t,e){super(t),this.closeCode=void 0,this.closeReason=void 0,this.name="SessionConnectionError",this.closeCode=null==e?void 0:e.closeCode,this.closeReason=null==e?void 0:e.closeReason}}class kc extends vc{constructor(t,e,i,n){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=t,this.conversationId=e,this.inputFormat=i,this.outputFormat=n,this.socket.addEventListener("error",(t=>{setTimeout((()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:t})),0)})),this.socket.addEventListener("close",(t=>{this.disconnect(1e3===t.code?{reason:"agent",context:t,closeCode:t.code,closeReason:t.reason||void 0}:{reason:"error",message:t.reason||"The connection was closed by the server.",context:t,closeCode:t.code,closeReason:t.reason||void 0})})),this.socket.addEventListener("message",(t=>{try{const e=JSON.parse(t.data);if(!gc(e))return void this.debug({type:"invalid_event",message:"Received invalid socket event",data:t.data});this.handleMessage(e)}catch(e){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:e instanceof Error?e.message:e+"",data:t.data})}}))}static async create(t){let e=null;try{var i,n,s;const r=null!=(i=t.origin)?i:"wss://api.elevenlabs.io";let o;const a=(null==(n=t.overrides)||null==(n=n.client)?void 0:n.version)||pc,c=(null==(s=t.overrides)||null==(s=s.client)?void 0:s.source)||"js_sdk";if(t.signedUrl){const e=t.signedUrl.includes("?")?"&":"?";o=`${t.signedUrl}${e}source=${c}&version=${a}`}else o=`${r}/v1/convai/conversation?agent_id=${t.agentId}&source=${c}&version=${a}`;const d=["convai"];t.authorization&&d.push("bearer."+t.authorization),e=new WebSocket(o,d);const h=await new Promise(((i,n)=>{e.addEventListener("open",(()=>{var i;const n=yc(t);null==(i=e)||i.send(JSON.stringify(n))}),{once:!0}),e.addEventListener("error",(()=>{setTimeout((()=>n(new wc("The connection was closed due to a socket error."))),0)})),e.addEventListener("close",(t=>{n(new wc(t.reason||(1e3===t.code?"Connection closed normally before session could be established.":"Connection closed unexpectedly before session could be established."),{closeCode:t.code,closeReason:t.reason||void 0}))})),e.addEventListener("message",(t=>{const e=JSON.parse(t.data);gc(e)&&("conversation_initiation_metadata"===e.type?i(e.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))}),{once:!0})})),{conversation_id:l,agent_output_audio_format:u,user_input_audio_format:f}=h,v=mc(null!=f?f:"pcm_16000"),m=mc(u);return new kc(e,l,v,m)}catch(t){var r;throw null==(r=e)||r.close(),t}}close(){this.socket.close(1e3,"User ended conversation")}sendMessage(t){this.socket.send(JSON.stringify(t))}async setMicMuted(t){console.warn(`WebSocket connection setMicMuted called with ${t}, but this is handled by VoiceConversation`)}}function Tc(t){const e=new Uint8Array(t);return window.btoa(String.fromCharCode(...e))}function Sc(t){const e=window.atob(t),i=e.length,n=new Uint8Array(i);for(let t=0;t<i;t++)n[t]=e.charCodeAt(t);return n.buffer}const Ec=new Map;function Oc(t,e){return async(i,n)=>{const s=Ec.get(t);if(s)return i.addModule(s);if(n)try{return await i.addModule(n),void Ec.set(t,n)}catch(e){throw Error(`Failed to load the ${t} worklet module from path: ${n}. Error: ${e}`)}const r=new Blob([e],{type:"application/javascript"}),o=URL.createObjectURL(r);try{return await i.addModule(o),void Ec.set(t,o)}catch(t){URL.revokeObjectURL(o)}try{const n="data:application/javascript;base64,"+btoa(e);await i.addModule(n),Ec.set(t,n)}catch(e){throw Error(`Failed to load the ${t} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}const xc=Oc("rawAudioProcessor",'/*\n * ulaw encoding logic taken from the wavefile library\n * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js\n * USED BY @elevenlabs/client\n */\n\nconst BIAS = 0x84;\nconst CLIP = 32635;\nconst encodeTable = [\n 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,\n 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,\n 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,\n 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7\n];\n\nfunction encodeSample(sample) {\n let sign;\n let exponent;\n let mantissa;\n let muLawSample;\n sign = (sample >> 8) & 0x80;\n if (sign !== 0) sample = -sample;\n sample = sample + BIAS;\n if (sample > CLIP) sample = CLIP;\n exponent = encodeTable[(sample>>7) & 0xFF];\n mantissa = (sample >> (exponent+3)) & 0x0F;\n muLawSample = ~(sign | (exponent << 4) | mantissa);\n \n return muLawSample;\n}\n\nclass RawAudioProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n \n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.isMuted = false;\n this.buffer = []; // Initialize an empty buffer\n this.bufferSize = data.sampleRate / 4;\n this.format = data.format;\n\n if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) {\n globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => {\n this.resampler = resampler;\n });\n }\n break;\n case "setMuted":\n this.isMuted = data.isMuted;\n break;\n }\n };\n }\n process(inputs) {\n if (!this.buffer) {\n return true;\n }\n \n const input = inputs[0]; // Get the first input node\n if (input.length > 0) {\n let channelData = input[0]; // Get the first channel\'s data\n\n // Resample the audio if necessary\n if (this.resampler) {\n channelData = this.resampler.full(channelData);\n }\n\n // Add channel data to the buffer\n this.buffer.push(...channelData);\n // Get max volume \n let sum = 0.0;\n for (let i = 0; i < channelData.length; i++) {\n sum += channelData[i] * channelData[i];\n }\n const maxVolume = Math.sqrt(sum / channelData.length);\n // Check if buffer size has reached or exceeded the threshold\n if (this.buffer.length >= this.bufferSize) {\n const float32Array = this.isMuted \n ? new Float32Array(this.buffer.length)\n : new Float32Array(this.buffer);\n\n let encodedArray = this.format === "ulaw"\n ? new Uint8Array(float32Array.length)\n : new Int16Array(float32Array.length);\n\n // Iterate through the Float32Array and convert each sample to PCM16\n for (let i = 0; i < float32Array.length; i++) {\n // Clamp the value to the range [-1, 1]\n let sample = Math.max(-1, Math.min(1, float32Array[i]));\n\n // Scale the sample to the range [-32768, 32767]\n let value = sample < 0 ? sample * 32768 : sample * 32767;\n if (this.format === "ulaw") {\n value = encodeSample(Math.round(value));\n }\n\n encodedArray[i] = value;\n }\n\n // Send the buffered data to the main script\n this.port.postMessage([encodedArray, maxVolume]);\n\n // Clear the buffer after sending\n this.buffer = [];\n }\n }\n return true; // Continue processing\n }\n}\nregisterProcessor("rawAudioProcessor", RawAudioProcessor);\n');class Ac extends vc{constructor(t,e,i,n,s={}){super(s),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=t,this.conversationId=e,this.inputFormat=i,this.outputFormat=n,this.setupRoomEventListeners()}static async create(t){let e;if("conversationToken"in t&&t.conversationToken)e=t.conversationToken;else{if(!("agentId"in t)||!t.agentId)throw Error("Either conversationToken or agentId is required for WebRTC connection");try{var i,n,s;const o=(null==(i=t.overrides)||null==(i=i.client)?void 0:i.version)||pc,a=(null==(n=t.overrides)||null==(n=n.client)?void 0:n.source)||"js_sdk",c=`${r=null!=(s=t.origin)?s:"https://api.elevenlabs.io",r.replace(/^wss:\/\//,"https://")}/v1/convai/conversation/token?agent_id=${t.agentId}&source=${a}&version=${o}`,d=await fetch(c);if(!d.ok)throw Error(`ElevenLabs API returned ${d.status} ${d.statusText}`);if(e=(await d.json()).token,!e)throw Error("No conversation token received from API")}catch(e){let i=e instanceof Error?e.message:e+"";throw e instanceof Error&&e.message.includes("401")&&(i="Your agent has authentication enabled, but no signed URL or conversation token was provided."),Error(`Failed to fetch conversation token for agent ${t.agentId}: ${i}`)}}var r;const o=new ac;try{const i="room_"+Date.now(),n=mc("pcm_48000"),s=mc("pcm_48000"),r=new Ac(o,i,n,s,t),c=t.livekitUrl||"wss://livekit.rtc.elevenlabs.io";var a;await o.connect(c,e),await new Promise((t=>{if(r.isConnected)t();else{const e=()=>{o.off(Rs.Connected,e),t()};o.on(Rs.Connected,e)}})),o.name&&(r.conversationId=(null==(a=o.name.match(/(conv_[a-zA-Z0-9]+)/))?void 0:a[0])||o.name),t.textOnly||await o.localParticipant.setMicrophoneEnabled(!0);const d=yc(t);return r.debug({type:bc,message:d}),await r.sendMessage(d),r}catch(t){throw await o.disconnect(),t}}setupRoomEventListeners(){var t=this;this.room.on(Rs.Connected,(async function(){t.isConnected=!0,console.info("WebRTC room connected")})),this.room.on(Rs.Disconnected,(t=>{this.isConnected=!1,this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:null==t?void 0:""+t})})})),this.room.on(Rs.ConnectionStateChanged,(t=>{t===Na.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:"LiveKit connection state changed to "+t,context:new Event("connection_state_changed")}))})),this.room.on(Rs.DataReceived,((t,e)=>{try{const e=JSON.parse((new TextDecoder).decode(t));if("audio"===e.type)return;gc(e)?this.handleMessage(e):console.warn("Invalid socket event received:",e)}catch(e){console.warn("Failed to parse incoming data message:",e),console.warn("Raw payload:",(new TextDecoder).decode(t))}})),this.room.on(Rs.TrackSubscribed,(async function(e,i,n){if(e.kind===mr.Kind.Audio&&n.identity.includes("agent")){const i=e,n=i.attach();if(n.autoplay=!0,n.controls=!1,t.outputDeviceId&&n.setSinkId)try{await n.setSinkId(t.outputDeviceId)}catch(t){console.warn("Failed to set output device for new audio element:",t)}n.style.display="none",document.body.appendChild(n),t.audioElements.push(n),1===t.audioElements.length&&(null==t.onDebug||t.onDebug({type:"audio_element_ready"})),await t.setupAudioCapture(i)}})),this.room.on(Rs.ActiveSpeakersChanged,(async function(e){t.updateMode(e.length>0&&e[0].identity.startsWith("agent")?"speaking":"listening")})),this.room.on(Rs.ParticipantDisconnected,(t=>{var e;null!=(e=t.identity)&&e.startsWith("agent")&&this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:"agent disconnected"})})}))}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach((t=>{t.track&&t.track.stop()}))}catch(t){console.warn("Error stopping local tracks:",t)}this.audioCaptureContext&&(this.audioCaptureContext.close().catch((t=>{console.warn("Error closing audio capture context:",t)})),this.audioCaptureContext=null),this.audioElements.forEach((t=>{t.parentNode&&t.parentNode.removeChild(t)})),this.audioElements=[],this.room.disconnect()}}async sendMessage(t){if(this.isConnected&&this.room.localParticipant){if(!("user_audio_chunk"in t))try{const e=(new TextEncoder).encode(JSON.stringify(t));await this.room.localParticipant.publishData(e,{reliable:!0})}catch(e){this.debug({type:"send_message_error",message:{message:t,error:e}}),console.error("Failed to send message via WebRTC:",e)}}else console.warn("Cannot send message: room not connected or no local participant")}getRoom(){return this.room}async setMicMuted(t){if(!this.isConnected||!this.room.localParticipant)return void console.warn("Cannot set microphone muted: room not connected or no local participant");const e=this.room.localParticipant.getTrackPublication(mr.Source.Microphone);if(null!=e&&e.track)try{t?await e.track.mute():await e.track.unmute()}catch(e){await this.room.localParticipant.setMicrophoneEnabled(!t)}else await this.room.localParticipant.setMicrophoneEnabled(!t)}async setupAudioCapture(t){try{const e=new AudioContext;this.audioCaptureContext=e,this.outputAnalyser=e.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;const i=new MediaStream([t.mediaStreamTrack]),n=e.createMediaStreamSource(i);n.connect(this.outputAnalyser),await xc(e.audioWorklet);const s=new AudioWorkletNode(e,"rawAudioProcessor");this.outputAnalyser.connect(s),s.port.postMessage({type:"setFormat",format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),s.port.onmessage=t=>{const[e,i]=t.data;if(i>.01){const t=Tc(e.buffer),i=this.audioEventId++;this.handleMessage({type:"audio",audio_event:{audio_base_64:t,event_id:i}})}},n.connect(s)}catch(t){console.warn("Failed to set up audio capture:",t)}}setAudioVolume(t){this.audioElements.forEach((e=>{e.volume=t}))}async setAudioOutputDevice(t){if(!("setSinkId"in HTMLAudioElement.prototype))throw Error("setSinkId is not supported in this browser");const e=this.audioElements.map((async function(e){try{await e.setSinkId(t)}catch(t){throw console.error("Failed to set sink ID for audio element:",t),t}}));await Promise.all(e),this.outputDeviceId=t}async setAudioInputDevice(t){if(!this.isConnected||!this.room.localParticipant)throw Error("Cannot change input device: room not connected or no local participant");try{const e=this.room.localParticipant.getTrackPublication(mr.Source.Microphone);null!=e&&e.track&&(await e.track.stop(),await this.room.localParticipant.unpublishTrack(e.track));const i={deviceId:{exact:t},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},n=await function(t){return hn(this,void 0,void 0,(function*(){return(yield ic({audio:null==t||t,video:!1}))[0]}))}(i);await this.room.localParticipant.publishTrack(n,{name:"microphone",source:mr.Source.Microphone})}catch(t){console.error("Failed to change input device:",t);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(t){console.error("Failed to recover microphone after device switch error:",t)}throw t}}getOutputByteFrequencyData(){return this.outputAnalyser?(null!=this.outputFrequencyData||(this.outputFrequencyData=new Uint8Array(this.outputAnalyser.frequencyBinCount)),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}}async function Cc(t){const e=function(t){return t.connectionType?t.connectionType:"conversationToken"in t&&t.conversationToken?"webrtc":"websocket"}(t);switch(e){case"websocket":return kc.create(t);case"webrtc":return Ac.create(t);default:throw Error("Unknown connection type: "+e)}}function _c(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}async function Ic(t={default:0,android:3e3}){let e=t.default;var i;if(/android/i.test(navigator.userAgent))e=null!=(i=t.android)?i:e;else if(_c()){var n;e=null!=(n=t.ios)?n:e}e>0&&await new Promise((t=>setTimeout(t,e)))}class Rc extends fc{static async startSession(t){const e=fc.getFullOptions(t);e.onStatusChange&&e.onStatusChange({status:"connecting"}),e.onCanSendFeedbackChange&&e.onCanSendFeedbackChange({canSendFeedback:!1}),e.onModeChange&&e.onModeChange({mode:"listening"}),e.onCanSendFeedbackChange&&e.onCanSendFeedbackChange({canSendFeedback:!1});let i=null;try{return await Ic(e.connectionDelay),i=await Cc(t),new Rc(e,i)}catch(t){var n;throw e.onStatusChange&&e.onStatusChange({status:"disconnected"}),null==(n=i)||n.close(),t}}}const jc={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}};class Pc{static async create({sampleRate:t,format:e,preferHeadphonesForIosDevices:i,inputDeviceId:n,workletPaths:s,libsampleratePath:r}){let o=null,a=null;try{const c=lc({sampleRate:{ideal:t}},jc);if(_c()&&i){const t=(await window.navigator.mediaDevices.enumerateDevices()).find((t=>"audioinput"===t.kind&&["airpod","headphone","earphone"].find((e=>t.label.toLowerCase().includes(e)))));t&&(c.deviceId={ideal:t.deviceId})}n&&(c.deviceId=Pc.getDeviceIdConstraint(n));const d=navigator.mediaDevices.getSupportedConstraints().sampleRate;o=new window.AudioContext(d?{sampleRate:t}:{});const h=o.createAnalyser();if(!d){const t=r||"https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js";await o.audioWorklet.addModule(t)}await xc(o.audioWorklet,null==s?void 0:s.rawAudioProcessor);const l=lc({voiceIsolation:!0},c);a=await navigator.mediaDevices.getUserMedia({audio:l});const u=o.createMediaStreamSource(a),f=new AudioWorkletNode(o,"rawAudioProcessor");return f.port.postMessage({type:"setFormat",format:e,sampleRate:t}),u.connect(h),h.connect(f),await o.resume(),new Pc(o,h,f,a,u)}catch(t){var c,d;throw null==(c=a)||c.getTracks().forEach((t=>{t.stop()})),null==(d=o)||d.close(),t}}static getDeviceIdConstraint(t){if(t)return _c()?{ideal:t}:{exact:t}}constructor(t,e,i,n,s){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=t,this.analyser=e,this.worklet=i,this.inputStream=n,this.mediaStreamSource=s}async close(){this.inputStream.getTracks().forEach((t=>{t.stop()})),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(t){this.worklet.port.postMessage({type:"setMuted",isMuted:t})}async setInputDevice(t){try{const e=lc({},jc);t&&(e.deviceId=Pc.getDeviceIdConstraint(t));const i=lc({voiceIsolation:!0},e),n=await navigator.mediaDevices.getUserMedia({audio:i});this.inputStream.getTracks().forEach((t=>{t.stop()})),this.mediaStreamSource.disconnect(),this.inputStream=n,this.mediaStreamSource=this.context.createMediaStreamSource(n),this.mediaStreamSource.connect(this.analyser)}catch(t){throw console.error("Failed to switch input device:",t),t}}}const Dc=Oc("audioConcatProcessor",'/*\n * ulaw decoding logic taken from the wavefile library\n * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js\n * USED BY @elevenlabs/client\n */\n\nconst decodeTable = [0,132,396,924,1980,4092,8316,16764];\n\nfunction decodeSample(muLawSample) {\n let sign;\n let exponent;\n let mantissa;\n let sample;\n muLawSample = ~muLawSample;\n sign = (muLawSample & 0x80);\n exponent = (muLawSample >> 4) & 0x07;\n mantissa = muLawSample & 0x0F;\n sample = decodeTable[exponent] + (mantissa << (exponent+3));\n if (sign !== 0) sample = -sample;\n\n return sample;\n}\n\nclass AudioConcatProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffers = []; // Initialize an empty buffer\n this.cursor = 0;\n this.currentBuffer = null;\n this.wasInterrupted = false;\n this.finished = false;\n \n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.format = data.format;\n break;\n case "buffer":\n this.wasInterrupted = false;\n this.buffers.push(\n this.format === "ulaw"\n ? new Uint8Array(data.buffer)\n : new Int16Array(data.buffer)\n );\n break;\n case "interrupt":\n this.wasInterrupted = true;\n break;\n case "clearInterrupted":\n if (this.wasInterrupted) {\n this.wasInterrupted = false;\n this.buffers = [];\n this.currentBuffer = null;\n }\n }\n };\n }\n process(_, outputs) {\n let finished = false;\n const output = outputs[0][0];\n for (let i = 0; i < output.length; i++) {\n if (!this.currentBuffer) {\n if (this.buffers.length === 0) {\n finished = true;\n break;\n }\n this.currentBuffer = this.buffers.shift();\n this.cursor = 0;\n }\n\n let value = this.currentBuffer[this.cursor];\n if (this.format === "ulaw") {\n value = decodeSample(value);\n }\n output[i] = value / 32768;\n this.cursor++;\n\n if (this.cursor >= this.currentBuffer.length) {\n this.currentBuffer = null;\n }\n }\n\n if (this.finished !== finished) {\n this.finished = finished;\n this.port.postMessage({ type: "process", finished });\n }\n\n return true; // Continue processing\n }\n}\n\nregisterProcessor("audioConcatProcessor", AudioConcatProcessor);\n');class Mc{static async create({sampleRate:t,format:e,outputDeviceId:i,workletPaths:n}){let s=null,r=null;try{s=new AudioContext({sampleRate:t});const o=s.createAnalyser(),a=s.createGain();r=new Audio,r.src="",r.load(),r.autoplay=!0,r.style.display="none",document.body.appendChild(r);const c=s.createMediaStreamDestination();r.srcObject=c.stream,a.connect(o),o.connect(c),await Dc(s.audioWorklet,null==n?void 0:n.audioConcatProcessor);const d=new AudioWorkletNode(s,"audioConcatProcessor");return d.port.postMessage({type:"setFormat",format:e}),d.connect(a),await s.resume(),i&&r.setSinkId&&await r.setSinkId(i),new Mc(s,o,a,d,r)}catch(t){var o,a;throw null!=(o=r)&&o.parentNode&&r.parentNode.removeChild(r),null==(a=r)||a.pause(),s&&"closed"!==s.state&&await s.close(),t}}constructor(t,e,i,n,s){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=t,this.analyser=e,this.gain=i,this.worklet=n,this.audioElement=s}async setOutputDevice(t){if(!("setSinkId"in HTMLAudioElement.prototype))throw Error("setSinkId is not supported in this browser");await this.audioElement.setSinkId(t||"")}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}}class Nc extends fc{static async requestWakeLock(){if("wakeLock"in navigator)try{return await navigator.wakeLock.request("screen")}catch(t){}return null}static async startSession(t){var e;const i=fc.getFullOptions(t);i.onStatusChange&&i.onStatusChange({status:"connecting"}),i.onCanSendFeedbackChange&&i.onCanSendFeedbackChange({canSendFeedback:!1});let n=null,s=null,r=null,o=null,a=null;(null==(e=t.useWakeLock)||e)&&(a=await Nc.requestWakeLock());try{var c;return o=await navigator.mediaDevices.getUserMedia({audio:!0}),await Ic(i.connectionDelay),s=await Cc(t),[n,r]=await Promise.all([Pc.create(lc({},s.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),Mc.create(lc({},s.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),null==(c=o)||c.getTracks().forEach((t=>{t.stop()})),o=null,new Nc(i,s,n,r,a)}catch(t){var d,h,l,u;i.onStatusChange&&i.onStatusChange({status:"disconnected"}),null==(d=o)||d.getTracks().forEach((t=>{t.stop()})),null==(h=s)||h.close(),await(null==(l=n)?void 0:l.close()),await(null==(u=r)?void 0:u.close());try{var f;await(null==(f=a)?void 0:f.release()),a=null}catch(t){}throw t}}constructor(t,e,i,n,s){super(t,e),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.visibilityChangeHandler=null,this.onInputWorkletMessage=t=>{"connected"===this.status&&this.connection.sendMessage({user_audio_chunk:Tc(t.data[0].buffer)})},this.onOutputWorkletMessage=({data:t})=>{"process"===t.type&&this.updateMode(t.finished?"listening":"speaking")},this.addAudioBase64Chunk=t=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"}),this.output.worklet.port.postMessage({type:"buffer",buffer:Sc(t)})},this.fadeOutAudio=()=>{this.updateMode("listening"),this.output.worklet.port.postMessage({type:"interrupt"}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout((()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"})}),2e3)},this.calculateVolume=t=>{if(0===t.length)return 0;let e=0;for(let i=0;i<t.length;i++)e+=t[i]/255;return e/=t.length,e<0?0:e>1?1:e},this.setVolume=({volume:t})=>{const e=Number.isFinite(t)?Math.min(1,Math.max(0,t)):1;this.volume=e,this.connection instanceof Ac?this.connection.setAudioVolume(e):this.output.gain.gain.value=e},this.input=i,this.output=n,this.wakeLock=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage,s&&(this.visibilityChangeHandler=()=>{var t;"visible"===document.visibilityState&&null!=(t=this.wakeLock)&&t.released&&Nc.requestWakeLock().then((t=>{this.wakeLock=t}))},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}async handleEndSession(){await super.handleEndSession(),this.visibilityChangeHandler&&document.removeEventListener("visibilitychange",this.visibilityChangeHandler);try{var t;await(null==(t=this.wakeLock)?void 0:t.release()),this.wakeLock=null}catch(t){}await this.input.close(),await this.output.close()}handleInterruption(t){super.handleInterruption(t),this.fadeOutAudio()}handleAudio(t){var e,i;super.handleAudio(t),t.audio_event.alignment&&this.options.onAudioAlignment&&this.options.onAudioAlignment(t.audio_event.alignment),this.lastInterruptTimestamp<=t.audio_event.event_id&&(t.audio_event.audio_base_64&&(null==(e=(i=this.options).onAudio)||e.call(i,t.audio_event.audio_base_64),this.connection instanceof Ac||this.addAudioBase64Chunk(t.audio_event.audio_base_64)),this.currentEventId=t.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}setMicMuted(t){this.connection instanceof Ac?this.connection.setMicMuted(t):this.input.setMuted(t)}getInputByteFrequencyData(){return null!=this.inputFrequencyData||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof Ac?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(null!=this.outputFrequencyData||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:t,format:e,preferHeadphonesForIosDevices:i,inputDeviceId:n}){try{if(this.connection instanceof kc)try{return await this.input.setInputDevice(n),this.input}catch(t){console.warn("Failed to change device on existing input, recreating:",t)}this.connection instanceof Ac&&await this.connection.setAudioInputDevice(n||""),await this.input.close();const s=await Pc.create({sampleRate:null!=t?t:this.connection.inputFormat.sampleRate,format:null!=e?e:this.connection.inputFormat.format,preferHeadphonesForIosDevices:i,inputDeviceId:n,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath});return this.input=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(t){throw console.error("Error changing input device",t),t}}async changeOutputDevice({sampleRate:t,format:e,outputDeviceId:i}){try{if(this.connection instanceof kc)try{return await this.output.setOutputDevice(i),this.output}catch(t){console.warn("Failed to change device on existing output, recreating:",t)}this.connection instanceof Ac&&await this.connection.setAudioOutputDevice(i||""),await this.output.close();const n=await Mc.create({sampleRate:null!=t?t:this.connection.outputFormat.sampleRate,format:null!=e?e:this.connection.outputFormat.format,outputDeviceId:i,workletPaths:this.options.workletPaths});return this.output=n,this.output}catch(t){throw console.error("Error changing output device",t),t}}}var Uc,Lc,Bc;!function(t){t.SESSION_STARTED="session_started",t.PARTIAL_TRANSCRIPT="partial_transcript",t.COMMITTED_TRANSCRIPT="committed_transcript",t.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",t.AUTH_ERROR="auth_error",t.ERROR="error",t.OPEN="open",t.CLOSE="close",t.QUOTA_EXCEEDED="quota_exceeded",t.COMMIT_THROTTLED="commit_throttled",t.TRANSCRIBER_ERROR="transcriber_error",t.UNACCEPTED_TERMS="unaccepted_terms",t.RATE_LIMITED="rate_limited",t.INPUT_ERROR="input_error",t.QUEUE_OVERFLOW="queue_overflow",t.RESOURCE_EXHAUSTED="resource_exhausted",t.SESSION_TIME_LIMIT_EXCEEDED="session_time_limit_exceeded",t.CHUNK_SIZE_EXCEEDED="chunk_size_exceeded",t.INSUFFICIENT_AUDIO_ACTIVITY="insufficient_audio_activity"}(Uc||(Uc={})),function(t){t.PCM_8000="pcm_8000",t.PCM_16000="pcm_16000",t.PCM_22050="pcm_22050",t.PCM_24000="pcm_24000",t.PCM_44100="pcm_44100",t.PCM_48000="pcm_48000",t.ULAW_8000="ulaw_8000"}(Lc||(Lc={})),function(t){t.MANUAL="manual",t.VAD="vad"}(Bc||(Bc={}));const Fc=i(class extends n{constructor(t){super(),!1!==t&&this.__registerHost(),this.__attachShadow(),this.conversationStarted=o(this,"conversationStarted"),this.conversationEnded=o(this,"conversationEnded"),this.widgetError=o(this,"widgetError"),this.statusChanged=o(this,"statusChanged"),this.messageReceived=o(this,"messageReceived"),this.positionX="right",this.positionY="bottom",this.variant="floating",this.mode="dark",this.primaryColor="#6366f1",this.brandName="Customer Support",this.language="en",this.autoExpand=!1,this.showBranding=!0,this.fabPrompt="Do you need help?",this.fabButtonText="Start",this.status="disconnected",this.isExpanded=!1,this.termsAccepted=!1,this.errorMessage=null,this.inputVolume=0,this.outputVolume=0,this.messages=[],this.inputText="",this.copiedIndex=null,this.selectedMode="text",this.conversation=null,this.volumeInterval=null,this.messagesContainer=null,this.mediaStream=null,this.isTextOnlyMode=!0,this.pendingMessage=null,this.handleInputKeyDown=t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.handleSendText())},this.handleInputChange=t=>{this.inputText=t.target.value},this.handleToggleExpand=()=>{this.isExpanded=!this.isExpanded},this.copyToClipboard=(t,e)=>{navigator.clipboard.writeText(t),this.copiedIndex=e,setTimeout((()=>{this.copiedIndex=null}),2e3)},this.handleAcceptTerms=()=>{this.termsAccepted=!0},this.handleDeclineTerms=()=>{this.isExpanded=!1}}componentWillLoad(){this.autoExpand&&(this.isExpanded=!0)}disconnectedCallback(){this.cleanup()}async startConversation(t=!0){await this.handleStartConversation(t)}async endConversation(){await this.handleEndConversation()}async getStatus(){return this.status}async sendMessage(t){await this.handleSendText(t)}scrollToBottom(){if(this.messagesContainer){const t=this.messagesContainer;setTimeout((()=>{t.scrollTop=t.scrollHeight}),50)}}async getMicStream(){if(this.mediaStream)return this.mediaStream;try{const t=await navigator.mediaDevices.getUserMedia({audio:!0});return this.mediaStream=t,this.errorMessage=null,t}catch(t){throw t instanceof DOMException&&"NotAllowedError"===t.name&&(this.errorMessage=this.t("microphoneError")),t}}async handleStartConversation(t=!0,e=!1){if("connecting"!==this.status&&"connected"!==this.status)try{this.errorMessage=null,this.status="connecting",this.isTextOnlyMode=t,this.statusChanged.emit(this.status),e||(this.messages=[]),t||await this.getMicStream();const i=this.pendingMessage;let n,s;const r=new Promise(((t,e)=>{n=t,s=e})),o=setTimeout((()=>{s(Error("Connection timeout"))}),15e3),a=t?Rc:Nc;this.conversation=await a.startSession({agentId:this.agentId,connectionType:t?"websocket":"webrtc",overrides:{conversation:{textOnly:t,client_events:t?["agent_response","agent_chat_response_part","user_transcript"]:void 0}},onStatusChange:e=>{const i=e.status,r=this.status;this.status=i,this.statusChanged.emit(i),"connected"===i&&"connected"!==r&&(clearTimeout(o),this.conversationStarted.emit(),t||this.startVolumeMonitoring(),n()),"disconnected"===i&&("connected"===r?(this.conversationEnded.emit(),this.stopVolumeMonitoring()):"connecting"===r&&(clearTimeout(o),s(Error("Connection failed"))))},onMessage:t=>{if(t.message){const e={role:"user"===(t.role||t.source)?"user":"assistant",content:t.message};this.messages=[...this.messages,e],this.messageReceived.emit(e),this.scrollToBottom()}},onError:t=>{this.errorMessage=this.t("connectionError"),this.status="disconnected",this.statusChanged.emit(this.status),this.widgetError.emit({message:t+""})}}),await r,i&&this.conversation&&(this.conversation.sendUserMessage(i),this.pendingMessage=null)}catch(t){this.status="disconnected",this.statusChanged.emit(this.status),this.pendingMessage=null,this.errorMessage=t instanceof DOMException&&"NotAllowedError"===t.name?this.t("microphoneError"):this.t("connectionError"),this.widgetError.emit({message:this.errorMessage})}}async handleEndConversation(){this.conversation&&(this.status="disconnecting",this.statusChanged.emit(this.status),await this.conversation.endSession(),this.conversation=null,this.status="disconnected",this.statusChanged.emit(this.status),this.mediaStream&&(this.mediaStream.getTracks().forEach((t=>t.stop())),this.mediaStream=null))}async handleSendText(t){const e=t||this.inputText.trim();if(e)if("disconnected"===this.status){const t={role:"user",content:e};this.inputText="",this.pendingMessage=e,this.messages=[t],this.scrollToBottom();const i="text"===this.selectedMode;try{await this.handleStartConversation(i,!0)}catch{this.pendingMessage=null}}else"connected"===this.status&&(this.messages=[...this.messages,{role:"user",content:e}],this.inputText="",this.conversation&&"function"==typeof this.conversation.sendUserMessage?this.conversation.sendUserMessage(e):console.error("[Staylift] Cannot send message: no active conversation"),this.scrollToBottom())}async handleVoiceButton(){"disconnected"===this.status||null===this.status?await this.handleStartConversation(!1):"connected"===this.status&&await this.handleEndConversation()}async handleTextButton(){"disconnected"===this.status||null===this.status?await this.handleStartConversation(!0):"connected"===this.status&&await this.handleEndConversation()}startVolumeMonitoring(){this.volumeInterval=setInterval((()=>{if(this.conversation&&"connected"===this.status){const t=this.conversation.getInputVolume?.()??0,e=this.conversation.getOutputVolume?.()??0;this.inputVolume=Math.min(1,2.5*Math.pow(t,.5)),this.outputVolume=Math.min(1,2.5*Math.pow(e,.5))}}),50)}stopVolumeMonitoring(){this.volumeInterval&&(clearInterval(this.volumeInterval),this.volumeInterval=null),this.inputVolume=0,this.outputVolume=0}cleanup(){this.stopVolumeMonitoring(),this.conversation&&(this.conversation.endSession(),this.conversation=null),this.mediaStream&&(this.mediaStream.getTracks().forEach((t=>t.stop())),this.mediaStream=null)}t(t){const e={en:{microphoneError:"Please enable microphone permissions in your browser.",connectionError:"Connection failed. Please try again.",tapToStart:"Tap to start voice chat",connected:"Connected",placeholder:"Type a message...",emptyTitle:"Start a conversation",emptyDesc:"Type a message or tap the voice button",starting:"Starting conversation",connecting:"Connecting...",ready:"Ready to chat",talkOrType:"Start talking or type",poweredBy:"Powered by Staylift",termsTitle:"Terms and Conditions",termsText:'By clicking "Agree," and each time I interact with this AI agent, I consent to the recording, storage, and sharing of my communications with third-party service providers, and as described in the Privacy Policy.',termsWarning:"If you do not wish to have your conversations recorded, please refrain from using this service.",termsAgree:"Agree",termsDecline:"Decline",modeText:"Text",modeVoice:"Voice",startVoice:"Start Voice Call",endVoice:"End Call",startText:"Start Text Chat",endText:"End Chat"},pl:{microphoneError:"Proszę włączyć uprawnienia mikrofonu.",connectionError:"Połączenie nieudane. Spróbuj ponownie.",tapToStart:"Dotknij, aby rozpocząć rozmowę",connected:"Połączono",placeholder:"Napisz wiadomość...",emptyTitle:"Rozpocznij rozmowę",emptyDesc:"Napisz wiadomość lub naciśnij przycisk głosowy",starting:"Rozpoczynanie rozmowy",connecting:"Łączenie...",ready:"Gotowe do czatu",talkOrType:"Mów lub pisz",poweredBy:"Powered by Staylift",termsTitle:"Regulamin",termsText:'Klikając „Zgadzam się" i za każdym razem, gdy wchodzę w interakcję z tym agentem AI, wyrażam zgodę na nagrywanie, przechowywanie i udostępnianie moich komunikatów zewnętrznym dostawcom usług, zgodnie z Polityką Prywatności.',termsWarning:"Jeśli nie chcesz, aby Twoje rozmowy były nagrywane, prosimy o nieużywanie tej usługi.",termsAgree:"Zgadzam się",termsDecline:"Odrzuć",modeText:"Tekst",modeVoice:"Głos",startVoice:"Rozpocznij rozmowę głosową",endVoice:"Zakończ",startText:"Rozpocznij czat",endText:"Zakończ czat"},de:{microphoneError:"Bitte aktivieren Sie die Mikrofonberechtigung in Ihrem Browser.",connectionError:"Verbindung fehlgeschlagen. Bitte versuchen Sie es erneut.",tapToStart:"Tippen, um den Voice-Chat zu starten",connected:"Verbunden",placeholder:"Nachricht eingeben...",emptyTitle:"Gespräch starten",emptyDesc:"Nachricht eingeben oder Voice-Button drücken",starting:"Gespräch wird gestartet",connecting:"Verbindung wird hergestellt...",ready:"Bereit zum Chatten",talkOrType:"Sprechen oder tippen",poweredBy:"Powered by Staylift",termsTitle:"Nutzungsbedingungen",termsText:'Durch Klicken auf „Zustimmen" und bei jeder Interaktion mit diesem KI-Agenten stimme ich der Aufzeichnung, Speicherung und Weitergabe meiner Kommunikation an Drittanbieter zu, wie in der Datenschutzrichtlinie beschrieben.',termsWarning:"Wenn Sie nicht möchten, dass Ihre Gespräche aufgezeichnet werden, verwenden Sie diesen Dienst bitte nicht.",termsAgree:"Zustimmen",termsDecline:"Ablehnen",modeText:"Text",modeVoice:"Stimme",startVoice:"Sprachanruf starten",endVoice:"Beenden",startText:"Text-Chat starten",endText:"Chat beenden"}};return e[this.language]?.[t]||e.en[t]||t}getPositionClasses(){return`sl-x-${this.positionX} sl-y-${this.positionY}`}getThemeColors(){return"light"===this.mode?{bg:"#ffffff",text:"#18181b",muted:"#71717a",border:"#e4e4e7",surface:"#f4f4f5"}:{bg:"#18181b",text:"#ffffff",muted:"#a1a1aa",border:"#27272a",surface:"#27272a"}}render(){const t="connecting"===this.status||"disconnecting"===this.status,e="connected"===this.status&&!this.isTextOnlyMode,i=this.getThemeColors(),n={"--sl-primary":this.primaryColor,"--sl-bg":i.bg,"--sl-text":i.text,"--sl-muted":i.muted,"--sl-border":i.border,"--sl-surface":i.surface};return"inline"===this.variant?c("div",{class:"sl-widget sl-inline",style:n},this.renderCard(t)):c("div",{class:"sl-widget sl-floating "+this.getPositionClasses(),style:n},this.isExpanded?c("div",{class:"sl-card"},this.renderCard(t)):c("div",{class:"sl-fab-pill"},c("div",{class:"sl-fab-avatar"},this.avatarUrl?c("img",{src:this.avatarUrl,alt:"",class:"sl-fab-avatar-img"}):c("staylift-orb",{size:48,primaryColor:this.primaryColor,inputVolume:this.inputVolume,outputVolume:this.outputVolume,isActive:e})),c("div",{class:"sl-fab-content"},c("span",{class:"sl-fab-prompt"},this.fabPrompt),c("button",{class:"sl-fab-btn",onClick:this.handleToggleExpand},c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"})),this.fabButtonText))))}renderCard(t){return this.termsAccepted?[this.renderHeader(t),this.renderContent(),this.renderFooter(t)]:this.renderTerms()}renderTerms(){return c("div",{class:"sl-terms"},c("div",{class:"sl-terms-content"},c("h3",{class:"sl-terms-title"},this.t("termsTitle")),c("p",{class:"sl-terms-text"},this.t("termsText")),c("p",{class:"sl-terms-warning"},this.t("termsWarning"))),c("div",{class:"sl-terms-actions"},c("button",{class:"sl-terms-btn sl-terms-btn--decline",onClick:this.handleDeclineTerms},this.t("termsDecline")),c("button",{class:"sl-terms-btn sl-terms-btn--agree",onClick:this.handleAcceptTerms},this.t("termsAgree"))))}renderHeader(t){return c("div",{class:"sl-header"},c("div",{class:"sl-header-left"},c("div",{class:"sl-orb-ring"},this.avatarUrl?c("img",{src:this.avatarUrl,alt:"",class:"sl-header-avatar-img"}):c("staylift-orb",{size:40,primaryColor:this.primaryColor,inputVolume:this.inputVolume,outputVolume:this.outputVolume,isActive:"connected"===this.status&&!this.isTextOnlyMode})),c("div",{class:"sl-header-text"},c("span",{class:"sl-title"},this.brandName),c("span",{class:"sl-subtitle"},this.errorMessage?c("span",{class:"sl-error"},this.errorMessage):"disconnected"===this.status?this.t("tapToStart"):"connected"===this.status?c("span",{class:"sl-connected"},this.t("connected")):t?c("span",{class:"sl-shimmer"},this.status):null))),c("div",{class:"sl-header-right"},c("div",{class:`sl-dot ${"connected"===this.status?"sl-dot--active":""} ${t?"sl-dot--pulse":""}`}),"floating"===this.variant&&c("button",{class:"sl-close",onClick:this.handleToggleExpand},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M18 6L6 18M6 6l12 12"})))))}renderContent(){const t="connecting"===this.status,e="connected"===this.status;return c("div",{class:"sl-content",ref:t=>this.messagesContainer=t??null},0===this.messages.length?c("div",{class:"sl-empty"},c("staylift-orb",{size:48,primaryColor:this.primaryColor,isActive:!1}),c("h3",{class:"sl-empty-title"},this.t(t?"starting":e?"talkOrType":"emptyTitle")),c("p",{class:"sl-empty-desc"},this.t(t?"connecting":e?"ready":"emptyDesc"))):this.messages.map(((t,e)=>c("div",{class:"sl-msg sl-msg--"+t.role,key:e},c("div",{class:"sl-msg-row"},c("div",{class:"sl-msg-bubble"},t.content)),"assistant"===t.role&&c("div",{class:"sl-msg-actions"},c("button",{class:"sl-action",onClick:()=>this.copyToClipboard(t.content,e)},this.copiedIndex===e?c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("polyline",{points:"20 6 9 17 4 12"})):c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"}))))))))}renderFooter(t){const e="disconnected"===this.status,i="connected"===this.status&&!this.isTextOnlyMode,n="connected"===this.status&&this.isTextOnlyMode;return c("div",{class:"sl-footer"},e&&c("div",{class:"sl-mode-toggle"},c("button",{class:"sl-mode-btn "+("text"===this.selectedMode?"sl-mode-btn--active":""),onClick:()=>this.selectedMode="text"},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})),this.t("modeText")),c("button",{class:"sl-mode-btn "+("voice"===this.selectedMode?"sl-mode-btn--active":""),onClick:()=>this.selectedMode="voice"},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),c("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),c("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),c("line",{x1:"8",y1:"23",x2:"16",y2:"23"})),this.t("modeVoice"))),n&&c("div",{class:"sl-input-row"},c("button",{class:"sl-btn sl-btn--end",onClick:()=>this.handleTextButton(),disabled:t,title:this.t("endText")},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c("line",{x1:"6",y1:"6",x2:"18",y2:"18"}))),c("input",{type:"text",class:"sl-input",placeholder:this.t("placeholder"),value:this.inputText,onInput:this.handleInputChange,onKeyDown:this.handleInputKeyDown,disabled:t}),c("button",{class:"sl-btn",onClick:()=>this.handleSendText(),disabled:!this.inputText.trim()||t},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),c("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})))),"text"===this.selectedMode&&e&&c("div",{class:"sl-voice-controls"},c("button",{class:"sl-voice-btn",onClick:()=>this.handleTextButton(),disabled:t},c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})),this.t(t?"connecting":"startText"))),"voice"===this.selectedMode&&e&&c("div",{class:"sl-voice-controls"},c("button",{class:"sl-voice-btn",onClick:()=>this.handleVoiceButton(),disabled:t},c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),c("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),c("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),c("line",{x1:"8",y1:"23",x2:"16",y2:"23"})),this.t(t?"connecting":"startVoice"))),i&&c("div",{class:"sl-voice-controls"},c("button",{class:"sl-voice-btn sl-voice-btn--end",onClick:()=>this.handleVoiceButton(),disabled:t},c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91"}),c("line",{x1:"22",y1:"2",x2:"2",y2:"22"})),this.t("endVoice"))),this.showBranding&&c("div",{class:"sl-branding"},c("a",{href:"https://staylift.com",target:"_blank",rel:"noopener noreferrer"},c("img",{src:"data:image/png;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8IAEQgAIAAgAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAMCBAEFAAYHCAkKC//EAMMQAAEDAwIEAwQGBAcGBAgGcwECAAMRBBIhBTETIhAGQVEyFGFxIweBIJFCFaFSM7EkYjAWwXLRQ5I0ggjhU0AlYxc18JNzolBEsoPxJlQ2ZJR0wmDShKMYcOInRTdls1V1pJXDhfLTRnaA40dWZrQJChkaKCkqODk6SElKV1hZWmdoaWp3eHl6hoeIiYqQlpeYmZqgpaanqKmqsLW2t7i5usDExcbHyMnK0NTV1tfY2drg5OXm5+jp6vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAQIAAwQFBgcICQoL/8QAwxEAAgIBAwMDAgMFAgUCBASHAQACEQMQEiEEIDFBEwUwIjJRFEAGMyNhQhVxUjSBUCSRoUOxFgdiNVPw0SVgwUThcvEXgmM2cCZFVJInotIICQoYGRooKSo3ODk6RkdISUpVVldYWVpkZWZnaGlqc3R1dnd4eXqAg4SFhoeIiYqQk5SVlpeYmZqgo6SlpqeoqaqwsrO0tba3uLm6wMLDxMXGx8jJytDT1NXW19jZ2uDi4+Tl5ufo6ery8/T19vf4+fr/2wBDAAICAgICAgMCAgMFAwMDBQYFBQUFBggGBgYGBggKCAgICAgICgoKCgoKCgoMDAwMDAwODg4ODg8PDw8PDw8PDw//2wBDAQICAgQEBAcEBAcQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/2gAMAwEAAhEDEQAAAfiPo6T9gTw/lbxH1R8xAWn0XwXsuXwv2J+cvsHnGXj/AP/aAAgBAQABBQJ2O0btujuvDXiGygZS/B6bCDwr9Yvii93+QRKL5RL8C7HvO8yb3t22f0cO3xxpg2+r22+3Pbre83K/u0XUoD//2gAIAQMRAT8BwnczyRDk/enDhl9/j+j8l+8kutyx9kUA/wD/2gAIAQIRAT8B0OVnO3//2gAIAQEABj8CajttnLc48eWgqo1XV5t08MMftLWggDvtxssUw8hKlH+VTrr9rTFZoWnZ41URJQhMyx+avw8nw7SWKbmWDaf+BASqiVfyR8S7mwljSi1jhISnyTQdNPtfB8GLe1uVxRjXFLwurhcqR5E6dv/EADMQAQADAAICAgICAwEBAAACCwERACExQVFhcYGRobHB8NEQ4fEgMEBQYHCAkKCwwNDg/9oACAEBAAE/IZsYHlgL2hFFykgNxq/8i4rZQAQHMl53M1Hu+FPRCE0H7+OCoZU37nAvVx5U656pS9EIT8wQj3YdyrMaSOzIAl5fmjVxMtl8cUFL/9oADAMBAAIRAxEAABD2kov/xAAzEQEBAQADAAECBQUBAQABAQkBABEhMRBBUWEgcfCRgaGx0cHh8TBAUGBwgJCgsMDQ4P/aAAgBAxEBPxDT3M5sJdI+Ma/bs4t0zZy8v7fT4v/aAAgBAhEBPxBPA2RcX//aAAgBAQABPxCXMUdNxPzQSDHSzRnYYmQIwJUDyoU5qBhvVIgVuSPBo61iI8V5sIdq5DxIPbJQrnR+qCA5rryHQleAAiIk2UhJuwnSp6JKa/KjgYm/NRmPignYSnymSrtfVNewxg4eEjzFnxEX/9k=",alt:"Staylift",class:"sl-branding-logo"}),this.t("poweredBy"))))}get el(){return this}static get style(){return":host{--sl-primary:#6366f1;--sl-bg:#18181b;--sl-text:#ffffff;--sl-muted:#a1a1aa;--sl-border:#27272a;--sl-surface:#27272a;--sl-success:#22c55e;--sl-danger:#ef4444;font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;font-size:14px;line-height:1.5;color:var(--sl-text)}.sl-widget *{box-sizing:border-box}.sl-floating{position:fixed;z-index:999999}.sl-x-left{left:40px;right:auto}.sl-x-center{left:50%;right:auto;transform:translateX(-50%)}.sl-x-right{right:40px;left:auto}.sl-y-top{top:40px;bottom:auto}.sl-y-bottom{bottom:40px;top:auto}.sl-fab{width:64px;height:64px;border-radius:50%;border:1px solid var(--sl-border);background:var(--sl-bg);cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 8px 32px rgba(0, 0, 0, 0.4);transition:transform 0.2s, box-shadow 0.2s;padding:8px}.sl-fab:hover{transform:scale(1.05);box-shadow:0 12px 40px rgba(0, 0, 0, 0.5)}.sl-fab-pill{display:flex;align-items:center;gap:16px;padding:12px 16px 12px 12px;background:var(--sl-bg);border:1px solid var(--sl-border);border-radius:32px;box-shadow:0 8px 32px rgba(0, 0, 0, 0.4);animation:sl-fade-in 0.2s ease}.sl-fab-avatar{width:48px;height:48px;border-radius:50%;overflow:hidden;flex-shrink:0;border:1px solid var(--sl-border)}.sl-fab-avatar-img{width:100%;height:100%;object-fit:cover}.sl-fab-content{display:flex;flex-direction:column;gap:8px}.sl-fab-prompt{font-size:14px;font-weight:500;color:var(--sl-text);white-space:nowrap}.sl-fab-btn{display:flex;align-items:center;gap:6px;padding:8px 20px;border:none;border-radius:20px;background:var(--sl-primary);color:white;font-size:13px;font-weight:500;cursor:pointer;transition:all 0.2s}.sl-fab-btn:hover{filter:brightness(1.1);transform:translateY(-1px)}.sl-card{width:440px;height:440px;max-height:calc(100vh - 100px);background:var(--sl-bg);border-radius:16px;border:1px solid var(--sl-border);box-shadow:0 20px 60px rgba(0, 0, 0, 0.5);display:flex;flex-direction:column;overflow:hidden;animation:sl-fade-in 0.2s ease}.sl-inline{width:100%;max-width:540px;height:440px;background:var(--sl-bg);border-radius:16px;border:1px solid var(--sl-border);display:flex;flex-direction:column;overflow:hidden}@keyframes sl-fade-in{from{opacity:0;transform:translateY(10px) scale(0.98)}to{opacity:1;transform:translateY(0) scale(1)}}.sl-header{display:flex;align-items:center;justify-content:space-between;padding:16px;flex-shrink:0;border-bottom:1px solid var(--sl-border)}.sl-header-left{display:flex;align-items:center;gap:16px}.sl-orb-ring{width:40px;height:40px;border-radius:50%;border:1px solid var(--sl-border);overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center}.sl-header-avatar-img{width:100%;height:100%;object-fit:cover;object-position:center center;display:block}.sl-header-text{display:flex;flex-direction:column;gap:2px}.sl-title{font-size:14px;font-weight:500;color:var(--sl-text);line-height:1.2}.sl-subtitle{font-size:12px;color:var(--sl-muted);line-height:1.2}.sl-error{color:var(--sl-danger)}.sl-connected{color:var(--sl-success)}.sl-shimmer{background:linear-gradient(90deg, var(--sl-muted) 0%, var(--sl-text) 50%, var(--sl-muted) 100%);background-size:200% 100%;-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;animation:sl-shimmer 1.5s infinite;text-transform:capitalize}@keyframes sl-shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}.sl-header-right{display:flex;align-items:center;gap:12px}.sl-dot{width:8px;height:8px;border-radius:50%;background:var(--sl-muted);opacity:0.4;transition:all 0.3s}.sl-dot--active{background:var(--sl-success);opacity:1;box-shadow:0 0 8px rgba(34, 197, 94, 0.5)}.sl-dot--pulse{background:var(--sl-text);opacity:0.4;animation:sl-pulse 1s infinite}@keyframes sl-pulse{0%,100%{opacity:0.4}50%{opacity:0.8}}.sl-close{width:32px;height:32px;border-radius:50%;border:none;background:transparent;color:var(--sl-muted);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s}.sl-close:hover{background:var(--sl-surface);color:var(--sl-text)}.sl-content{flex:1;overflow-y:auto;padding:12px 24px 24px;display:flex;flex-direction:column;gap:8px}.sl-empty{display:flex;flex-direction:column;align-items:center;text-align:center;gap:12px}.sl-empty-title{margin:0;font-size:15px;font-weight:500;color:var(--sl-text)}.sl-empty-desc{margin:0;font-size:13px;color:var(--sl-muted)}.sl-mode-toggle{display:flex;gap:8px;margin-bottom:12px;padding:4px;background:var(--sl-surface);border-radius:10px}.sl-mode-btn{display:flex;align-items:center;gap:6px;padding:8px 16px;border:none;border-radius:8px;background:transparent;color:var(--sl-muted);font-size:13px;font-weight:500;cursor:pointer;transition:all 0.2s}.sl-mode-btn:hover{color:var(--sl-text)}.sl-mode-btn--active{background:var(--sl-bg);color:var(--sl-text);box-shadow:0 1px 3px rgba(0, 0, 0, 0.2)}.sl-voice-controls{display:flex;justify-content:center}.sl-voice-btn{display:flex;align-items:center;justify-content:center;gap:10px;width:100%;padding:14px 24px;border:none;border-radius:12px;background:var(--sl-primary);color:white;font-size:14px;font-weight:500;cursor:pointer;transition:all 0.2s}.sl-voice-btn:hover:not(:disabled){filter:brightness(1.1);transform:translateY(-1px)}.sl-voice-btn:disabled{opacity:0.6;cursor:not-allowed}.sl-voice-btn--end{background:var(--sl-danger)}.sl-voice-btn--end:hover:not(:disabled){filter:brightness(1.1)}.sl-msg{display:flex;flex-direction:column;gap:4px}.sl-msg-row{display:flex;align-items:flex-end;gap:8px}.sl-msg--user .sl-msg-row{justify-content:flex-end}.sl-msg--assistant .sl-msg-row{justify-content:flex-start}.sl-msg-bubble{max-width:85%;padding:10px 14px;border-radius:12px;font-size:14px;line-height:1.5;white-space:pre-wrap;word-wrap:break-word}.sl-msg--user .sl-msg-bubble{background:var(--sl-primary);color:white;border-bottom-right-radius:4px}.sl-msg--assistant .sl-msg-bubble{background:var(--sl-surface);color:var(--sl-text);border-bottom-left-radius:4px}.sl-msg-actions{display:flex;gap:4px;padding-left:32px}.sl-action{width:28px;height:28px;border-radius:6px;border:none;background:transparent;color:var(--sl-muted);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s}.sl-action:hover{background:var(--sl-surface);color:var(--sl-text)}.sl-footer{padding:16px;border-top:1px solid var(--sl-border);flex-shrink:0}.sl-branding{text-align:center;margin-top:8px;padding-top:8px}.sl-branding a{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--sl-muted);text-decoration:none;opacity:0.6;transition:opacity 0.2s}.sl-branding a:hover{opacity:1}.sl-branding-logo{width:16px;height:16px;border-radius:3px;object-fit:cover}.sl-input-row{display:flex;align-items:center;gap:8px}.sl-input{flex:1;height:36px;padding:0 12px;border:none;border-radius:8px;background:transparent;color:var(--sl-text);font-size:14px;outline:none}.sl-input::placeholder{color:var(--sl-muted)}.sl-input:disabled{opacity:0.5;cursor:not-allowed}.sl-btn{width:36px;height:36px;border-radius:50%;border:none;background:transparent;color:var(--sl-muted);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s;flex-shrink:0}.sl-btn:hover:not(:disabled){background:var(--sl-surface);color:var(--sl-text)}.sl-btn:disabled{opacity:0.3;cursor:not-allowed}.sl-btn--end{background:var(--sl-surface);color:var(--sl-text)}.sl-btn--end:hover:not(:disabled){background:var(--sl-danger);color:white}.sl-terms{display:flex;flex-direction:column;height:100%;padding:24px}.sl-terms-content{flex:1;display:flex;flex-direction:column;justify-content:center;gap:16px}.sl-terms-title{margin:0;font-size:18px;font-weight:600;color:var(--sl-text)}.sl-terms-text{margin:0;font-size:14px;line-height:1.6;color:var(--sl-text)}.sl-terms-warning{margin:0;font-size:13px;line-height:1.5;color:var(--sl-muted);font-style:italic}.sl-terms-actions{display:flex;gap:12px;padding-top:16px;border-top:1px solid var(--sl-border)}.sl-terms-btn{flex:1;padding:12px 20px;border:none;border-radius:8px;font-size:14px;font-weight:500;cursor:pointer;transition:all 0.2s}.sl-terms-btn--decline{background:var(--sl-surface);color:var(--sl-muted)}.sl-terms-btn--decline:hover{background:var(--sl-border);color:var(--sl-text)}.sl-terms-btn--agree{background:var(--sl-primary);color:white}.sl-terms-btn--agree:hover{filter:brightness(1.1)}@media (max-width: 480px){.sl-card{width:calc(100vw - 32px);max-width:400px}.sl-floating.sl-x-left,.sl-floating.sl-x-right{left:16px;right:16px}.sl-floating.sl-x-center{left:16px;right:16px;transform:none}.sl-floating.sl-y-bottom{bottom:16px}.sl-floating.sl-y-top{top:16px}}"}},[1,"staylift-widget",{agentId:[1,"agent-id"],positionX:[1,"position-x"],positionY:[1,"position-y"],variant:[1],mode:[1],primaryColor:[1,"primary-color"],brandName:[1,"brand-name"],language:[1],autoExpand:[4,"auto-expand"],showBranding:[4,"show-branding"],avatarUrl:[1,"avatar-url"],fabPrompt:[1,"fab-prompt"],fabButtonText:[1,"fab-button-text"],status:[32],isExpanded:[32],termsAccepted:[32],errorMessage:[32],inputVolume:[32],outputVolume:[32],messages:[32],inputText:[32],copiedIndex:[32],selectedMode:[32],startConversation:[64],endConversation:[64],getStatus:[64],sendMessage:[64]}]);function Vc(){"undefined"!=typeof customElements&&["staylift-widget","staylift-orb"].forEach((i=>{switch(i){case"staylift-widget":customElements.get(t(i))||customElements.define(t(i),Fc);break;case"staylift-orb":customElements.get(t(i))||e()}}))}Vc();export{Fc as StayliftWidget,Vc as d}
1
+ import{t,d as e,p as i,H as n,c as o,h as c}from"./p-DnOZjbwA.js";export{S as StayliftOrb,g as getAssetPath,r as render,s as setAssetPath,a as setNonce,b as setPlatformOptions}from"./p-DnOZjbwA.js";function d(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(i){if("default"!==i&&!(i in t)){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})}}))})),Object.freeze(t)}var h=Object.defineProperty,l=(t,e,i)=>((t,e,i)=>e in t?h(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,i);let u=class{constructor(){l(this,"_locking"),l(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let t;this._locks+=1;const e=new Promise((e=>t=()=>{this._locks-=1,e()})),i=this._locking.then((()=>t));return this._locking=this._locking.then((()=>e)),i}};function f(t,e){if(!t)throw Error(e)}function v(t){if("number"!=typeof t)throw Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>2147483647||t<-2147483648)throw Error("invalid int 32: "+t)}function m(t){if("number"!=typeof t)throw Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>4294967295||t<0)throw Error("invalid uint 32: "+t)}function p(t){if("number"!=typeof t)throw Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>34028234663852886e22||t<-34028234663852886e22))throw Error("invalid float 32: "+t)}const y=Symbol("@bufbuild/protobuf/enum-type");function w(t){const e=t[y];return f(e,"missing enum type on enum object"),e}function k(t,e,i){t[y]=T(e,i.map((e=>({no:e.no,name:e.name,localName:t[e.no]}))))}function T(t,e){const i=Object.create(null),n=Object.create(null),s=[];for(const t of e){const e=O(t);s.push(e),i[t.name]=e,n[t.no]=e}return{typeName:t,values:s,findName:t=>i[t],findNumber:t=>n[t]}}function E(t,e){const i={};for(const t of e){const e=O(t);i[e.localName]=e.no,i[e.no]=e.localName}return k(i,t,e),i}function O(t){return"localName"in t?t:Object.assign(Object.assign({},t),{localName:t.name})}class x{equals(t){return this.getType().runtime.util.equals(this.getType(),this,t)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(t,e){const i=this.getType().runtime.bin,n=i.makeReadOptions(e);return i.readMessage(this,n.readerFactory(t),t.byteLength,n),this}fromJson(t,e){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(e);return n.readMessage(i,t,s,this),this}fromJsonString(t,e){let i;try{i=JSON.parse(t)}catch(t){throw Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(t instanceof Error?t.message:t+""))}return this.fromJson(i,e)}toBinary(t){const e=this.getType().runtime.bin,i=e.makeWriteOptions(t),n=i.writerFactory();return e.writeMessage(this,n,i),n.finish()}toJson(t){const e=this.getType().runtime.json,i=e.makeWriteOptions(t);return e.writeMessage(this,i)}toJsonString(t){var e;const i=this.toJson(t);return JSON.stringify(i,null,null!==(e=null==t?void 0:t.prettySpaces)&&void 0!==e?e:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function A(){let t=0,e=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[t,e]}let i=this.buf[this.pos++];if(t|=(15&i)<<28,e=(112&i)>>4,!(128&i))return this.assertBounds(),[t,e];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,!(128&n))return this.assertBounds(),[t,e]}throw Error("invalid varint")}function C(t,e,i){for(let n=0;n<28;n+=7){const s=t>>>n,r=!(s>>>7==0&&0==e);if(i.push(255&(r?128|s:s)),!r)return}const n=t>>>28&15|(7&e)<<4,s=!!(e>>3);if(i.push(255&(s?128|n:n)),s){for(let t=3;t<31;t+=7){const n=e>>>t,s=!(n>>>7==0);if(i.push(255&(s?128|n:n)),!s)return}i.push(e>>>31&1)}}const _=4294967296;function I(t){const e="-"===t[0];e&&(t=t.slice(1));const i=1e6;let n=0,s=0;function r(e,r){const o=Number(t.slice(e,r));s*=i,n=n*i+o,n>=_&&(s+=n/_|0,n%=_)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?P(n,s):j(n,s)}function R(t,e){if(({lo:t,hi:e}=function(t,e){return{lo:t>>>0,hi:e>>>0}}(t,e)),e<=2097151)return _*e+t+"";const i=16777215&(t>>>24|e<<8),n=e>>16&65535;let s=(16777215&t)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),""+o+D(r)+D(s)}function j(t,e){return{lo:0|t,hi:0|e}}function P(t,e){return e=~e,t?t=1+~t:e+=1,j(t,e)}const D=t=>{const e=t+"";return"0000000".slice(e.length)+e};function M(t,e){if(t>=0){for(;t>127;)e.push(127&t|128),t>>>=7;e.push(t)}else{for(let i=0;i<9;i++)e.push(127&t|128),t>>=7;e.push(1)}}function N(){let t=this.buf[this.pos++],e=127&t;if(!(128&t))return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(127&t)<<7,!(128&t))return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(127&t)<<14,!(128&t))return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(127&t)<<21,!(128&t))return this.assertBounds(),e;t=this.buf[this.pos++],e|=(15&t)<<28;for(let e=5;128&t&&e<10;e++)t=this.buf[this.pos++];if(128&t)throw Error("invalid varint");return this.assertBounds(),e>>>0}const U=function(){const t=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof t.getBigInt64&&"function"==typeof t.getBigUint64&&"function"==typeof t.setBigInt64&&"function"==typeof t.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const e=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(t){const n="bigint"==typeof t?t:BigInt(t);if(n>i||n<e)throw Error("int64 invalid: ".concat(t));return n},uParse(t){const e="bigint"==typeof t?t:BigInt(t);if(e>s||e<n)throw Error("uint64 invalid: ".concat(t));return e},enc(e){return t.setBigInt64(0,this.parse(e),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(e){return t.setBigInt64(0,this.uParse(e),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec:(e,i)=>(t.setInt32(0,e,!0),t.setInt32(4,i,!0),t.getBigInt64(0,!0)),uDec:(e,i)=>(t.setInt32(0,e,!0),t.setInt32(4,i,!0),t.getBigUint64(0,!0))}}const e=t=>f(/^-?[0-9]+$/.test(t),"int64 invalid: ".concat(t)),i=t=>f(/^[0-9]+$/.test(t),"uint64 invalid: ".concat(t));return{zero:"0",supported:!1,parse:t=>("string"!=typeof t&&(t=""+t),e(t),t),uParse:t=>("string"!=typeof t&&(t=""+t),i(t),t),enc:t=>("string"!=typeof t&&(t=""+t),e(t),I(t)),uEnc:t=>("string"!=typeof t&&(t=""+t),i(t),I(t)),dec:(t,e)=>function(t,e){let i=j(t,e);const n=2147483648&i.hi;n&&(i=P(i.lo,i.hi));const s=R(i.lo,i.hi);return n?"-"+s:s}(t,e),uDec:(t,e)=>R(t,e)}}();var L,B,F;function V(t,e,i){if(e===i)return!0;if(t==L.BYTES){if(!(e instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(e.length!==i.length)return!1;for(let t=0;t<e.length;t++)if(e[t]!==i[t])return!1;return!0}switch(t){case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return e==i}return!1}function q(t,e){switch(t){case L.BOOL:return!1;case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return 0==e?U.zero:"0";case L.DOUBLE:case L.FLOAT:return 0;case L.BYTES:return new Uint8Array(0);case L.STRING:return"";default:return 0}}function z(t,e){switch(t){case L.BOOL:return!1===e;case L.STRING:return""===e;case L.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return 0==e}}!function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"}(L||(L={})),function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING"}(B||(B={})),function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"}(F||(F={}));class J{constructor(t){this.stack=[],this.textEncoder=null!=t?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let e=0;e<this.chunks.length;e++)t+=this.chunks[e].length;let e=new Uint8Array(t),i=0;for(let t=0;t<this.chunks.length;t++)e.set(this.chunks[t],i),i+=this.chunks[t].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),e=this.stack.pop();if(!e)throw Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,e){return this.uint32((t<<3|e)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(m(t);t>127;)this.buf.push(127&t|128),t>>>=7;return this.buf.push(t),this}int32(t){return v(t),M(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){p(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){m(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){v(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return v(t),M(t=(t<<1^t>>31)>>>0,this.buf),this}sfixed64(t){let e=new Uint8Array(8),i=new DataView(e.buffer),n=U.enc(t);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),i=new DataView(e.buffer),n=U.uEnc(t);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(e)}int64(t){let e=U.enc(t);return C(e.lo,e.hi,this.buf),this}sint64(t){let e=U.enc(t),i=e.hi>>31;return C(e.lo<<1^i,(e.hi<<1|e.lo>>>31)^i,this.buf),this}uint64(t){let e=U.uEnc(t);return C(e.lo,e.hi,this.buf),this}}class W{constructor(t,e){this.varint64=A,this.uint32=N,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=null!=e?e:new TextDecoder}tag(){let t=this.uint32(),e=t>>>3,i=7&t;if(e<=0||i<0||i>5)throw Error("illegal tag: field no "+e+" wire type "+i);return[e,i]}skip(t,e){let i=this.pos;switch(t){case F.Varint:for(;128&this.buf[this.pos++];);break;case F.Bit64:this.pos+=4;case F.Bit32:this.pos+=4;break;case F.LengthDelimited:let i=this.uint32();this.pos+=i;break;case F.StartGroup:for(;;){const[t,i]=this.tag();if(i===F.EndGroup){if(void 0!==e&&t!==e)throw Error("invalid end group tag");break}this.skip(i,t)}break;default:throw Error("cant skip wire type "+t)}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 t=this.uint32();return t>>>1^-(1&t)}int64(){return U.dec(...this.varint64())}uint64(){return U.uDec(...this.varint64())}sint64(){let[t,e]=this.varint64(),i=-(1&t);return t=(t>>>1|(1&e)<<31)^i,e=e>>>1^i,U.dec(t,e)}bool(){let[t,e]=this.varint64();return 0!==t||0!==e}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return U.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return U.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 t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function G(t){const e=t.field.localName,i=Object.create(null);return i[e]=function(t){const e=t.field;if(e.repeated)return[];if(void 0!==e.default)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return q(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(t),[i,()=>i[e]]}let Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),H=[];for(let t=0;t<Q.length;t++)H[Q[t].charCodeAt(0)]=t;H[45]=Q.indexOf("+"),H[95]=Q.indexOf("/");const K={dec(t){let e=3*t.length/4;"="==t[t.length-2]?e-=2:"="==t[t.length-1]&&(e-=1);let i,n=new Uint8Array(e),s=0,r=0,o=0;for(let e=0;e<t.length;e++){if(i=H[t.charCodeAt(e)],void 0===i)switch(t[e]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(t){let e,i="",n=0,s=0;for(let r=0;r<t.length;r++)switch(e=t[r],n){case 0:i+=Q[e>>2],s=(3&e)<<4,n=1;break;case 1:i+=Q[s|e>>4],s=(15&e)<<2,n=2;break;case 2:i+=Q[s|e>>6],i+=Q[63&e],n=0}return n&&(i+=Q[s],i+="=",1==n&&(i+="=")),i}};function Y(t,e,i){X(e,t);const n=e.runtime.bin.makeReadOptions(i),s=function(t,e){if(!e.repeated&&("enum"==e.kind||"scalar"==e.kind)){for(let i=t.length-1;i>=0;--i)if(t[i].no==e.no)return[t[i]];return[]}return t.filter((t=>t.no===e.no))}(t.getType().runtime.bin.listUnknownFields(t),e.field),[r,o]=G(e);for(const t of s)e.runtime.bin.readField(r,n.readerFactory(t.data),e.field,t.wireType,n);return o()}function Z(t,e,i,n){X(e,t);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if($(t,e)){const i=t.getType().runtime.bin.listUnknownFields(t).filter((t=>t.no!=e.field.no));t.getType().runtime.bin.discardUnknownFields(t);for(const e of i)t.getType().runtime.bin.onUnknownField(t,e.no,e.wireType,e.data)}const o=r.writerFactory();let a=e.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[e,i]=c.tag(),n=c.skip(i,e);t.getType().runtime.bin.onUnknownField(t,e,i,n)}}function $(t,e){const i=t.getType();return e.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(t).find((t=>t.no==e.field.no))}function X(t,e){f(t.extendee.typeName==e.getType().typeName,"extension ".concat(t.typeName," can only be applied to message ").concat(t.extendee.typeName))}function tt(t,e){const i=t.localName;if(t.repeated)return e[i].length>0;if(t.oneof)return e[t.oneof.localName].case===i;switch(t.kind){case"enum":case"scalar":return t.opt||t.req?void 0!==e[i]:"enum"==t.kind?e[i]!==t.T.values[0].no:!z(t.T,e[i]);case"message":return void 0!==e[i];case"map":return Object.keys(e[i]).length>0}}function et(t,e){const i=t.localName,n=!t.opt&&!t.req;if(t.repeated)e[i]=[];else if(t.oneof)e[t.oneof.localName]={case:void 0};else switch(t.kind){case"map":e[i]={};break;case"enum":e[i]=n?t.T.values[0].no:void 0;break;case"scalar":e[i]=n?q(t.T,t.L):void 0;break;case"message":e[i]=void 0}}function it(t,e){if(null===t||"object"!=typeof t)return!1;if(!Object.getOwnPropertyNames(x.prototype).every((e=>e in t&&"function"==typeof t[e])))return!1;const i=t.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===e||i.typeName==e.typeName)}function nt(t,e){return it(e)||!t.fieldWrapper?e:t.fieldWrapper.wrapField(e)}const st={ignoreUnknownFields:!1},rt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ot(t){return t?Object.assign(Object.assign({},st),t):st}function at(t){return t?Object.assign(Object.assign({},rt),t):rt}const ct=Symbol(),dt=Symbol();function ht(t){if(null===t)return"null";switch(typeof t){case"object":return Array.isArray(t)?"array":"object";case"string":return t.length>100?"string":'"'.concat(t.split('"').join('\\"'),'"');default:return t+""}}function lt(t,e,i,n,s){let r=i.localName;if(i.repeated){if(f("map"!=i.kind),null===e)return;if(!Array.isArray(e))throw Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e)));const o=t[r];for(const t of e){if(null===t)throw Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(t)));switch(i.kind){case"message":o.push(i.T.fromJson(t,n));break;case"enum":const e=vt(i.T,t,n.ignoreUnknownFields,!0);e!==dt&&o.push(e);break;case"scalar":try{o.push(ft(i.T,t,i.L,!0))}catch(e){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),Error(n)}}}}else if("map"==i.kind){if(null===e)return;if("object"!=typeof e||Array.isArray(e))throw Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e)));const o=t[r];for(const[t,r]of Object.entries(e)){if(null===r)throw Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let a;try{a=ut(i.K,t)}catch(t){let n="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),Error(n)}switch(i.V.kind){case"message":o[a]=i.V.T.fromJson(r,n);break;case"enum":const t=vt(i.V.T,r,n.ignoreUnknownFields,!0);t!==dt&&(o[a]=t);break;case"scalar":try{o[a]=ft(i.V.T,r,B.BIGINT,!0)}catch(t){let n="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),Error(n)}}}}else switch(i.oneof&&(t=t[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const o=i.T;if(null===e&&"google.protobuf.Value"!=o.typeName)return;let a=t[r];it(a)?a.fromJson(e,n):(t[r]=a=o.fromJson(e,n),o.fieldWrapper&&!i.oneof&&(t[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=vt(i.T,e,n.ignoreUnknownFields,!1);switch(c){case ct:et(i,t);break;case dt:break;default:t[r]=c}break;case"scalar":try{const n=ft(i.T,e,i.L,!1);n===ct?et(i,t):t[r]=n}catch(t){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(ht(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),Error(n)}}}function ut(t,e){if(t===L.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1}return""+ft(t,e,B.BIGINT,!0)}function ft(t,e,i,n){if(null===e)return n?q(t,i):ct;switch(t){case L.DOUBLE:case L.FLOAT:if("NaN"===e)return NaN;if("Infinity"===e)return 1/0;if("-Infinity"===e)return-1/0;if(""===e)break;if("string"==typeof e&&e.trim().length!==e.length)break;if("string"!=typeof e&&"number"!=typeof e)break;const n=Number(e);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return t==L.FLOAT&&p(n),n;case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:let s;if("number"==typeof e?s=e:"string"==typeof e&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),void 0===s)break;return t==L.UINT32||t==L.FIXED32?m(s):v(s),s;case L.INT64:case L.SFIXED64:case L.SINT64:if("number"!=typeof e&&"string"!=typeof e)break;const r=U.parse(e);return i?""+r:r;case L.FIXED64:case L.UINT64:if("number"!=typeof e&&"string"!=typeof e)break;const o=U.uParse(e);return i?""+o:o;case L.BOOL:if("boolean"!=typeof e)break;return e;case L.STRING:if("string"!=typeof e)break;return e;case L.BYTES:if(""===e)return new Uint8Array(0);if("string"!=typeof e)break;return K.dec(e)}throw Error()}function vt(t,e,i,n){if(null===e)return"google.protobuf.NullValue"==t.typeName?0:n?t.values[0].no:ct;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const n=t.findName(e);if(void 0!==n)return n.no;if(i)return dt}throw Error("cannot decode enum ".concat(t.typeName," from JSON: ").concat(ht(e)))}function mt(t){return!(!t.repeated&&"map"!=t.kind&&(t.oneof||"message"==t.kind||t.opt||t.req))}function pt(t,e,i){if("map"==t.kind){f("object"==typeof e&&null!=e);const n={},s=Object.entries(e);switch(t.V.kind){case"scalar":for(const[e,i]of s)n[""+e]=bt(t.V.T,i);break;case"message":for(const[t,e]of s)n[""+t]=e.toJson(i);break;case"enum":const e=t.V.T;for(const[t,r]of s)n[""+t]=gt(e,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(t.repeated){f(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let i=0;i<e.length;i++)n.push(bt(t.T,e[i]));break;case"enum":for(let s=0;s<e.length;s++)n.push(gt(t.T,e[s],i.enumAsInteger));break;case"message":for(let t=0;t<e.length;t++)n.push(e[t].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(t.kind){case"scalar":return bt(t.T,e);case"enum":return gt(t.T,e,i.enumAsInteger);case"message":return nt(t.T,e).toJson(i)}}function gt(t,e,i){var n;if(f("number"==typeof e),"google.protobuf.NullValue"==t.typeName)return null;if(i)return e;const s=t.findNumber(e);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:e}function bt(t,e){switch(t){case L.INT32:case L.SFIXED32:case L.SINT32:case L.FIXED32:case L.UINT32:return f("number"==typeof e),e;case L.FLOAT:case L.DOUBLE:return f("number"==typeof e),Number.isNaN(e)?"NaN":e===1/0?"Infinity":e===-1/0?"-Infinity":e;case L.STRING:return f("string"==typeof e),e;case L.BOOL:return f("boolean"==typeof e),e;case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:return f("bigint"==typeof e||"string"==typeof e||"number"==typeof e),""+e;case L.BYTES:return f(e instanceof Uint8Array),K.enc(e)}}const yt=Symbol("@bufbuild/protobuf/unknown-fields"),wt={readUnknownFields:!0,readerFactory:t=>new W(t)},kt={writeUnknownFields:!0,writerFactory:()=>new J};function Tt(t){return t?Object.assign(Object.assign({},wt),t):wt}function St(t){return t?Object.assign(Object.assign({},kt),t):kt}function Et(t,e,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((t=t[i.oneof.localName]).case!=o&&delete t.value,t.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?L.INT32:i.T;let c=At;if("scalar"==i.kind&&i.L>0&&(c=xt),r){let i=t[o];if(n==F.LengthDelimited&&a!=L.STRING&&a!=L.BYTES){let t=e.uint32()+e.pos;for(;e.pos<t;)i.push(c(e,a))}else i.push(c(e,a))}else t[o]=c(e,a);break;case"message":const d=i.T;r?t[o].push(Ot(e,new d,s,i)):it(t[o])?Ot(e,t[o],s,i):(t[o]=Ot(e,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(t[o]=d.fieldWrapper.unwrapField(t[o])));break;case"map":let[h,l]=function(t,e,i){const n=e.uint32(),s=e.pos+n;let r,o;for(;e.pos<s;){const[n]=e.tag();switch(n){case 1:r=At(e,t.K);break;case 2:switch(t.V.kind){case"scalar":o=At(e,t.V.T);break;case"enum":o=e.int32();break;case"message":o=Ot(e,new t.V.T,i,void 0)}}}if(void 0===r&&(r=q(t.K,B.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=""+r),void 0===o)switch(t.V.kind){case"scalar":o=q(t.V.T,B.BIGINT);break;case"enum":o=t.V.T.values[0].no;break;case"message":o=new t.V.T}return[r,o]}(i,e,s);t[o][h]=l}}function Ot(t,e,i,n){const s=e.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(e,t,r?n.no:t.uint32(),i,r),e}function xt(t,e){const i=At(t,e);return"bigint"==typeof i?""+i:i}function At(t,e){switch(e){case L.STRING:return t.string();case L.BOOL:return t.bool();case L.DOUBLE:return t.double();case L.FLOAT:return t.float();case L.INT32:return t.int32();case L.INT64:return t.int64();case L.UINT64:return t.uint64();case L.FIXED64:return t.fixed64();case L.BYTES:return t.bytes();case L.FIXED32:return t.fixed32();case L.SFIXED32:return t.sfixed32();case L.SFIXED64:return t.sfixed64();case L.SINT64:return t.sint64();case L.UINT32:return t.uint32();case L.SINT32:return t.sint32()}}function Ct(t,e,i,n){f(void 0!==e);const s=t.repeated;switch(t.kind){case"scalar":case"enum":let r="enum"==t.kind?L.INT32:t.T;if(s)if(f(Array.isArray(e)),t.packed)!function(t,e,i,n){if(!n.length)return;t.tag(i,F.LengthDelimited).fork();let[,s]=jt(e);for(let e=0;e<n.length;e++)t[s](n[e]);t.join()}(i,r,t.no,e);else for(const n of e)Rt(i,r,t.no,n);else Rt(i,r,t.no,e);break;case"message":if(s){f(Array.isArray(e));for(const s of e)It(i,n,t,s)}else It(i,n,t,e);break;case"map":f("object"==typeof e&&null!=e);for(const[s,r]of Object.entries(e))_t(i,n,t,s,r)}}function _t(t,e,i,n,s){t.tag(i.no,F.LengthDelimited),t.fork();let r=n;switch(i.K){case L.INT32:case L.FIXED32:case L.UINT32:case L.SFIXED32:case L.SINT32:r=Number.parseInt(n);break;case L.BOOL:f("true"==n||"false"==n),r="true"==n}switch(Rt(t,i.K,1,r),i.V.kind){case"scalar":Rt(t,i.V.T,2,s);break;case"enum":Rt(t,L.INT32,2,s);break;case"message":f(void 0!==s),t.tag(2,F.LengthDelimited).bytes(s.toBinary(e))}t.join()}function It(t,e,i,n){const s=nt(i.T,n);i.delimited?t.tag(i.no,F.StartGroup).raw(s.toBinary(e)).tag(i.no,F.EndGroup):t.tag(i.no,F.LengthDelimited).bytes(s.toBinary(e))}function Rt(t,e,i,n){f(void 0!==n);let[s,r]=jt(e);t.tag(i,s)[r](n)}function jt(t){let e=F.Varint;switch(t){case L.BYTES:case L.STRING:e=F.LengthDelimited;break;case L.DOUBLE:case L.FIXED64:case L.SFIXED64:e=F.Bit64;break;case L.FIXED32:case L.SFIXED32:case L.FLOAT:e=F.Bit32}return[e,L[t].toLowerCase()]}function Pt(t){if(void 0===t)return t;if(it(t))return t.clone();if(t instanceof Uint8Array){const e=new Uint8Array(t.byteLength);return e.set(t),e}return t}function Dt(t){return t instanceof Uint8Array?t:new Uint8Array(t)}class Mt{constructor(t,e){this._fields=t,this._normalizer=e}findJsonName(t){if(!this.jsonNames){const t={};for(const e of this.list())t[e.jsonName]=t[e.name]=e;this.jsonNames=t}return this.jsonNames[t]}find(t){if(!this.numbers){const t={};for(const e of this.list())t[e.no]=e;this.numbers=t}return this.numbers[t]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((t,e)=>t.no-e.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const t=this.members;let e;for(const i of this.list())i.oneof?i.oneof!==e&&(e=i.oneof,t.push(e)):t.push(i)}return this.members}}function Nt(t,e){const i=Lt(t);return e?i:zt(qt(i))}const Ut=Lt;function Lt(t){let e=!1;const i=[];for(let n=0;n<t.length;n++){let s=t.charAt(n);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const Bt=new Set(["constructor","toString","toJSON","valueOf"]),Ft=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Vt=t=>"".concat(t,"$"),qt=t=>Ft.has(t)?Vt(t):t,zt=t=>Bt.has(t)?Vt(t):t;class Jt{constructor(t){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=t,this.localName=function(t){return Nt(t,!1)}(t)}addField(t){f(t.oneof===this,"field ".concat(t.name," not one of ").concat(this.name)),this.fields.push(t)}findField(t){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[t]}}const Wt={syntax:"proto3",json:{makeReadOptions:ot,makeWriteOptions:at,readMessage(t,e,i,n){if(null==e||Array.isArray(e)||"object"!=typeof e)throw Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(ht(e)));n=null!=n?n:new t;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(e)){const e=t.fields.findJsonName(o);if(e){if(e.oneof){if(null===a&&"scalar"==e.kind)continue;const i=s.get(e.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(e.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(e.oneof,o)}lt(n,a,e,i,t)}else{let e=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==t.typeName){e=!0;const[t,r]=G(s);lt(t,a,s.field,i,s),Z(n,s,r(),i)}}if(!e&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(t,e){const i=t.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!tt(s,t)){if(s.req)throw"required field not set";if(!e.emitDefaultValues)continue;if(!mt(s))continue}const i=pt(s,s.oneof?t[s.oneof.localName].value:t[s.localName],e);void 0!==i&&(n[e.useProtoFieldName?s.name:s.jsonName]=i)}const r=e.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(t)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&$(t,o)){const i=Y(t,o,e),s=pt(o.field,i,e);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(t){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),n=t instanceof Error?t.message:t+"";throw Error(e+(n.length>0?": ".concat(n):""))}return n},readScalar:(t,e,i)=>ft(t,e,null!=i?i:B.BIGINT,!0),writeScalar(t,e,i){if(void 0!==e)return i||z(t,e)?bt(t,e):void 0},debug:ht},bin:{makeReadOptions:Tt,makeWriteOptions:St,listUnknownFields(t){var e;return null!==(e=t[yt])&&void 0!==e?e:[]},discardUnknownFields(t){delete t[yt]},writeUnknownFields(t,e){const i=t[yt];if(i)for(const t of i)e.tag(t.no,t.wireType).raw(t.data)},onUnknownField(t,e,i,n){const s=t;Array.isArray(s[yt])||(s[yt]=[]),s[yt].push({no:e,wireType:i,data:n})},readMessage(t,e,i,n,s){const r=t.getType(),o=s?e.len:e.pos+i;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!0!==s||c!=F.EndGroup);){const i=r.fields.find(a);if(i)Et(t,e,i,c,n);else{const i=e.skip(c,a);n.readUnknownFields&&this.onUnknownField(t,a,c,i)}}if(s&&(c!=F.EndGroup||a!==i))throw Error("invalid end group tag")},readField:Et,writeMessage(t,e,i){const n=t.getType();for(const s of n.fields.byNumber())if(tt(s,t))Ct(s,s.oneof?t[s.oneof.localName].value:t[s.localName],e,i);else if(s.req)throw Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(t,e),e},writeField(t,e,i,n){void 0!==e&&Ct(t,e,i,n)}},util:Object.assign(Object.assign({},{setEnumType:k,initPartial(t,e){if(void 0===t)return;const i=e.getType();for(const n of i.fields.byMember()){const i=n.localName,s=e,r=t;if(null!=r[i])switch(n.kind){case"oneof":const t=r[i].case;if(void 0===t)continue;const e=n.findField(t);let o=r[i].value;e&&"message"==e.kind&&!it(o,e.T)?o=new e.T(o):e&&"scalar"===e.kind&&e.T===L.BYTES&&(o=Dt(o)),s[i]={case:t,value:o};break;case"scalar":case"enum":let a=r[i];n.T===L.BYTES&&(a=n.repeated?a.map(Dt):Dt(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===L.BYTES)for(const[t,e]of Object.entries(r[i]))s[i][t]=Dt(e);else Object.assign(s[i],r[i]);break;case"message":const t=n.V.T;for(const e of Object.keys(r[i])){let n=r[i][e];t.fieldWrapper||(n=new t(n)),s[i][e]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((t=>it(t,c)?t:new c(t)));else{const t=r[i];s[i]=c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?Dt(t):t:it(t,c)?t:new c(t)}}}},equals:(t,e,i)=>e===i||!(!e||!i)&&t.fields.byMember().every((t=>{const n=e[t.localName],s=i[t.localName];if(t.repeated){if(n.length!==s.length)return!1;switch(t.kind){case"message":return n.every(((e,i)=>t.T.equals(e,s[i])));case"scalar":return n.every(((e,i)=>V(t.T,e,s[i])));case"enum":return n.every(((t,e)=>V(L.INT32,t,s[e])))}throw Error("repeated cannot contain ".concat(t.kind))}switch(t.kind){case"message":let e=n,i=s;return t.T.fieldWrapper&&(void 0===e||it(e)||(e=t.T.fieldWrapper.wrapField(e)),void 0===i||it(i)||(i=t.T.fieldWrapper.wrapField(i))),t.T.equals(e,i);case"enum":return V(L.INT32,n,s);case"scalar":return V(t.T,n,s);case"oneof":if(n.case!==s.case)return!1;const r=t.findField(n.case);if(void 0===r)return!0;switch(r.kind){case"message":return r.T.equals(n.value,s.value);case"enum":return V(L.INT32,n.value,s.value);case"scalar":return V(r.T,n.value,s.value)}throw Error("oneof cannot contain ".concat(r.kind));case"map":const o=Object.keys(n).concat(Object.keys(s));switch(t.V.kind){case"message":const e=t.V.T;return o.every((t=>e.equals(n[t],s[t])));case"enum":return o.every((t=>V(L.INT32,n[t],s[t])));case"scalar":const i=t.V.T;return o.every((t=>V(i,n[t],s[t])))}}})),clone(t){const e=t.getType(),i=new e,n=i;for(const i of e.fields.byMember()){const e=t[i.localName];let s;if(i.repeated)s=e.map(Pt);else if("map"==i.kind){s=n[i.localName];for(const[t,i]of Object.entries(e))s[t]=Pt(i)}else s="oneof"==i.kind?i.findField(e.case)?{case:e.case,value:Pt(e.value)}:{case:void 0}:Pt(e);n[i.localName]=s}for(const i of e.runtime.bin.listUnknownFields(t))e.runtime.bin.onUnknownField(n,i.no,i.wireType,i.data);return i}}),{newFieldList:t=>new Mt(t,(t=>function(t){var e,i,n,s,r,o;const a=[];let c;for(const d of"function"==typeof t?t():t){const t=d;if(t.localName=Nt(d.name,void 0!==d.oneof),t.jsonName=null!==(e=d.jsonName)&&void 0!==e?e:Ut(d.name),t.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(t.L=null!==(n=d.L)&&void 0!==n?n:B.BIGINT),t.delimited=null!==(s=d.delimited)&&void 0!==s&&s,t.req=null!==(r=d.req)&&void 0!==r&&r,t.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(t.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=L.BYTES&&d.T!=L.STRING),void 0!==d.oneof){const e="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==e||(c=new Jt(e)),t.oneof=c,c.addField(t)}a.push(t)}return a}(t))),initFields:t=>{for(const e of t.getType().fields.byMember()){if(e.opt)continue;const i=e.localName,n=t;if(e.repeated)n[i]=[];else switch(e.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=q(e.T,e.L)}}}}),makeMessageType(t,e,i){return function(t,e,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(e){t.util.initFields(this),t.util.initPartial(e,this)}}[r];return Object.setPrototypeOf(o.prototype,new x),Object.assign(o,{runtime:t,typeName:e,fields:t.util.newFieldList(i),fromBinary:(t,e)=>(new o).fromBinary(t,e),fromJson:(t,e)=>(new o).fromJson(t,e),fromJsonString:(t,e)=>(new o).fromJsonString(t,e),equals:(e,i)=>t.util.equals(o,e,i)}),o}(this,t,e,i)},makeEnum:E,makeEnumType:T,getEnumType:w,makeExtension(t,e,i){return function(t,e,i,n){let s;return{typeName:e,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=e.split(".").pop(),i.jsonName="[".concat(e,"]"),s=t.util.newFieldList([i]).list()[0]}return s},runtime:t}}(this,t,e,i)}};class Gt extends x{constructor(t){super(),this.seconds=U.zero,this.nanos=0,Wt.util.initPartial(t,this)}fromJson(t,e){if("string"!=typeof t)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Wt.json.debug(t)));const i=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw Error("cannot decode google.protobuf.Timestamp from JSON: 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 Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=U.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(t){const e=1e3*Number(this.seconds);if(e<Date.parse("0001-01-01T00:00:00Z")||e>Date.parse("9999-12-31T23:59:59Z"))throw Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const t=(""+(this.nanos+1e9)).substring(1);i="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(e).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return Gt.fromDate(new Date)}static fromDate(t){const e=t.getTime();return new Gt({seconds:U.parse(Math.floor(e/1e3)),nanos:e%1e3*1e6})}static fromBinary(t,e){return(new Gt).fromBinary(t,e)}static fromJson(t,e){return(new Gt).fromJson(t,e)}static fromJsonString(t,e){return(new Gt).fromJsonString(t,e)}static equals(t,e){return Wt.util.equals(Gt,t,e)}}Gt.runtime=Wt,Gt.typeName="google.protobuf.Timestamp",Gt.fields=Wt.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const Qt=Wt.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Gt},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ht,repeated:!0},{no:5,name:"events",kind:"message",T:Yt,repeated:!0}])),Ht=Wt.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:Kt,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Kt=Wt.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Gt},{no:3,name:"value",kind:"scalar",T:2}])),Yt=Wt.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:Gt},{no:7,name:"normalized_end_timestamp",kind:"message",T:Gt,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Zt=Wt.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),$t=Wt.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Xt=Wt.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"}]),te=Wt.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ee=Wt.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ie=Wt.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ne=Wt.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"}]),se=Wt.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"}]),re=Wt.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),oe=Wt.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"}]),ae=Wt.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:ce,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:qe}])),ce=Wt.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),de=Wt.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:Wt.getEnumType(Xt),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}])),he=Wt.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:Wt.getEnumType(le)},{no:4,name:"tracks",kind:"message",T:pe,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:de},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Wt.getEnumType(ue)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Wt.getEnumType(ne)},{no:18,name:"kind_details",kind:"enum",T:Wt.getEnumType(fe),repeated:!0}])),le=Wt.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ue=Wt.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"}]),fe=Wt.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),ve=Wt.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),me=Wt.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:ge,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Wt.getEnumType(be)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),pe=Wt.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Wt.getEnumType($t)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:Wt.getEnumType(Xt)},{no:10,name:"layers",kind:"message",T:ge,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:me,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:Wt.getEnumType(ve)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:qe},{no:19,name:"audio_features",kind:"enum",T:Wt.getEnumType(oe),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Wt.getEnumType(Zt)}])),ge=Wt.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Wt.getEnumType(te)},{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}])),be=Wt.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"}]),ye=Wt.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Wt.getEnumType(we)},{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:Oe,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Se,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:xe,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Ae,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Qt,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:_e,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Ie,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Re,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:je,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Ge,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Qe,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:He,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:ke,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),we=Wt.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),ke=Wt.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:Wt.getEnumType(ve)},{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}])),Te=Wt.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Oe,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:_e,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Ie,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Re,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:je,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Ge,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Qe,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:He,oneof:"value"}])),Se=Wt.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Ee,repeated:!0}])),Ee=Wt.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}])),Oe=Wt.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}])),xe=Wt.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Ae=Wt.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:Ce,repeated:!0}])),Ce=Wt.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}])),_e=Wt.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}])),Ie=Wt.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}])),Re=Wt.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),je=Wt.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:Pe,oneof:"value"}])),Pe=Wt.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}])),De=Wt.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Me=Wt.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Wt.getEnumType(Ne)},{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}])),Ne=Wt.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Ue=Wt.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Wt.getEnumType(Le)},{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}])),Le=Wt.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"}]),Be=Wt.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Fe},{no:2,name:"screen",kind:"message",T:Fe},{no:3,name:"resume_connection",kind:"enum",T:Wt.getEnumType(ie)},{no:4,name:"disabled_codecs",kind:"message",T:Ve},{no:5,name:"force_relay",kind:"enum",T:Wt.getEnumType(ie)}])),Fe=Wt.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Wt.getEnumType(ie)}])),Ve=Wt.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ce,repeated:!0},{no:2,name:"publish",kind:"message",T:ce,repeated:!0}])),qe=Wt.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),ze=Wt.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Je=Wt.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Wt.getEnumType(ze)},{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"}),We=Wt.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Ge=Wt.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:Wt.getEnumType(ve)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Je,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:We,oneof:"content_header"}]),{localName:"DataStream_Header"}),Qe=Wt.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"}),He=Wt.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"}),Ke=Wt.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Ye=Wt.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Ze=Wt.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),$e=Wt.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Xe=Wt.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:di,oneof:"message"},{no:2,name:"answer",kind:"message",T:di,oneof:"message"},{no:3,name:"trickle",kind:"message",T:ni,oneof:"message"},{no:4,name:"add_track",kind:"message",T:ii,oneof:"message"},{no:5,name:"mute",kind:"message",T:si,oneof:"message"},{no:6,name:"subscription",kind:"message",T:li,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ui,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:gi,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Ri,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Di,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ui,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:bi,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Li,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:fi,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:vi,oneof:"message"}])),ti=Wt.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:ri,oneof:"message"},{no:2,name:"answer",kind:"message",T:di,oneof:"message"},{no:3,name:"offer",kind:"message",T:di,oneof:"message"},{no:4,name:"trickle",kind:"message",T:ni,oneof:"message"},{no:5,name:"update",kind:"message",T:hi,oneof:"message"},{no:6,name:"track_published",kind:"message",T:ai,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:9,name:"mute",kind:"message",T:si,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:wi,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ki,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Si,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Oi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Ci,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ji,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ci,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:oi,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Bi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:qi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:zi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Wi,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Pi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Yi,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:_i,oneof:"message"}])),ei=Wt.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:ge,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Wt.getEnumType(be)}])),ii=Wt.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:Wt.getEnumType($t)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:Wt.getEnumType(Xt)},{no:9,name:"layers",kind:"message",T:ge,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ei,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:Wt.getEnumType(ve)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Wt.getEnumType(Zt)},{no:17,name:"audio_features",kind:"enum",T:Wt.getEnumType(oe),repeated:!0}])),ni=Wt.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Wt.getEnumType(Ye)},{no:3,name:"final",kind:"scalar",T:8}])),si=Wt.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),ri=Wt.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:ae},{no:2,name:"participant",kind:"message",T:he},{no:3,name:"other_participants",kind:"message",T:he,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:yi,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:Be},{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:Me},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ce,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),oi=Wt.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:yi,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Be},{no:3,name:"server_info",kind:"message",T:Me},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),ai=Wt.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:pe}])),ci=Wt.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),di=Wt.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}}])),hi=Wt.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:he,repeated:!0}])),li=Wt.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:De,repeated:!0}])),ui=Wt.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:Wt.getEnumType(te)},{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}])),fi=Wt.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Wt.getEnumType(oe),repeated:!0}])),vi=Wt.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}])),mi=Wt.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Wt.getEnumType(ne)},{no:3,name:"action",kind:"enum",T:Wt.getEnumType(pi)},{no:4,name:"regions",kind:"message",T:Fi}])),pi=Wt.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),gi=Wt.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:ge,repeated:!0}])),bi=Wt.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}])),yi=Wt.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}])),wi=Wt.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Ee,repeated:!0}])),ki=Wt.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:ae}])),Ti=Wt.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Wt.getEnumType(ee)},{no:3,name:"score",kind:"scalar",T:2}])),Si=Wt.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Ti,repeated:!0}])),Ei=Wt.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:Wt.getEnumType(Ze)}])),Oi=Wt.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Ei,repeated:!0}])),xi=Wt.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Wt.getEnumType(te)},{no:2,name:"enabled",kind:"scalar",T:8}])),Ai=Wt.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:xi,repeated:!0}])),Ci=Wt.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:xi,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Ai,repeated:!0}])),_i=Wt.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Ke,repeated:!0}])),Ii=Wt.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}])),Ri=Wt.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Ii,repeated:!0}])),ji=Wt.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}])),Pi=Wt.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:ae},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:he},{no:4,name:"other_participants",kind:"message",T:he,repeated:!0}])),Di=Wt.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:di},{no:2,name:"subscription",kind:"message",T:li},{no:3,name:"publish_tracks",kind:"message",T:ai,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ni,repeated:!0},{no:5,name:"offer",kind:"message",T:di},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Mi,repeated:!0}])),Mi=Wt.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Ni=Wt.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:Wt.getEnumType(Ye)}])),Ui=Wt.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:Wt.getEnumType($e),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"}])),Li=Wt.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Bi=Wt.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Fi=Wt.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Vi,repeated:!0}])),Vi=Wt.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}])),qi=Wt.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Wt.getEnumType(re)}])),zi=Wt.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Wt.getEnumType(Ji)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:ni,oneof:"request"},{no:5,name:"add_track",kind:"message",T:ii,oneof:"request"},{no:6,name:"mute",kind:"message",T:si,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:bi,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:fi,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:vi,oneof:"request"}])),Ji=Wt.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"}]),Wi=Wt.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Gi=Wt.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}])),Qi=Wt.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:Ue},{no:2,name:"connection_settings",kind:"message",T:Gi},{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:ii,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:di},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:Wt.getEnumType(se)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Di}])),Hi=Wt.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:Wt.getEnumType(Ki)},{no:2,name:"join_request",kind:"scalar",T:12}])),Ki=Wt.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Yi=Wt.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]));function Zi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var $i,Xi,tn,en={exports:{}},nn=en.exports,sn=($i||($i=1,function(t){!function(e,i){t.exports?t.exports=i():e.log=i()}(nn,(function(){var t=function(){},e="undefined",i=typeof window!==e&&typeof window.navigator!==e&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(t,e){var i=t[e];if("function"==typeof i.bind)return i.bind(t);try{return Function.prototype.bind.call(i,t)}catch(e){return function(){return Function.prototype.apply.call(i,t,arguments)}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.call(console.log,console,arguments)),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?t:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===e&&i<this.levels.SILENT)return"No console available for logging"}function d(t){return function(){typeof console!==e&&(c.call(this),this[t].apply(this,arguments))}}function h(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==e&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):t)}(n)||d.apply(this,arguments)}function l(t,i){var o,a,d,l=this,u="loglevel";function f(){var t;if(typeof window!==e&&u){try{t=window.localStorage[u]}catch(t){}if(typeof t===e)try{var i=window.document.cookie,n=encodeURIComponent(u),s=i.indexOf(n+"=");-1!==s&&(t=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(t){}return void 0===l.levels[t]&&(t=void 0),t}}function v(t){var e=t;if("string"==typeof e&&void 0!==l.levels[e.toUpperCase()]&&(e=l.levels[e.toUpperCase()]),"number"==typeof e&&e>=0&&e<=l.levels.SILENT)return e;throw new TypeError("log.setLevel() called with invalid level: "+t)}"string"==typeof t?u+=":"+t:"symbol"==typeof t&&(u=void 0),l.name=t,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=i||h,l.getLevel=function(){return null!=d?d:null!=a?a:o},l.setLevel=function(t,i){return d=v(t),!1!==i&&function(t){var i=(n[t]||"silent").toUpperCase();if(typeof window!==e&&u){try{return void(window.localStorage[u]=i)}catch(t){}try{window.document.cookie=encodeURIComponent(u)+"="+i+";"}catch(t){}}}(d),c.call(l)},l.setDefaultLevel=function(t){a=v(t),f()||l.setLevel(t,!1)},l.resetLevel=function(){d=null,function(){if(typeof window!==e&&u){try{window.localStorage.removeItem(u)}catch(t){}try{window.document.cookie=encodeURIComponent(u)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(t){}}}(),c.call(l)},l.enableAll=function(t){l.setLevel(l.levels.TRACE,t)},l.disableAll=function(t){l.setLevel(l.levels.SILENT,t)},l.rebuild=function(){if(r!==l&&(o=v(r.getLevel())),c.call(l),r===l)for(var t in s)s[t].rebuild()},o=v(r?r.getLevel():"WARN");var m=f();null!=m&&(d=v(m)),c.call(l)}(r=new l).getLogger=function(t){if("symbol"!=typeof t&&"string"!=typeof t||""===t)throw new TypeError("You must supply a name when creating a logger.");var e=s[t];return e||(e=s[t]=new l(t,r.methodFactory)),e};var u=typeof window!==e?window.log:void 0;return r.noConflict=function(){return typeof window!==e&&window.log===r&&(window.log=u),r},r.getLoggers=function(){return s},r.default=r,r}))}(en)),en.exports);!function(t){t[t.trace=0]="trace",t[t.debug=1]="debug",t[t.info=2]="info",t[t.warn=3]="warn",t[t.error=4]="error",t[t.silent=5]="silent"}(Xi||(Xi={})),function(t){t.Default="livekit",t.Room="livekit-room",t.TokenSource="livekit-token-source",t.Participant="livekit-participant",t.Track="livekit-track",t.Publication="livekit-track-publication",t.Engine="livekit-engine",t.Signal="livekit-signal",t.PCManager="livekit-pc-manager",t.PCTransport="livekit-pc-transport",t.E2EE="lk-e2ee"}(tn||(tn={}));let rn=sn.getLogger("livekit");function on(t){const e=sn.getLogger(t);return e.setDefaultLevel(rn.getLevel()),e}Object.values(tn).map((t=>sn.getLogger(t))),rn.setDefaultLevel(Xi.info);const an=sn.getLogger("lk-e2ee"),cn=7e3,dn=[0,300,1200,2700,4800,cn,cn,cn,cn,cn];function hn(t,e,i,n){return new(i||(i=Promise))((function(s,r){function o(t){try{c(n.next(t))}catch(t){r(t)}}function a(t){try{c(n.throw(t))}catch(t){r(t)}}function c(t){t.done?s(t.value):function(t){return t instanceof i?t:new i((function(e){e(t)}))}(t.value).then(o,a)}c((n=n.apply(t,e||[])).next())}))}function ln(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,i=t[Symbol.asyncIterator];return i?i.call(t):(t=function(t){var e="function"==typeof Symbol&&Symbol.iterator,i=e&&t[e],n=0;if(i)return i.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(t),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(i){e[i]=t[i]&&function(e){return new Promise((function(n,s){!function(t,e,i,n){Promise.resolve(n).then((function(e){t({value:e,done:i})}),e)}(n,s,(e=t[i](e)).done,e.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var un,fn={exports:{}},vn=function(){if(un)return fn.exports;un=1;var t,e="object"==typeof Reflect?Reflect:null,i=e&&"function"==typeof e.apply?e.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)};t=e&&"function"==typeof e.ownKeys?e.ownKeys:Object.getOwnPropertySymbols?function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:function(t){return Object.getOwnPropertyNames(t)};var n=Number.isNaN||function(t){return t!=t};function s(){s.init.call(this)}fn.exports=s,fn.exports.once=function(t,e){return new Promise((function(i,n){function s(i){t.removeListener(e,r),n(i)}function r(){"function"==typeof t.removeListener&&t.removeListener("error",s),i([].slice.call(arguments))}v(t,e,r,{once:!0}),"error"!==e&&function(t,e){"function"==typeof t.on&&v(t,"error",e,{once:!0})}(t,s)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function o(t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}function a(t){return void 0===t._maxListeners?s.defaultMaxListeners:t._maxListeners}function c(t,e,i,n){var s,r,c;if(o(i),void 0===(r=t._events)?(r=t._events=Object.create(null),t._eventsCount=0):(void 0!==r.newListener&&(t.emit("newListener",e,i.listener?i.listener:i),r=t._events),c=r[e]),void 0===c)c=r[e]=i,++t._eventsCount;else if("function"==typeof c?c=r[e]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(t))>0&&c.length>s&&!c.warned){c.warned=!0;var d=Error("Possible EventEmitter memory leak detected. "+c.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=t,d.type=e,d.count=c.length,function(t){console&&console.warn&&console.warn(t)}(d)}return t}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 h(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function l(t,e,i){var n=t._events;if(void 0===n)return[];var s=n[e];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(t){for(var e=Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}(s):f(s,s.length)}function u(t){var e=this._events;if(void 0!==e){var i=e[t];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function f(t,e){for(var i=Array(e),n=0;n<e;++n)i[n]=t[n];return i}function v(t,e,i,n){if("function"==typeof t.on)n.once?t.once(e,i):t.on(e,i);else{if("function"!=typeof t.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t);t.addEventListener(e,(function s(r){n.once&&t.removeEventListener(e,s),i(r)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(t){if("number"!=typeof t||t<0||n(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");r=t}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||n(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var s="error"===t,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var a=Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[t];if(void 0===c)return!1;if("function"==typeof c)i(c,this,e);else{var d=c.length,h=f(c,d);for(n=0;n<d;++n)i(h[n],this,e)}return!0},s.prototype.on=s.prototype.addListener=function(t,e){return c(this,t,e,!1)},s.prototype.prependListener=function(t,e){return c(this,t,e,!0)},s.prototype.once=function(t,e){return o(e),this.on(t,h(this,t,e)),this},s.prototype.prependOnceListener=function(t,e){return o(e),this.prependListener(t,h(this,t,e)),this},s.prototype.removeListener=function(t,e){var i,n,s,r,a;if(o(e),void 0===(n=this._events))return this;if(void 0===(i=n[t]))return this;if(i===e||i.listener===e)0==--this._eventsCount?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,i.listener||e));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===e||i[r].listener===e){a=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}(i,s),1===i.length&&(n[t]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",t,a||e)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(t){var e,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[t]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[t]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(e=i[t]))this.removeListener(t,e);else if(void 0!==e)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this},s.prototype.listeners=function(t){return l(this,t,!0)},s.prototype.rawListeners=function(t){return l(this,t,!1)},s.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):u.call(t,e)},s.prototype.listenerCount=u,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]},fn.exports}();let mn=!0,pn=!0;function gn(t,e,i){const n=t.match(e);return n&&n.length>=i&&parseFloat(n[i],10)}function bn(t,e,i){if(!t.RTCPeerConnection)return;const n=t.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(t,n){if(t!==e)return s.apply(this,arguments);const r=t=>{const e=i(t);e&&(n.handleEvent?n.handleEvent(e):n(e))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(n,r),s.call(this,t,r)};const r=n.removeEventListener;n.removeEventListener=function(t,i){if(t!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(i))return r.apply(this,arguments);const n=this._eventMap[e].get(i);return this._eventMap[e].delete(i),0===this._eventMap[e].size&&delete this._eventMap[e],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.call(this,t,n)},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(t){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),t&&this.addEventListener(e,this["_on"+e]=t)},enumerable:!0,configurable:!0})}function yn(t){return"boolean"!=typeof t?Error("Argument type: "+typeof t+". Please use a boolean."):(mn=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function wn(t){return"boolean"!=typeof t?Error("Argument type: "+typeof t+". Please use a boolean."):(pn=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function kn(){if("object"==typeof window){if(mn)return;void 0!==console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Tn(t,e){pn&&console.warn(t+" is deprecated, please use "+e+" instead.")}function Sn(t){return"[object Object]"===Object.prototype.toString.call(t)}function En(t){return Sn(t)?Object.keys(t).reduce((function(e,i){const n=Sn(t[i]),s=n?En(t[i]):t[i];return void 0===s||n&&!Object.keys(s).length?e:Object.assign(e,{[i]:s})}),{}):t}function On(t,e,i){e&&!i.has(e.id)&&(i.set(e.id,e),Object.keys(e).forEach((n=>{n.endsWith("Id")?On(t,t.get(e[n]),i):n.endsWith("Ids")&&e[n].forEach((e=>{On(t,t.get(e),i)}))})))}function xn(t,e,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===e)return s;const r=[];return t.forEach((t=>{"track"===t.type&&t.trackIdentifier===e.id&&r.push(t)})),r.forEach((e=>{t.forEach((i=>{i.type===n&&i.trackId===e.id&&On(t,i,s)}))})),s}const An=kn;function Cn(t,e){const i=t&&t.navigator;if(!i.mediaDevices)return;const n=function(t){if("object"!=typeof t||t.mandatory||t.optional)return t;const e={};return Object.keys(t).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof t[i]?t[i]:{ideal:t[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(t,e){return t?t+e.charAt(0).toUpperCase()+e.slice(1):"deviceId"===e?"sourceId":e};if(void 0!==n.ideal){e.optional=e.optional||[];let t={};"number"==typeof n.ideal?(t[s("min",i)]=n.ideal,e.optional.push(t),t={},t[s("max",i)]=n.ideal,e.optional.push(t)):(t[s("",i)]=n.ideal,e.optional.push(t))}void 0!==n.exact&&"number"!=typeof n.exact?(e.mandatory=e.mandatory||{},e.mandatory[s("",i)]=n.exact):["min","max"].forEach((t=>{void 0!==n[t]&&(e.mandatory=e.mandatory||{},e.mandatory[s(t,i)]=n[t])}))})),t.advanced&&(e.optional=(e.optional||[]).concat(t.advanced)),e},s=function(t,s){if(e.version>=61)return s(t);if((t=JSON.parse(JSON.stringify(t)))&&"object"==typeof t.audio){const e=function(t,e,i){e in t&&!(i in t)&&(t[i]=t[e],delete t[e])};e((t=JSON.parse(JSON.stringify(t))).audio,"autoGainControl","googAutoGainControl"),e(t.audio,"noiseSuppression","googNoiseSuppression"),t.audio=n(t.audio)}if(t&&"object"==typeof t.video){let r=t.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=e.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let e;if(delete t.video.facingMode,"environment"===r.exact||"environment"===r.ideal?e=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(e=["front"]),e)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((t=>"videoinput"===t.kind));let o=i.find((t=>e.some((e=>t.label.toLowerCase().includes(e)))));return!o&&i.length&&e.includes("back")&&(o=i[i.length-1]),o&&(t.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),t.video=n(t.video),An("chrome: "+JSON.stringify(t)),s(t)}))}t.video=n(t.video)}return An("chrome: "+JSON.stringify(t)),s(t)},r=function(t){return e.version>=64?t:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[t.name]||t.name,message:t.message,constraint:t.constraint||t.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(t,e,n){s(t,(t=>{i.webkitGetUserMedia(t,e,(t=>{n&&n(r(t))}))}))}.bind(i),i.mediaDevices.getUserMedia){const t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(e){return s(e,(e=>t(e).then((t=>{if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach((t=>{t.stop()})),new DOMException("","NotFoundError");return t}),(t=>Promise.reject(r(t))))))}}}function _n(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function In(t){if("object"==typeof t&&t.RTCPeerConnection&&!("ontrack"in t.RTCPeerConnection.prototype)){Object.defineProperty(t.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=e=>{e.stream.addEventListener("addtrack",(i=>{let n;n=t.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((t=>t.track&&t.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[e.stream],this.dispatchEvent(s)})),e.stream.getTracks().forEach((i=>{let n;n=t.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((t=>t.track&&t.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[e.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else bn(t,"track",(t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t)))}function Rn(t){if("object"==typeof t&&t.RTCPeerConnection&&!("getSenders"in t.RTCPeerConnection.prototype)&&"createDTMFSender"in t.RTCPeerConnection.prototype){const e=function(t,e){return{track:e,get dtmf(){return void 0===this._dtmf&&(this._dtmf="audio"===e.kind?t.createDTMFSender(e):null),this._dtmf},_pc:t}};if(!t.RTCPeerConnection.prototype.getSenders){t.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(t,n){let s=i.apply(this,arguments);return s||(s=e(this,t),this._senders.push(s)),s};const n=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(t){n.apply(this,arguments);const e=this._senders.indexOf(t);-1!==e&&this._senders.splice(e,1)}}const i=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(t){this._senders=this._senders||[],i.call(this,t),t.getTracks().forEach((t=>{this._senders.push(e(this,t))}))};const n=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(t){this._senders=this._senders||[],n.call(this,t),t.getTracks().forEach((t=>{const e=this._senders.find((e=>e.track===t));e&&this._senders.splice(this._senders.indexOf(e),1)}))}}else if("object"==typeof t&&t.RTCPeerConnection&&"getSenders"in t.RTCPeerConnection.prototype&&"createDTMFSender"in t.RTCPeerConnection.prototype&&t.RTCRtpSender&&!("dtmf"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;t.RTCPeerConnection.prototype.getSenders=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t},Object.defineProperty(t.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&(this._dtmf="audio"===this.track.kind?this._pc.createDTMFSender(this.track):null),this._dtmf}})}}function jn(t){if(!("object"==typeof t&&t.RTCPeerConnection&&t.RTCRtpSender&&t.RTCRtpReceiver))return;if(!("getStats"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t});const i=t.RTCPeerConnection.prototype.addTrack;i&&(t.RTCPeerConnection.prototype.addTrack=function(){const t=i.apply(this,arguments);return t._pc=this,t}),t.RTCRtpSender.prototype.getStats=function(){const t=this;return this._pc.getStats().then((e=>xn(e,t.track,!0)))}}if(!("getStats"in t.RTCRtpReceiver.prototype)){const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t}),bn(t,"track",(t=>(t.receiver._pc=t.srcElement,t))),t.RTCRtpReceiver.prototype.getStats=function(){const t=this;return this._pc.getStats().then((e=>xn(e,t.track,!1)))}}if(!("getStats"in t.RTCRtpSender.prototype)||!("getStats"in t.RTCRtpReceiver.prototype))return;const e=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof t.MediaStreamTrack){const t=arguments[0];let e,i,n;return this.getSenders().forEach((i=>{i.track===t&&(e?n=!0:e=i)})),this.getReceivers().forEach((e=>(e.track===t&&(i?n=!0:i=e),e.track===t))),n||e&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Pn(t){t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((t=>this._shimmedLocalStreams[t][0]))};const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(t,i){if(!i)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=e.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=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(t){this._shimmedLocalStreams=this._shimmedLocalStreams||{},t.getTracks().forEach((t=>{const e=this.getSenders().find((e=>e.track===t));if(e)throw new DOMException("Track already exists.","InvalidAccessError")}));const e=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((t=>-1===e.indexOf(t)));this._shimmedLocalStreams[t.id]=[t].concat(n)};const n=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(t){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[t.id],n.apply(this,arguments)};const s=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(t){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},t&&Object.keys(this._shimmedLocalStreams).forEach((e=>{const i=this._shimmedLocalStreams[e].indexOf(t);-1!==i&&this._shimmedLocalStreams[e].splice(i,1),1===this._shimmedLocalStreams[e].length&&delete this._shimmedLocalStreams[e]})),s.apply(this,arguments)}}function Dn(t,e){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Pn(t);const i=t.RTCPeerConnection.prototype.getLocalStreams;t.RTCPeerConnection.prototype.getLocalStreams=function(){const t=i.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map((t=>this._reverseStreams[t.id]))};const n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(e){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},e.getTracks().forEach((t=>{const e=this.getSenders().find((e=>e.track===t));if(e)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[e.id]){const i=new t.MediaStream(e.getTracks());this._streams[e.id]=i,this._reverseStreams[i.id]=e,e=i}n.call(this,e)};const s=t.RTCPeerConnection.prototype.removeStream;function r(t,e){let i=e.sdp;return Object.keys(t._reverseStreams||[]).forEach((e=>{const n=t._reverseStreams[e];i=i.replace(RegExp(t._streams[n.id].id,"g"),n.id)})),new RTCSessionDescription({type:e.type,sdp:i})}t.RTCPeerConnection.prototype.removeStream=function(t){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.call(this,this._streams[t.id]||t),delete this._reverseStreams[this._streams[t.id]?this._streams[t.id].id:t.id],delete this._streams[t.id]},t.RTCPeerConnection.prototype.addTrack=function(e,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((t=>t===e)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const s=this.getSenders().find((t=>t.track===e));if(s)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(e),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new t.MediaStream([e]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((t=>t.track===e))},["createOffer","createAnswer"].forEach((function(e){const i=t.RTCPeerConnection.prototype[e],n={[e](){const t=arguments;return arguments.length&&"function"==typeof arguments[0]?i.call(this,(e=>{const i=r(this,e);t[0].call(null,i)}),(e=>{t[1]&&t[1].apply(null,e)}),arguments[2]):i.apply(this,arguments).then((t=>r(this,t)))}};t.RTCPeerConnection.prototype[e]=n[e]}));const o=t.RTCPeerConnection.prototype.setLocalDescription;t.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(t,e){let i=e.sdp;return Object.keys(t._reverseStreams||[]).forEach((e=>{const n=t._reverseStreams[e],s=t._streams[n.id];i=i.replace(RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:e.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(t.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(t.RTCPeerConnection.prototype,"localDescription",{get(){const t=a.get.apply(this);return""===t.type?t:r(this,t)}}),t.RTCPeerConnection.prototype.removeTrack=function(t){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!t._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(t._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let e;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((e=>t.track===e))&&(e=this._streams[i])})),e&&(1===e.getTracks().length?this.removeStream(this._reverseStreams[e.id]):e.removeTrack(t.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Mn(t,e){!t.RTCPeerConnection&&t.webkitRTCPeerConnection&&(t.RTCPeerConnection=t.webkitRTCPeerConnection),t.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(e){const i=t.RTCPeerConnection.prototype[e],n={[e](){return arguments[0]=new("addIceCandidate"===e?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};t.RTCPeerConnection.prototype[e]=n[e]}))}function Nn(t,e){bn(t,"negotiationneeded",(t=>{const i=t.target;if(!(e.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return t}))}var Un=Object.freeze({__proto__:null,fixNegotiationNeeded:Nn,shimAddTrackRemoveTrack:Dn,shimAddTrackRemoveTrackWithNative:Pn,shimGetSendersWithDtmf:Rn,shimGetUserMedia:Cn,shimMediaStream:_n,shimOnTrack:In,shimPeerConnection:Mn,shimSenderReceiverGetStats:jn});function Ln(t,e){const i=t&&t.navigator,n=t&&t.MediaStreamTrack;if(i.getUserMedia=function(t,e,n){Tn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(t).then(e,n)},!(e.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const t=function(t,e,i){e in t&&!(i in t)&&(t[i]=t[e],delete t[e])},e=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)),t(i.audio,"autoGainControl","mozAutoGainControl"),t(i.audio,"noiseSuppression","mozNoiseSuppression")),e(i)},n&&n.prototype.getSettings){const e=n.prototype.getSettings;n.prototype.getSettings=function(){const i=e.apply(this,arguments);return t(i,"mozAutoGainControl","autoGainControl"),t(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const e=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),t(i,"autoGainControl","mozAutoGainControl"),t(i,"noiseSuppression","mozNoiseSuppression")),e.call(this,i)}}}}function Bn(t){"object"==typeof t&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Fn(t,e){if("object"!=typeof t||!t.RTCPeerConnection&&!t.mozRTCPeerConnection)return;!t.RTCPeerConnection&&t.mozRTCPeerConnection&&(t.RTCPeerConnection=t.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(e){const i=t.RTCPeerConnection.prototype[e],n={[e](){return arguments[0]=new("addIceCandidate"===e?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};t.RTCPeerConnection.prototype[e]=n[e]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){const[t,s,r]=arguments;return n.call(this,t||null).then((t=>{if(e.version<53&&!s)try{t.forEach((t=>{t.type=i[t.type]||t.type}))}catch(e){if("TypeError"!==e.name)throw e;t.forEach(((e,n)=>{t.set(n,Object.assign({},e,{type:i[e.type]||e.type}))}))}return t})).then(s,r)}}function Vn(t){if("object"!=typeof t||!t.RTCPeerConnection||!t.RTCRtpSender)return;if(t.RTCRtpSender&&"getStats"in t.RTCRtpSender.prototype)return;const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t});const i=t.RTCPeerConnection.prototype.addTrack;i&&(t.RTCPeerConnection.prototype.addTrack=function(){const t=i.apply(this,arguments);return t._pc=this,t}),t.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function qn(t){if("object"!=typeof t||!t.RTCPeerConnection||!t.RTCRtpSender)return;if(t.RTCRtpSender&&"getStats"in t.RTCRtpReceiver.prototype)return;const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const t=e.call(this);return t.forEach((t=>t._pc=this)),t}),bn(t,"track",(t=>(t.receiver._pc=t.srcElement,t))),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function zn(t){t.RTCPeerConnection&&!("removeStream"in t.RTCPeerConnection.prototype)&&(t.RTCPeerConnection.prototype.removeStream=function(t){Tn("removeStream","removeTrack"),this.getSenders().forEach((e=>{e.track&&t.getTracks().includes(e.track)&&this.removeTrack(e)}))})}function Jn(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function Wn(t){if("object"!=typeof t||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.addTransceiver;e&&(t.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let t=arguments[1]&&arguments[1].sendEncodings;void 0===t&&(t=[]),t=[...t];const i=t.length>0;i&&t.forEach((t=>{if("rid"in t&&!/^[a-z0-9]{0,16}$/i.test(t.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in t&&!(parseFloat(t.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in t&&!(parseFloat(t.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=e.apply(this,arguments);if(i){const{sender:e}=n,i=e.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=t,e.sendEncodings=t,this.setParametersPromises.push(e.setParameters(i).then((()=>{delete e.sendEncodings})).catch((()=>{delete e.sendEncodings}))))}return n})}function Gn(t){if("object"!=typeof t||!t.RTCRtpSender)return;const e=t.RTCRtpSender.prototype.getParameters;e&&(t.RTCRtpSender.prototype.getParameters=function(){const t=e.apply(this,arguments);return"encodings"in t||(t.encodings=[].concat(this.sendEncodings||[{}])),t})}function Qn(t){if("object"!=typeof t||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>e.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):e.apply(this,arguments)}}function Hn(t){if("object"!=typeof t||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.createAnswer;t.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>e.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):e.apply(this,arguments)}}var Kn=Object.freeze({__proto__:null,shimAddTransceiver:Wn,shimCreateAnswer:Hn,shimCreateOffer:Qn,shimGetDisplayMedia:function(t,e){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(t.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const t=new DOMException("getDisplayMedia without video constraints is undefined");return t.name="NotFoundError",t.code=8,Promise.reject(t)}return!0===i.video?i.video={mediaSource:e}:i.video.mediaSource=e,t.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Gn,shimGetUserMedia:Ln,shimOnTrack:Bn,shimPeerConnection:Fn,shimRTCDataChannel:Jn,shimReceiverGetStats:qn,shimRemoveStream:zn,shimSenderGetStats:Vn});function Yn(t){if("object"==typeof t&&t.RTCPeerConnection){if("getLocalStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in t.RTCPeerConnection.prototype)){const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addStream=function(t){this._localStreams||(this._localStreams=[]),this._localStreams.includes(t)||this._localStreams.push(t),t.getAudioTracks().forEach((i=>e.call(this,i,t))),t.getVideoTracks().forEach((i=>e.call(this,i,t)))},t.RTCPeerConnection.prototype.addTrack=function(t){for(var i=arguments.length,n=Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach((t=>{this._localStreams?this._localStreams.includes(t)||this._localStreams.push(t):this._localStreams=[t]})),e.apply(this,arguments)}}"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const e=this._localStreams.indexOf(t);if(-1===e)return;this._localStreams.splice(e,1);const i=t.getTracks();this.getSenders().forEach((t=>{i.includes(t.track)&&this.removeTrack(t)}))})}}function Zn(t){if("object"==typeof t&&t.RTCPeerConnection&&("getRemoteStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in t.RTCPeerConnection.prototype))){Object.defineProperty(t.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=t=>{t.streams.forEach((t=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(t))return;this._remoteStreams.push(t);const e=new Event("addstream");e.stream=t,this.dispatchEvent(e)}))})}});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){const t=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((e=>{if(t._remoteStreams||(t._remoteStreams=[]),t._remoteStreams.indexOf(e)>=0)return;t._remoteStreams.push(e);const i=new Event("addstream");i.stream=e,t.dispatchEvent(i)}))}),e.apply(t,arguments)}}}function $n(t){if("object"!=typeof t||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype,i=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(t,e){const n=i.call(this,arguments.length>=2?arguments[2]:arguments[0]);return e?(n.then(t,e),Promise.resolve()):n},e.createAnswer=function(t,e){const i=n.call(this,arguments.length>=2?arguments[2]:arguments[0]);return e?(i.then(t,e),Promise.resolve()):i};let a=function(t,e,i){const n=s.call(this,t);return i?(n.then(e,i),Promise.resolve()):n};e.setLocalDescription=a,a=function(t,e,i){const n=r.call(this,t);return i?(n.then(e,i),Promise.resolve()):n},e.setRemoteDescription=a,a=function(t,e,i){const n=o.call(this,t);return i?(n.then(e,i),Promise.resolve()):n},e.addIceCandidate=a}function Xn(t){const e=t&&t.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=t=>i(ts(t))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(t,i,n){e.mediaDevices.getUserMedia(t).then(i,n)}.bind(e))}function ts(t){return t&&void 0!==t.video?Object.assign({},t,{video:En(t.video)}):t}function es(t){if(!t.RTCPeerConnection)return;const e=t.RTCPeerConnection;t.RTCPeerConnection=function(t,i){if(t&&t.iceServers){const e=[];for(let i=0;i<t.iceServers.length;i++){let n=t.iceServers[i];void 0===n.urls&&n.url?(Tn("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,e.push(n)):e.push(t.iceServers[i])}t.iceServers=e}return new e(t,i)},t.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(t.RTCPeerConnection,"generateCertificate",{get:()=>e.generateCertificate})}function is(t){"object"==typeof t&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ns(t){const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(t){if(t){void 0!==t.offerToReceiveAudio&&(t.offerToReceiveAudio=!!t.offerToReceiveAudio);const e=this.getTransceivers().find((t=>"audio"===t.receiver.track.kind));!1===t.offerToReceiveAudio&&e?"sendrecv"===e.direction?e.setDirection?e.setDirection("sendonly"):e.direction="sendonly":"recvonly"===e.direction&&(e.setDirection?e.setDirection("inactive"):e.direction="inactive"):!0!==t.offerToReceiveAudio||e||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==t.offerToReceiveVideo&&(t.offerToReceiveVideo=!!t.offerToReceiveVideo);const i=this.getTransceivers().find((t=>"video"===t.receiver.track.kind));!1===t.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!==t.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function ss(t){"object"!=typeof t||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var rs,os=Object.freeze({__proto__:null,shimAudioContext:ss,shimCallbacksAPI:$n,shimConstraints:ts,shimCreateOfferLegacy:ns,shimGetUserMedia:Xn,shimLocalStreamsAPI:Yn,shimRTCIceServerUrls:es,shimRemoteStreamsAPI:Zn,shimTrackEventTransceiver:is}),as={exports:{}},cs=(rs||(rs=1,function(t){const e={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split("\n").map((t=>t.trim()))},e.splitSections=function(t){return t.split("\nm=").map(((t,e)=>(e>0?"m="+t:t).trim()+"\r\n"))},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter((t=>0===t.indexOf(i)))},e.parseCandidate=function(t){let e;e=0===t.indexOf("a=candidate:")?t.substring(12).split(" "):t.substring(10).split(" ");const i={foundation:e[0],component:{1:"rtp",2:"rtcp"}[e[1]]||e[1],protocol:e[2].toLowerCase(),priority:parseInt(e[3],10),ip:e[4],address:e[4],port:parseInt(e[5],10),type:e[7]};for(let t=8;t<e.length;t+=2)switch(e[t]){case"raddr":i.relatedAddress=e[t+1];break;case"rport":i.relatedPort=parseInt(e[t+1],10);break;case"tcptype":i.tcpType=e[t+1];break;case"ufrag":i.ufrag=e[t+1],i.usernameFragment=e[t+1];break;default:void 0===i[e[t]]&&(i[e[t]]=e[t+1])}return i},e.writeCandidate=function(t){const e=[];e.push(t.foundation);const i=t.component;e.push("rtp"===i?1:"rtcp"===i?2:i),e.push(t.protocol.toUpperCase()),e.push(t.priority),e.push(t.address||t.ip),e.push(t.port);const n=t.type;return e.push("typ"),e.push(n),"host"!==n&&t.relatedAddress&&t.relatedPort&&(e.push("raddr"),e.push(t.relatedAddress),e.push("rport"),e.push(t.relatedPort)),t.tcpType&&"tcp"===t.protocol.toLowerCase()&&(e.push("tcptype"),e.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(e.push("ufrag"),e.push(t.usernameFragment||t.ufrag)),"candidate:"+e.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let e=t.substring(9).split(" ");const i={payloadType:parseInt(e.shift(),10)};return e=e[0].split("/"),i.name=e[0],i.clockRate=parseInt(e[1],10),i.channels=3===e.length?parseInt(e[2],10):1,i.numChannels=i.channels,i},e.writeRtpMap=function(t){let e=t.payloadType;void 0!==t.preferredPayloadType&&(e=t.preferredPayloadType);const i=t.channels||t.numChannels||1;return"a=rtpmap:"+e+" "+t.name+"/"+t.clockRate+(1!==i?"/"+i:"")+"\r\n"},e.parseExtmap=function(t){const e=t.substring(9).split(" ");return{id:parseInt(e[0],10),direction:e[0].indexOf("/")>0?e[0].split("/")[1]:"sendrecv",uri:e[1],attributes:e.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&"sendrecv"!==t.direction?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+"\r\n"},e.parseFmtp=function(t){const e={};let i;const n=t.substring(t.indexOf(" ")+1).split(";");for(let t=0;t<n.length;t++)i=n[t].trim().split("="),e[i[0].trim()]=i[1];return e},e.writeFmtp=function(t){let e="",i=t.payloadType;if(void 0!==t.preferredPayloadType&&(i=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const n=[];Object.keys(t.parameters).forEach((e=>{n.push(void 0!==t.parameters[e]?e+"="+t.parameters[e]:e)})),e+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return e},e.parseRtcpFb=function(t){const e=t.substring(t.indexOf(" ")+1).split(" ");return{type:e.shift(),parameter:e.join(" ")}},e.writeRtcpFb=function(t){let e="",i=t.payloadType;return void 0!==t.preferredPayloadType&&(i=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach((t=>{e+="a=rtcp-fb:"+i+" "+t.type+(t.parameter&&t.parameter.length?" "+t.parameter:"")+"\r\n"})),e},e.parseSsrcMedia=function(t){const e=t.indexOf(" "),i={ssrc:parseInt(t.substring(7,e),10)},n=t.indexOf(":",e);return n>-1?(i.attribute=t.substring(e+1,n),i.value=t.substring(n+1)):i.attribute=t.substring(e+1),i},e.parseSsrcGroup=function(t){const e=t.substring(13).split(" ");return{semantics:e.shift(),ssrcs:e.map((t=>parseInt(t,10)))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const e=t.substring(14).split(" ");return{algorithm:e[0].toLowerCase(),value:e[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,e){let i="a=setup:"+e+"\r\n";return t.fingerprints.forEach((t=>{i+="a=fingerprint:"+t.algorithm+" "+t.value+"\r\n"})),i},e.parseCryptoLine=function(t){const e=t.substring(9).split(" ");return{tag:parseInt(e[0],10),cryptoSuite:e[1],keyParams:e[2],sessionParams:e.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+("object"==typeof t.keyParams?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+"\r\n"},e.parseCryptoKeyParams=function(t){if(0!==t.indexOf("inline:"))return null;const e=t.substring(7).split("|");return{keyMethod:"inline",keySalt:e[0],lifeTime:e[1],mkiValue:e[2]?e[2].split(":")[0]:void 0,mkiLength:e[2]?e[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const n=e.matchPrefix(t+i,"a=ice-ufrag:")[0],s=e.matchPrefix(t+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let e="a=ice-ufrag:"+t.usernameFragment+"\r\na=ice-pwd:"+t.password+"\r\n";return t.iceLite&&(e+="a=ice-lite\r\n"),e},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=e.splitLines(t)[0].split(" ");i.profile=n[2];for(let s=3;s<n.length;s++){const r=n[s],o=e.matchPrefix(t,"a=rtpmap:"+r+" ")[0];if(o){const n=e.parseRtpMap(o),s=e.matchPrefix(t,"a=fmtp:"+r+" ");switch(n.parameters=s.length?e.parseFmtp(s[0]):{},n.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+r+" ").map(e.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}e.matchPrefix(t,"a=extmap:").forEach((t=>{i.headerExtensions.push(e.parseExtmap(t))}));const s=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach((t=>{s.forEach((e=>{t.rtcpFeedback.find((t=>t.type===e.type&&t.parameter===e.parameter))||t.rtcpFeedback.push(e)}))})),i},e.writeRtpDescription=function(t,i){let n="";n+="m="+t+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((t=>void 0!==t.preferredPayloadType?t.preferredPayloadType:t.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((t=>{n+=e.writeRtpMap(t),n+=e.writeFmtp(t),n+=e.writeRtcpFb(t)}));let s=0;return i.codecs.forEach((t=>{t.maxptime>s&&(s=t.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((t=>{n+=e.writeExtmap(t)})),n},e.parseRtpEncodingParameters=function(t){const i=[],n=e.parseRtpParameters(t),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=e.matchPrefix(t,"a=ssrc:").map((t=>e.parseSsrcMedia(t))).filter((t=>"cname"===t.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=e.matchPrefix(t,"a=ssrc-group:FID").map((t=>t.substring(17).split(" ").map((t=>parseInt(t,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((t=>{if("RTX"===t.name.toUpperCase()&&t.parameters.apt){let e={ssrc:a,codecPayloadType:parseInt(t.parameters.apt,10)};a&&c&&(e.rtx={ssrc:c}),i.push(e),s&&(e=JSON.parse(JSON.stringify(e)),e.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(e))}})),0===i.length&&a&&i.push({ssrc:a});let h=e.matchPrefix(t,"b=");return h.length&&(h=0===h[0].indexOf("b=TIAS:")?parseInt(h[0].substring(7),10):0===h[0].indexOf("b=AS:")?1e3*parseInt(h[0].substring(5),10)*.95-16e3:void 0,i.forEach((t=>{t.maxBitrate=h}))),i},e.parseRtcpParameters=function(t){const i={},n=e.matchPrefix(t,"a=ssrc:").map((t=>e.parseSsrcMedia(t))).filter((t=>"cname"===t.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=e.matchPrefix(t,"a=rtcp-mux");return i.mux=r.length>0,i},e.writeRtcpParameters=function(t){let e="";return t.reducedSize&&(e+="a=rtcp-rsize\r\n"),t.mux&&(e+="a=rtcp-mux\r\n"),void 0!==t.ssrc&&t.cname&&(e+="a=ssrc:"+t.ssrc+" cname:"+t.cname+"\r\n"),e},e.parseMsid=function(t){let i;const n=e.matchPrefix(t,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=e.matchPrefix(t,"a=ssrc:").map((t=>e.parseSsrcMedia(t))).filter((t=>"msid"===t.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},e.parseSctpDescription=function(t){const i=e.parseMLine(t),n=e.matchPrefix(t,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=e.matchPrefix(t,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const t=o[0].substring(10).split(" ");return{port:parseInt(t[0],10),protocol:t[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,e){let i=[];return i="DTLS/SCTP"!==t.protocol?["m="+t.kind+" 9 "+t.protocol+" "+e.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+e.port+"\r\n"]:["m="+t.kind+" 9 "+t.protocol+" "+e.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+e.port+" "+e.protocol+" 65535\r\n"],void 0!==e.maxMessageSize&&i.push("a=max-message-size:"+e.maxMessageSize+"\r\n"),i.join("")},e.generateSessionId=function(){return(""+Math.random()).substr(2,22)},e.writeSessionBoilerplate=function(t,i,n){let s;const r=void 0!==i?i:2;return s=t||e.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},e.getDirection=function(t,i){const n=e.splitLines(t);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return"0"===t.split(" ",2)[1]},e.parseMLine=function(t){const i=e.splitLines(t)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(t){const i=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(t){if("string"!=typeof t||0===t.length)return!1;const i=e.splitLines(t);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},t.exports=e}(as)),as.exports),ds=Zi(cs),hs=d({__proto__:null,default:ds},[cs]);function ls(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;const e=t.RTCIceCandidate;t.RTCIceCandidate=function(t){if("object"==typeof t&&t.candidate&&0===t.candidate.indexOf("a=")&&((t=JSON.parse(JSON.stringify(t))).candidate=t.candidate.substring(2)),t.candidate&&t.candidate.length){const i=new e(t),n=ds.parseCandidate(t.candidate);for(const t in n)t in i||Object.defineProperty(i,t,{value:n[t]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new e(t)},t.RTCIceCandidate.prototype=e.prototype,bn(t,"icecandidate",(e=>(e.candidate&&Object.defineProperty(e,"candidate",{value:new t.RTCIceCandidate(e.candidate),writable:"false"}),e)))}function us(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||bn(t,"icecandidate",(t=>{if(t.candidate){const e=ds.parseCandidate(t.candidate.candidate);"relay"===e.type&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[e.priority>>24])}return t}))}function fs(t,e){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===e.browser&&e.version>=76){const{sdpSemantics:t}=this.getConfiguration();"plan-b"===t&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(t){if(!t||!t.sdp)return!1;const e=ds.splitSections(t.sdp);return e.shift(),e.some((t=>{const e=ds.parseMLine(t);return e&&"application"===e.kind&&-1!==e.protocol.indexOf("SCTP")}))}(arguments[0])){const t=function(t){const e=t.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===e||e.length<2)return-1;const i=parseInt(e[1],10);return i!=i?-1:i}(arguments[0]),i=function(t){let i=65536;return"firefox"===e.browser&&(i=e.version<57?-1===t?16384:2147483637:e.version<60?57===e.version?65535:65536:2147483637),i}(t),n=function(t,i){let n=65536;"firefox"===e.browser&&57===e.version&&(n=65535);const s=ds.matchPrefix(t.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===e.browser&&-1!==i&&(n=2147483637),n}(arguments[0],t);let s;s=0===i&&0===n?1/0:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function vs(t){if(!t.RTCPeerConnection||!("createDataChannel"in t.RTCPeerConnection.prototype))return;function e(t,e){const i=t.send;t.send=function(){const n=arguments[0];if("open"===t.readyState&&e.sctp&&(n.length||n.size||n.byteLength)>e.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+e.sctp.maxMessageSize+" bytes)");return i.apply(t,arguments)}}const i=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){const t=i.apply(this,arguments);return e(t,this),t},bn(t,"datachannel",(t=>(e(t.channel,t.target),t)))}function ms(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=t=>{const e=t.target;if(e._lastConnectionState!==e.connectionState){e._lastConnectionState=e.connectionState;const i=new Event("connectionstatechange",t);e.dispatchEvent(i)}return t},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function ps(t,e){if(!t.RTCPeerConnection)return;if("chrome"===e.browser&&e.version>=71)return;if("safari"===e.browser&&e._safariVersion>=13.1)return;const i=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(e){if(e&&e.sdp&&-1!==e.sdp.indexOf("\na=extmap-allow-mixed")){const i=e.sdp.split("\n").filter((t=>"a=extmap-allow-mixed"!==t.trim())).join("\n");t.RTCSessionDescription&&e instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:e.type,sdp:i}):e.sdp=i}return i.apply(this,arguments)}}function gs(t,e){if(!t.RTCPeerConnection||!t.RTCPeerConnection.prototype)return;const i=t.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===e.browser&&e.version<78||"firefox"===e.browser&&e.version<68||"safari"===e.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function bs(t){if(!t.RTCPeerConnection||!t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype.setLocalDescription;e&&0!==e.length&&(t.RTCPeerConnection.prototype.setLocalDescription=function(){let t=arguments[0]||{};if("object"!=typeof t||t.type&&t.sdp)return e.apply(this,arguments);if(t={type:t.type,sdp:t.sdp},!t.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":t.type="offer";break;default:t.type="answer"}return t.sdp||"offer"!==t.type&&"answer"!==t.type?e.call(this,t):("offer"===t.type?this.createOffer:this.createAnswer).apply(this).then((t=>e.call(this,t)))})}var ys=Object.freeze({__proto__:null,removeExtmapAllowMixed:ps,shimAddIceCandidateNullOrEmpty:gs,shimConnectionState:ms,shimMaxMessageSize:fs,shimParameterlessSetLocalDescription:bs,shimRTCIceCandidate:ls,shimRTCIceCandidateRelayProtocol:us,shimSendThrowTypeError:vs});!function(){let{window:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=kn,n=function(t){const e={browser:null,version:null};if(void 0===t||!t.navigator||!t.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:i}=t;if(i.userAgentData&&i.userAgentData.brands){const t=i.userAgentData.brands.find((t=>"Chromium"===t.brand));if(t)return{browser:"chrome",version:parseInt(t.version,10)}}if(i.mozGetUserMedia)e.browser="firefox",e.version=parseInt(gn(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===t.isSecureContext&&t.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(gn(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!t.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return e.browser="Not a supported browser.",e;e.browser="safari",e.version=parseInt(gn(i.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype,e._safariVersion=gn(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return e}(t),s={browserDetails:n,commonShim:ys,extractVersion:gn,disableLog:yn,disableWarnings:wn,sdp:hs};switch(n.browser){case"chrome":if(!Un||!Mn||!e.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=Un,gs(t,n),bs(t),Cn(t,n),_n(t),Mn(t,n),In(t),Dn(t,n),Rn(t),jn(t),Nn(t,n),ls(t),us(t),ms(t),fs(t,n),vs(t),ps(t,n);break;case"firefox":if(!Kn||!Fn||!e.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Kn,gs(t,n),bs(t),Ln(t,n),Fn(t,n),Bn(t),zn(t),Vn(t),qn(t),Jn(t),Wn(t),Gn(t),Qn(t),Hn(t),ls(t),ms(t),fs(t,n),vs(t);break;case"safari":if(!os||!e.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=os,gs(t,n),bs(t),es(t),ns(t),$n(t),Yn(t),Zn(t),is(t),Xn(t),ss(t),ls(t),us(t),fs(t,n),vs(t),ps(t,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class ws extends Promise{constructor(t){super(t)}catch(t){return super.catch(t)}static reject(t){return super.reject(t)}static all(t){return super.all(t)}static race(t){return super.race(t)}}const ks=/version\/(\d+(\.?_?\d+)+)/i;let Ts;function Ss(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const i=navigator.userAgent.toLowerCase();if(void 0===Ts||e){const t=Es.find((t=>{let{test:e}=t;return e.test(i)}));Ts=null==t?void 0:t.describe(i)}return Ts}const Es=[{test:/firefox|iceweasel|fxios/i,describe:t=>({name:"Firefox",version:Os(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:xs(t)})},{test:/chrom|crios|crmo/i,describe:t=>({name:"Chrome",version:Os(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:xs(t)})},{test:/safari|applewebkit/i,describe:t=>({name:"Safari",version:Os(ks,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:xs(t)})}];function Os(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=e.match(t);return n&&n.length>=i&&n[i]||""}function xs(t){return t.includes("mac os")?Os(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}class As extends Error{constructor(t,e){super(e||"an error has occured"),this.name="LiveKitError",this.code=t}}var Cs,_s,Is,Rs,js,Ps,Ds;!function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout",t[t.WebSocket=6]="WebSocket",t[t.ServiceNotFound=7]="ServiceNotFound"}(Cs||(Cs={}));class Ms extends As{constructor(t,e,i,n){super(1,t),this.name="ConnectionError",this.status=i,this.reason=e,this.context=n,this.reasonName=Cs[e]}static notAllowed(t,e,i){return new Ms(t,Cs.NotAllowed,e,i)}static timeout(t){return new Ms(t,Cs.Timeout)}static leaveRequest(t,e){return new Ms(t,Cs.LeaveRequest,void 0,e)}static internal(t,e){return new Ms(t,Cs.InternalError,void 0,e)}static cancelled(t){return new Ms(t,Cs.Cancelled)}static serverUnreachable(t,e){return new Ms(t,Cs.ServerUnreachable,e)}static websocket(t,e,i){return new Ms(t,Cs.WebSocket,e,i)}static serviceNotFound(t,e){return new Ms(t,Cs.ServiceNotFound,void 0,e)}}class Ns extends As{constructor(t){super(21,null!=t?t:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Us extends As{constructor(t){super(20,null!=t?t:"track is invalid"),this.name="TrackInvalidError"}}class Ls extends As{constructor(t){super(10,null!=t?t:"unsupported server"),this.name="UnsupportedServer"}}class Bs extends As{constructor(t){super(12,null!=t?t:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Fs extends As{constructor(t){super(13,null!=t?t:"unable to negotiate"),this.name="NegotiationError"}}class Vs extends As{constructor(t,e){super(15,t),this.name="PublishTrackError",this.status=e}}class qs extends As{constructor(t,e){super(15,t),this.name="SignalRequestError",this.reason=e,this.reasonName="string"==typeof e?e:Ji[e]}}!function(t){t[t.AlreadyOpened=0]="AlreadyOpened",t[t.AbnormalEnd=1]="AbnormalEnd",t[t.DecodeFailed=2]="DecodeFailed",t[t.LengthExceeded=3]="LengthExceeded",t[t.Incomplete=4]="Incomplete",t[t.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",t[t.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(_s||(_s={}));class zs extends As{constructor(t,e){super(16,t),this.name="DataStreamError",this.reason=e,this.reasonName=_s[e]}}class Js extends As{constructor(t){super(18,t),this.name="SignalReconnectError"}}!function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"}(Is||(Is={})),function(t){t.getFailure=function(e){if(e&&"name"in e)return"NotFoundError"===e.name||"DevicesNotFoundError"===e.name?t.NotFound:"NotAllowedError"===e.name||"PermissionDeniedError"===e.name?t.PermissionDenied:"NotReadableError"===e.name||"TrackStartError"===e.name?t.DeviceInUse:t.Other}}(Is||(Is={}));class Ws{}function Gs(t){return void 0===t?t:"function"==typeof structuredClone?"object"==typeof t&&null!==t?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}Ws.setTimeout=function(){return setTimeout(...arguments)},Ws.setInterval=function(){return setInterval(...arguments)},Ws.clearTimeout=function(){return clearTimeout(...arguments)},Ws.clearInterval=function(){return clearInterval(...arguments)},function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"}(Rs||(Rs={})),function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackCpuConstrained="localTrackCpuConstrained",t.LocalSenderCreated="localSenderCreated",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.TrackCpuConstrained="trackCpuConstrained",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"}(js||(js={})),function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"}(Ps||(Ps={})),function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.CpuConstrained="cpuConstrained",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"}(Ds||(Ds={}));class Qs{constructor(t,e,i,n,s){if("object"==typeof t)this.width=t.width,this.height=t.height,this.aspectRatio=t.aspectRatio,this.encoding={maxBitrate:t.maxBitrate,maxFramerate:t.maxFramerate,priority:t.priority};else{if(void 0===e||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=t,this.height=e,this.aspectRatio=t/e,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Hs=["vp8","h264"],Ks=["vp8","h264","vp9","av1","h265"],Ys=function(t){return!!Hs.find((e=>e===t))};var Zs,$s;!function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"}(Zs||(Zs={})),function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}}($s||($s={}));const Xs={h90:new Qs(160,90,9e4,20),h180:new Qs(320,180,16e4,20),h216:new Qs(384,216,18e4,20),h360:new Qs(640,360,45e4,20),h540:new Qs(960,540,8e5,25),h720:new Qs(1280,720,17e5,30),h1080:new Qs(1920,1080,3e6,30),h1440:new Qs(2560,1440,5e6,30),h2160:new Qs(3840,2160,8e6,30)},tr={h120:new Qs(160,120,7e4,20),h180:new Qs(240,180,125e3,20),h240:new Qs(320,240,14e4,20),h360:new Qs(480,360,33e4,20),h480:new Qs(640,480,5e5,20),h540:new Qs(720,540,6e5,25),h720:new Qs(960,720,13e5,30),h1080:new Qs(1440,1080,23e5,30),h1440:new Qs(1920,1440,38e5,30)},er={h360fps3:new Qs(640,360,2e5,3,"medium"),h360fps15:new Qs(640,360,4e5,15,"medium"),h720fps5:new Qs(1280,720,8e5,5,"medium"),h720fps15:new Qs(1280,720,15e5,15,"medium"),h720fps30:new Qs(1280,720,2e6,30,"medium"),h1080fps15:new Qs(1920,1080,25e5,15,"medium"),h1080fps30:new Qs(1920,1080,5e6,30,"medium"),original:new Qs(0,0,7e6,30,"medium")};function ir(t,e,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=lr(null!=t?t:{}),h=null==e?void 0:e.processor,l=null==i?void 0:i.processor,u=null!=a?a:{};return!0===u.audio&&(u.audio={}),!0===u.video&&(u.video={}),u.audio&&(nr(u.audio,e),null!==(n=(r=u.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||h)&&(u.audio.processor=null!=c?c:h)),u.video&&(nr(u.video,i),null!==(s=(o=u.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(d||l)&&(u.video.processor=null!=d?d:l)),u}function nr(t,e){return Object.keys(e).forEach((i=>{void 0===t[i]&&(t[i]=e[i])})),t}function sr(t){var e,i,n,s;const r={};if(t.video)if("object"==typeof t.video){const i={},s=i,o=t.video;Object.keys(o).forEach((t=>{"resolution"===t?nr(s,o.resolution):s[t]=o[t]})),r.video=i,null!==(e=(n=r.video).deviceId)&&void 0!==e||(n.deviceId={ideal:"default"})}else r.video=!!t.video&&{deviceId:{ideal:"default"}};else r.video=!1;return t.audio?"object"==typeof t.audio?(r.audio=t.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function rr(){var t;const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e){const i=new e({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(t=window.document)||void 0===t?void 0:t.body)){const t=()=>hn(this,void 0,void 0,(function*(){var e;try{"suspended"===i.state&&(yield i.resume())}catch(t){console.warn("Error trying to auto-resume audio context",t)}finally{null===(e=window.document.body)||void 0===e||e.removeEventListener("click",t)}}));i.addEventListener("statechange",(()=>{var e;"closed"===i.state&&(null===(e=window.document.body)||void 0===e||e.removeEventListener("click",t))})),window.document.body.addEventListener("click",t)}return i}}function or(t){return"audioinput"===t?mr.Source.Microphone:"videoinput"===t?mr.Source.Camera:mr.Source.Unknown}function ar(t){return t===mr.Source.Microphone?"audioinput":t===mr.Source.Camera?"videoinput":void 0}function cr(t){return t.split("/")[1].toLowerCase()}function dr(t){const e=[];return t.forEach((t=>{void 0!==t.track&&e.push(new ai({cid:t.track.mediaStreamID,track:t.trackInfo}))})),e}function hr(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?hr(t.track):{})}}function lr(t){const e=Object.assign({},t);let i,n;return"object"==typeof e.audio&&e.audio.processor&&(i=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),"object"==typeof e.video&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:Gs(e)}}function ur(t,e){return t.width*t.height<e.width*e.height}const fr=[];var vr;!function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"}(vr||(vr={}));class mr extends vn.EventEmitter{get streamState(){return this._streamState}setStreamState(t){this._streamState=t}constructor(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=mr.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=rn,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=on(null!==(n=i.loggerName)&&void 0!==n?n:tn.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=e,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=mr.Source.Unknown}get logContext(){var t;return Object.assign(Object.assign({},null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this)),hr(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let e="audio";this.kind===mr.Kind.Video&&(e="video"),0===this.attachedElements.length&&this.kind===mr.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===e&&(fr.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&fr.splice(fr.indexOf(t),1)),t||(t=document.createElement(e))),this.attachedElements.includes(t)||this.attachedElements.push(t),pr(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),n=i.some((t=>"audio"===t.kind));return t.play().then((()=>{this.emit(n?Ds.AudioPlaybackStarted:Ds.VideoPlaybackStarted)})).catch((e=>{"NotAllowedError"===e.name?this.emit(n?Ds.AudioPlaybackFailed:Ds.VideoPlaybackFailed,e):"AbortError"===e.name?rn.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):rn.warn("could not playback ".concat(n?"audio":"video"),e),n&&t&&i.some((t=>"video"===t.kind))&&"NotAllowedError"===e.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(Ds.ElementAttached,t),t}detach(t){try{if(t){gr(this.mediaStreamTrack,t);const e=this.attachedElements.indexOf(t);return e>=0&&(this.attachedElements.splice(e,1),this.recycleElement(t),this.emit(Ds.ElementDetached,t)),t}const e=[];return this.attachedElements.forEach((t=>{gr(this.mediaStreamTrack,t),e.push(t),this.recycleElement(t),this.emit(Ds.ElementDetached,t)})),this.attachedElements=[],e}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(t){t.loggerName&&(this.log=on(t.loggerName)),t.loggerContextCb&&(this.loggerContextCb=t.loggerContextCb)}recycleElement(t){if(t instanceof HTMLAudioElement){let e=!0;t.pause(),fr.forEach((t=>{t.parentElement||(e=!1)})),e&&fr.push(t)}}handleAppVisibilityChanged(){return hn(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==mr.Kind.Video||setTimeout((()=>this.attachedElements.forEach((t=>t.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){_r()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){_r()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function pr(t,e){let i,n;i=e.srcObject instanceof MediaStream?e.srcObject:new MediaStream,n="audio"===t.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(t)||(n.forEach((t=>{i.removeTrack(t)})),i.addTrack(t)),xr()&&e instanceof HTMLVideoElement||(e.autoplay=!0),e.muted=0===i.getAudioTracks().length,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==i&&(e.srcObject=i,(xr()||Er())&&e instanceof HTMLVideoElement&&setTimeout((()=>{e.srcObject=i,e.play().catch((()=>{}))}),0))}function gr(t,e){if(e.srcObject instanceof MediaStream){const i=e.srcObject;i.removeTrack(t),e.srcObject=i.getTracks().length>0?i:null}}!function(t){let e,i,n;!function(t){t.Audio="audio",t.Video="video",t.Unknown="unknown"}(e=t.Kind||(t.Kind={})),function(t){t.Camera="camera",t.Microphone="microphone",t.ScreenShare="screen_share",t.ScreenShareAudio="screen_share_audio",t.Unknown="unknown"}(i=t.Source||(t.Source={})),function(t){t.Active="active",t.Paused="paused",t.Unknown="unknown"}(n=t.StreamState||(t.StreamState={})),t.kindToProto=function(t){switch(t){case e.Audio:return $t.AUDIO;case e.Video:return $t.VIDEO;default:return $t.DATA}},t.kindFromProto=function(t){switch(t){case $t.AUDIO:return e.Audio;case $t.VIDEO:return e.Video;default:return e.Unknown}},t.sourceToProto=function(t){switch(t){case i.Camera:return Xt.CAMERA;case i.Microphone:return Xt.MICROPHONE;case i.ScreenShare:return Xt.SCREEN_SHARE;case i.ScreenShareAudio:return Xt.SCREEN_SHARE_AUDIO;default:return Xt.UNKNOWN}},t.sourceFromProto=function(t){switch(t){case Xt.CAMERA:return i.Camera;case Xt.MICROPHONE:return i.Microphone;case Xt.SCREEN_SHARE:return i.ScreenShare;case Xt.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},t.streamStateFromProto=function(t){switch(t){case Ze.ACTIVE:return n.Active;case Ze.PAUSED:return n.Paused;default:return n.Unknown}}}(mr||(mr={}));const br="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function yr(t){return new ws((e=>Ws.setTimeout(e,t)))}function wr(){return"addTransceiver"in RTCPeerConnection.prototype}function kr(){return"addTrack"in RTCPeerConnection.prototype}function Tr(t){return"av1"===t||"vp9"===t}function Sr(t){return!(!document||Ar())&&(t||(t=document.createElement("audio")),"setSinkId"in t)}function Er(){var t;return"Firefox"===(null===(t=Ss())||void 0===t?void 0:t.name)}function Or(){const t=Ss();return!!t&&"Chrome"===t.name&&"iOS"!==t.os}function xr(){var t;return"Safari"===(null===(t=Ss())||void 0===t?void 0:t.name)}function Ar(){const t=Ss();return"Safari"===(null==t?void 0:t.name)||"iOS"===(null==t?void 0:t.os)}function Cr(){var t,e;return!!_r()&&(null!==(e=null===(t=navigator.userAgentData)||void 0===t?void 0:t.mobile)&&void 0!==e?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function _r(){return"undefined"!=typeof document}function Ir(){return"ReactNative"==navigator.product}function Rr(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function jr(t){return Rr(t)?t.hostname.split(".")[0]:null}function Pr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Dr(){if(!Ir())return;let t=Pr();return t?t.platform:void 0}function Mr(){if(_r())return window.devicePixelRatio;if(Ir()){let t=Pr();if(t)return t.devicePixelRatio}return 1}function Nr(t,e){const i=t.split("."),n=e.split("."),s=Math.min(i.length,n.length);for(let t=0;t<s;++t){const e=parseInt(i[t],10),r=parseInt(n[t],10);if(e>r)return 1;if(e<r)return-1;if(t===s-1&&e===r)return 0}return""===t&&""!==e?-1:""===e?1:i.length==n.length?0:i.length<n.length?-1:1}function Ur(t){for(const e of t)e.target.handleResize(e)}function Lr(t){for(const e of t)e.target.handleVisibilityChanged(e)}let Br=null;const Fr=()=>(Br||(Br=new ResizeObserver(Ur)),Br);let Vr=null;const qr=()=>(Vr||(Vr=new IntersectionObserver(Lr,{root:null,rootMargin:"0px"})),Vr);function zr(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=t,s.height=e;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(t/2,e/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let Jr;function Wr(){if(!Jr){const t=new AudioContext,e=t.createOscillator(),i=t.createGain();i.gain.setValueAtTime(0,0);const n=t.createMediaStreamDestination();if(e.connect(i),i.connect(n),e.start(),[Jr]=n.stream.getAudioTracks(),!Jr)throw Error("Could not get empty media stream audio track");Jr.enabled=!1}return Jr.clone()}class Gr{get isResolved(){return this._isResolved}constructor(t,e){this._isResolved=!1,this.onFinally=e,this.promise=new Promise(((e,i)=>hn(this,void 0,void 0,(function*(){this.resolve=e,this.reject=i,t&&(yield t(e,i))})))).finally((()=>{var t;this._isResolved=!0,null===(t=this.onFinally)||void 0===t||t.call(this)}))}}function Qr(t){if("string"==typeof t||"number"==typeof t)return t;if(Array.isArray(t))return t[0];if(void 0!==t.exact)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(void 0!==t.ideal)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function Hr(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function Kr(t){switch(t.reason){case Cs.LeaveRequest:return t.context;case Cs.Cancelled:return ne.CLIENT_INITIATED;case Cs.NotAllowed:return ne.USER_REJECTED;case Cs.ServerUnreachable:return ne.JOIN_FAILURE;default:return ne.UNKNOWN_REASON}}function Yr(t){return void 0!==t?Number(t):void 0}function Zr(t){return void 0!==t?BigInt(t):void 0}function $r(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function Xr(t){return!!t&&t.kind==mr.Kind.Audio}function to(t){return!!t&&t.kind==mr.Kind.Video}function eo(t){return $r(t)&&to(t)}function io(t){return $r(t)&&Xr(t)}function no(t){return!!t&&!t.isLocal}function so(t){return!!t&&!t.isLocal}function ro(t){return no(t)&&to(t)}function oo(t){return t.endsWith("/")?t:"".concat(t,"/")}function ao(t,e){return t.pathname="".concat(oo(t.pathname)).concat(e),t}function co(t){if("string"==typeof t)return ti.fromJson(JSON.parse(t),{ignoreUnknownFields:!0});if(t instanceof ArrayBuffer)return ti.fromBinary(new Uint8Array(t));throw Error("could not decode websocket message: ".concat(typeof t))}const ho="lk_e2ee";var lo,uo,fo,vo,mo;function po(){return void 0!==window.RTCRtpScriptTransform}!function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"}(lo||(lo={})),function(t){t.KeyRatcheted="keyRatcheted"}(uo||(uo={})),function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"}(fo||(fo={})),function(t){t.Error="cryptorError"}(vo||(vo={})),function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"}(mo||(mo={}));class go extends vn.EventEmitter{constructor(t,e){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=t=>{var e,i;const{kind:n,data:s}=t.data;switch(n){case"error":if(rn.error(s.error.message),s.uuid){const t=this.decryptDataRequests.get(s.uuid);if(null==t?void 0:t.reject){t.reject(s.error);break}const e=this.encryptDataRequests.get(s.uuid);if(null==e?void 0:e.reject){e.reject(s.error);break}}this.emit(fo.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((t=>{this.postKey(t)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((t=>{this.postKey(t)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(e=this.room)||void 0===e?void 0:e.localParticipant.identity))this.emit(fo.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const t=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(fo.ParticipantEncryptionStatusChanged,s.enabled,t)}break;case"ratchetKey":this.keyProvider.emit(lo.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const t=this.decryptDataRequests.get(s.uuid);(null==t?void 0:t.resolve)&&t.resolve(s);break;case"encryptDataResponse":const n=this.encryptDataRequests.get(s.uuid);(null==n?void 0:n.resolve)&&n.resolve(s)}},this.onWorkerError=t=>{rn.error("e2ee worker encountered an error:",{error:t.error}),this.emit(fo.EncryptionError,t.error,void 0)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=e}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(t){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||po()))throw new Ns("tried to setup end-to-end encryption on an unsupported browser");if(rn.info("setting up e2ee"),t!==this.room){this.room=t,this.setupEventListeners(t,this.keyProvider);const e={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:an.getLevel()}};this.worker&&(rn.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(e))}}setParticipantCryptorEnabled(t,e){rn.debug("set e2ee to ".concat(t," for participant ").concat(e)),this.postEnable(t,e)}setSifTrailer(t){t&&0!==t.length?this.postSifTrailer(t):rn.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(Ps.RTPVideoMapUpdate,(t=>{this.postRTPMap(t)}))}setupEventListeners(t,e){t.on(Rs.TrackPublished,((t,e)=>this.setParticipantCryptorEnabled(t.trackInfo.encryption!==ve.NONE,e.identity))),t.on(Rs.ConnectionStateChanged,(e=>{e===Na.Connected&&t.remoteParticipants.forEach((t=>{t.trackPublications.forEach((e=>{this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ve.NONE,t.identity)}))}))})).on(Rs.TrackUnsubscribed,((t,e,i)=>{var n;null===(n=this.worker)||void 0===n||n.postMessage({kind:"removeTransform",data:{participantIdentity:i.identity,trackId:t.mediaStreamID}})})).on(Rs.TrackSubscribed,((t,e,i)=>{this.setupE2EEReceiver(t,i.identity,e.trackInfo)})).on(Rs.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");e.getKeys().forEach((t=>{this.postKey(t)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),t.localParticipant.on(js.LocalSenderCreated,((t,e)=>hn(this,void 0,void 0,(function*(){this.setupE2EESender(e,t)})))),t.localParticipant.on(js.LocalTrackPublished,(t=>{if(!to(t.track)||!Ar())return;const e={kind:"updateCodec",data:{trackId:t.track.mediaStreamID,codec:cr(t.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(e)})),e.on(lo.SetKey,(t=>this.postKey(t))).on(lo.RatchetRequest,((t,e)=>this.postRatchetRequest(t,e)))}encryptData(t){return hn(this,void 0,void 0,(function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const e=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:e,payload:t,participantIdentity:this.room.localParticipant.identity}},n=new Gr;return n.onFinally=()=>{this.encryptDataRequests.delete(e)},this.encryptDataRequests.set(e,n),this.worker.postMessage(i),n.promise}))}handleEncryptedData(t,e,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),r={kind:"decryptDataRequest",data:{uuid:s,payload:t,iv:e,participantIdentity:i,keyIndex:n}},o=new Gr;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(r),o.promise}postRatchetRequest(t,e){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:t,keyIndex:e}})}postKey(t){let{key:e,participantIdentity:i,keyIndex:n}=t;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:e,keyIndex:n}};this.worker.postMessage(r)}postEnable(t,e){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");this.worker.postMessage({kind:"enable",data:{enabled:t,participantIdentity:e}})}postRTPMap(t){var e;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(e=this.room)||void 0===e?void 0:e.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");this.worker.postMessage({kind:"setRTPMap",data:{map:t,participantIdentity:this.room.localParticipant.identity}})}postSifTrailer(t){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:t}})}setupE2EEReceiver(t,e,i){if(t.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(t.receiver,t.mediaStreamID,e,"video"===t.kind?cr(i.mimeType):void 0)}}setupE2EESender(t,e){$r(t)&&e?this.handleSender(e,t.mediaStreamID,void 0):e||rn.warn("early return because sender is not ready")}handleReceiver(t,e,i,n){return hn(this,void 0,void 0,(function*(){if(this.worker){if(po()&&!Or())t.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:e,codec:n});else{if(ho in t&&n)return void this.worker.postMessage({kind:"updateCodec",data:{trackId:e,codec:n,participantIdentity:i}});let s=t.writableStream,r=t.readableStream;if(!s||!r){const e=t.createEncodedStreams();t.writableStream=e.writable,s=e.writable,t.readableStream=e.readable,r=e.readable}this.worker.postMessage({kind:"decode",data:{readableStream:r,writableStream:s,trackId:e,codec:n,participantIdentity:i,isReuse:ho in t}},[r,s])}t[ho]=!0}}))}handleSender(t,e,i){var n;if(!(ho in t)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(po()&&!Or())rn.info("initialize script transform"),t.transform=new RTCRtpScriptTransform(this.worker,{kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:e,codec:i});else{rn.info("initialize encoded streams");const n=t.createEncodedStreams();this.worker.postMessage({kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:e,participantIdentity:this.room.localParticipant.identity,isReuse:!1}},[n.readable,n.writable])}t[ho]=!0}}}class bo{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new bo),this._instance}addFailedConnectionAttempt(t){var e;const i=jr(new URL(t));if(!i)return;let n=null!==(e=this.failedConnectionAttempts.get(i))&&void 0!==e?e:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,yr(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(t){const e=new URL(t),i=e&&jr(e);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(t){const e=new URL(t),i=e&&jr(e);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}bo._instance=null;const yo="default";class wo{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new wo),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=wo.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){rn.debug("awaiting getUserMedia promise");try{t?yield wo.userMediaPromiseMap.get(t):yield Promise.all(wo.userMediaPromiseMap.values())}catch(t){rn.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!xr()||!e.hasDeviceInUse(t))){const e=0===s.filter((e=>e.kind===t)).length||s.some((e=>""===e.label&&(!t||e.kind===t)));if(e){const e={video:"audioinput"!==t&&"audiooutput"!==t,audio:"videoinput"!==t&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(e);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((t=>{t.stop()}))}}return e._previousDevices=s,t&&(s=s.filter((e=>e.kind===t))),s}()}))}normalizeDeviceId(t,e,i){return hn(this,void 0,void 0,(function*(){if(e!==yo)return e;const n=yield this.getDevices(t),s=n.find((t=>t.deviceId===yo));if(!s)return void rn.warn("could not reliably determine default device");const r=n.find((t=>t.deviceId!==yo&&t.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;rn.warn("could not reliably determine default device")}))}hasDeviceInUse(t){return t?wo.userMediaPromiseMap.has(t):wo.userMediaPromiseMap.size>0}}var ko;wo.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],wo.userMediaPromiseMap=new Map,function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"}(ko||(ko={}));class To{constructor(){this.pendingTasks=new Map,this.taskMutex=new u,this.nextTaskIndex=0}run(t){return hn(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ko.WAITING};this.pendingTasks.set(e.id,e);const i=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=ko.RUNNING,yield t()}finally{e.status=ko.COMPLETED,this.pendingTasks.delete(e.id),i()}}))}flush(){return hn(this,void 0,void 0,(function*(){return this.run((()=>hn(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}class So{get readyState(){return this.ws.readyState}constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;if(null===(i=e.signal)||void 0===i?void 0:i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=t;const s=new WebSocket(t,null!==(n=e.protocols)&&void 0!==n?n:[]);s.binaryType="arraybuffer",this.ws=s;const r=function(){let{closeCode:t,reason:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return s.close(t,e)};this.opened=new ws(((t,e)=>{const i=()=>{e(Ms.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{t({readable:new ReadableStream({start(t){s.onmessage=e=>{let{data:i}=e;return t.enqueue(i)},s.onerror=e=>t.error(e)},cancel:r}),writable:new WritableStream({write(t){s.send(t)},abort(){s.close()},close:r}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",i)},s.addEventListener("error",i)})),this.closed=new ws(((t,e)=>{const i=()=>hn(this,void 0,void 0,(function*(){const i=new ws((t=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",(e=>{t(e)}),{once:!0})})),n=yield ws.race([yr(250),i]);n?t(n):e(Ms.websocket("Encountered unspecified websocket error without a timely close event"))}));s.onclose=e=>{let{code:n,reason:r}=e;t({closeCode:n,reason:r}),s.removeEventListener("error",i)},s.addEventListener("error",i)})),e.signal&&(e.signal.onabort=()=>s.close()),this.close=r}}const Eo=["syncState","trickle","offer","answer","simulate","leave"];var Oo;!function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"}(Oo||(Oo={}));class xo{get currentState(){return this.state}get isDisconnected(){return this.state===Oo.DISCONNECTING||this.state===Oo.DISCONNECTED}get isEstablishingConnection(){return this.state===Oo.CONNECTING||this.state===Oo.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Oo.DISCONNECTED,this.log=rn,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=on(null!==(i=e.loggerName)&&void 0!==i?i:tn.Signal),this.loggerContextCb=e.loggerContextCb,this.useJSON=t,this.requestQueue=new To,this.queuedRequests=[],this.closingLock=new u,this.connectionLock=new u,this.state=Oo.DISCONNECTED}get logContext(){var t,e;return null!==(e=null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this))&&void 0!==e?e:{}}join(t,e,i,n){return hn(this,arguments,void 0,(function(t,e,i,n){var s=this;let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){return s.state=Oo.CONNECTING,s.options=i,yield s.connect(t,e,i,n,r)}()}))}reconnect(t,e,i,n){return hn(this,void 0,void 0,(function*(){if(this.options)return this.state=Oo.RECONNECTING,this.clearPingInterval(),yield this.connect(t,e,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath);this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)}))}connect(t,e,i,n){return hn(this,arguments,void 0,(function(t,e,i,n){var s=this;let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){const o=yield s.connectionLock.lock();s.connectOptions=i,s.useV0SignalPath=r;const a=function(){var t;const e=new Ue({sdk:Le.JS,protocol:16,version:"2.17.0"});return Ir()&&(e.os=null!==(t=Dr())&&void 0!==t?t:""),e}(),c=r?function(t,e,i){var n;const s=new URLSearchParams;return s.set("access_token",t),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid)),s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",Ir()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",""+e.protocol),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),i.adaptiveStream&&s.set("adaptive_stream","1"),i.reconnectReason&&s.set("reconnect_reason",""+i.reconnectReason),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type),s}(e,a,i):function(t,e,i){const n=new URLSearchParams;n.set("access_token",t);const s=new Qi({clientInfo:e,connectionSettings:new Gi({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0});i.reconnectReason&&(s.reconnectReason=i.reconnectReason);const r=new Hi({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}(e,a,i),d=""+function(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=function(t,e){const i=new URL(function(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}(t));return e.forEach(((t,e)=>{i.searchParams.set(e,t)})),ao(i,"rtc")}(t,e);return i?n:ao(n,"v1")}(t,c,r),h=""+function(t){return ao(new URL(Hr(t)),"validate")}(d);return new Promise(((t,e)=>hn(s,void 0,void 0,(function*(){var s,r;try{let o=!1;const a=t=>hn(this,void 0,void 0,(function*(){if(o)return;o=!0;const i=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(t instanceof AbortSignal))return e;const i=t.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:e;default:return"toString"in i?""+i:e}}(t instanceof Event?t.currentTarget:t,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then((()=>this.close(i))).catch((t=>{this.log.error(t),this.close()})):this.close(),c(),e(Ms.cancelled(i))}));null==n||n.addEventListener("abort",a);const c=()=>{clearTimeout(l),null==n||n.removeEventListener("abort",a)},l=setTimeout((()=>{a(Ms.timeout("room connection has timed out (signal)"))}),i.websocketTimeout),u=(t,e)=>{this.handleSignalConnected(t,l,e)},f=new URL(d);f.searchParams.has("access_token")&&f.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(f),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new So(d);try{this.ws.closed.then((t=>{var i;this.isEstablishingConnection&&e(Ms.internal("Websocket got closed during a (re)connection attempt: ".concat(t.reason))),1e3!==t.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:t.reason,code:t.closeCode,wasClean:1e3===t.closeCode,state:this.state})),this.state===Oo.CONNECTED&&this.handleOnClose(null!==(i=t.reason)&&void 0!==i?i:"Unexpected WS error"))})).catch((t=>{this.isEstablishingConnection&&e(Ms.internal("Websocket error during a (re)connection attempt: ".concat(t)))}));const n=yield this.ws.opened.catch((t=>hn(this,void 0,void 0,(function*(){if(this.state===Oo.CONNECTED)this.handleWSError(t),e(t);else{this.state=Oo.DISCONNECTED,clearTimeout(l);const i=yield this.handleConnectionError(t,h);e(i)}}))));if(clearTimeout(l),!n)return;const o=n.readable.getReader();this.streamWriter=n.writable.getWriter();const a=yield o.read();if(o.releaseLock(),!a.value)throw Ms.internal("no message received as first message");const c=co(a.value),d=this.validateFirstMessage(c,null!==(s=i.reconnect)&&void 0!==s&&s);if(!d.isValid)return void e(d.error);"join"===(null===(r=c.message)||void 0===r?void 0:r.case)&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}))),u(n,d.shouldProcessFirstMessage?c:void 0),t(d.response)}catch(t){e(t)}finally{c()}}finally{o()}}))))}()}))}startReadingLoop(t,e){return hn(this,void 0,void 0,(function*(){for(e&&this.handleSignalResponse(e);;){this.signalLatency&&(yield yr(this.signalLatency));const{done:e,value:i}=yield t.read();if(e)break;const n=co(i);this.handleSignalResponse(n)}}))}close(){return hn(this,arguments,void 0,(function(){var t=this;let e=!(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([Oo.DISCONNECTING||Oo.DISCONNECTED].includes(t.state))return void t.log.debug("ignoring signal close as it's already in disconnecting state");const n=yield t.closingLock.lock();try{if(t.clearPingInterval(),e&&(t.state=Oo.DISCONNECTING),t.ws){t.ws.close({closeCode:1e3,reason:i});const e=t.ws.closed;t.ws=void 0,t.streamWriter=void 0,yield Promise.race([e,yr(250)])}}catch(e){t.log.debug("websocket error while closing",Object.assign(Object.assign({},t.logContext),{error:e}))}finally{e&&(t.state=Oo.DISCONNECTED),n()}}()}))}sendOffer(t,e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:t.sdp})),this.sendRequest({case:"offer",value:Co(t,e)})}sendAnswer(t,e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:t.sdp})),this.sendRequest({case:"answer",value:Co(t,e)})}sendIceCandidate(t,e){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:t})),this.sendRequest({case:"trickle",value:new ni({candidateInit:JSON.stringify(t),target:e})})}sendMuteTrack(t,e){return this.sendRequest({case:"mute",value:new si({sid:t,muted:e})})}sendAddTrack(t){return this.sendRequest({case:"addTrack",value:t})}sendUpdateLocalMetadata(t,e){return hn(this,arguments,void 0,(function(t,e){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new bi({requestId:s,metadata:t,name:e,attributes:n})}),s}()}))}sendUpdateTrackSettings(t){this.sendRequest({case:"trackSetting",value:t})}sendUpdateSubscription(t){return this.sendRequest({case:"subscription",value:t})}sendSyncState(t){return this.sendRequest({case:"syncState",value:t})}sendUpdateVideoLayers(t,e){return this.sendRequest({case:"updateLayers",value:new gi({trackSid:t,layers:e})})}sendUpdateSubscriptionPermissions(t,e){return this.sendRequest({case:"subscriptionPermission",value:new Ri({allParticipants:t,trackPermissions:e})})}sendSimulateScenario(t){return this.sendRequest({case:"simulate",value:t})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:U.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Li({timestamp:U.parse(Date.now()),rtt:U.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(t,e){return this.sendRequest({case:"updateAudioTrack",value:new fi({trackSid:t,features:e})})}sendLeave(){return this.sendRequest({case:"leave",value:new mi({reason:ne.CLIENT_INITIATED,action:pi.DISCONNECT})})}sendRequest(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(t){const e=Eo.indexOf(t.case)>=0;return rn.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}(t);if(n&&e.state===Oo.RECONNECTING)return void e.queuedRequests.push((()=>hn(e,void 0,void 0,(function*(){yield this.sendRequest(t,!0)}))));if(i||(yield e.requestQueue.flush()),e.signalLatency&&(yield yr(e.signalLatency)),e.isDisconnected)return void e.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));if(!e.streamWriter)return void e.log.error("cannot send signal request before connected, type: ".concat(null==t?void 0:t.case),e.logContext);const s=new Xe({message:t});try{e.useJSON?yield e.streamWriter.write(s.toJsonString()):yield e.streamWriter.write(s.toBinary())}catch(t){e.log.error("error sending signal message",Object.assign(Object.assign({},e.logContext),{error:t}))}}()}))}handleSignalResponse(t){var e,i;const n=t.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const t=Ao(n.value);this.onAnswer&&this.onAnswer(t,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const t=Ao(n.value);this.onOffer&&this.onOffer(t,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){const t=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(t,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(e=n.value.participants)&&void 0!==e?e:[]):"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),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(n.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const t=this.queuedRequests.shift();t&&this.requestQueue.run(t)}}handleOnClose(t){return hn(this,void 0,void 0,(function*(){if(this.state===Oo.DISCONNECTED)return;const e=this.onClose;yield this.close(void 0,t),this.log.debug("websocket connection closed: ".concat(t),Object.assign(Object.assign({},this.logContext),{reason:t})),e&&e(t)}))}handleWSError(t){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:t}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Ws.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&Ws.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Ws.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Ws.clearInterval(this.pingInterval)}handleSignalConnected(t,e,i){this.state=Oo.CONNECTED,clearTimeout(e),this.startPingInterval(),this.startReadingLoop(t.readable.getReader(),i)}validateFirstMessage(t,e){var i,n,s,r,o;return"join"===(null===(i=t.message)||void 0===i?void 0:i.case)?{isValid:!0,response:t.message.value}:this.state===Oo.RECONNECTING&&"leave"!==(null===(n=t.message)||void 0===n?void 0:n.case)?"reconnect"===(null===(s=t.message)||void 0===s?void 0:s.case)?{isValid:!0,response:t.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&"leave"===(null===(r=t.message)||void 0===r?void 0:r.case)?{isValid:!1,error:Ms.leaveRequest("Received leave request while trying to (re)connect",t.message.value.reason)}:e?{isValid:!1,error:Ms.internal("Unexpected first message")}:{isValid:!1,error:Ms.internal("did not receive join response, got ".concat(null===(o=t.message)||void 0===o?void 0:o.case," instead"))}}handleConnectionError(t,e){return hn(this,void 0,void 0,(function*(){try{const i=yield fetch(e);switch(i.status){case 404:return Ms.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield i.text();return Ms.notAllowed(t,i.status)}return t instanceof Ms?t:Ms.internal("Encountered unknown websocket error during connection: ".concat(t),{status:i.status,statusText:i.statusText})}catch(t){return t instanceof Ms?t:Ms.serverUnreachable(t instanceof Error?t.message:"server was not reachable")}}))}}function Ao(t){const e={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=t.type}return e}function Co(t,e){return new di({sdp:t.sdp,type:t.type,id:e})}class _o{constructor(){this.buffer=[],this._totalSize=0}push(t){this.buffer.push(t),this._totalSize+=t.data.byteLength}pop(){const t=this.buffer.shift();return t&&(this._totalSize-=t.data.byteLength),t}getAll(){return this.buffer.slice()}popToSequence(t){for(;this.buffer.length>0&&this.buffer[0].sequence<=t;)this.pop()}alignBufferedAmount(t){for(;this.buffer.length>0&&!(this._totalSize-this.buffer[0].data.byteLength<=t);)this.pop()}get length(){return this.buffer.length}}class Io{constructor(t){this._map=new Map,this._lastCleanup=0,this.ttl=t}set(t,e){const i=Date.now();return i-this._lastCleanup>this.ttl/2&&this.cleanup(),this._map.set(t,{value:e,expiresAt:i+this.ttl}),this}get(t){const e=this._map.get(t);if(e){if(!(e.expiresAt<Date.now()))return e.value;this._map.delete(t)}}has(t){const e=this._map.get(t);return!(!e||e.expiresAt<Date.now()&&(this._map.delete(t),1))}delete(t){return this._map.delete(t)}clear(){this._map.clear()}cleanup(){const t=Date.now();for(const[e,i]of this._map.entries())i.expiresAt<t&&this._map.delete(e);this._lastCleanup=t}get size(){return this.cleanup(),this._map.size}forEach(t){this.cleanup();for(const[e,i]of this._map.entries())i.expiresAt>=Date.now()&&t(i.value,e,this.asValueMap())}map(t){this.cleanup();const e=[],i=this.asValueMap();for(const[n,s]of i.entries())e.push(t(s,n,i));return e}asValueMap(){const t=new Map;for(const[e,i]of this._map.entries())i.expiresAt>=Date.now()&&t.set(e,i.value);return t}}var Ro,jo,Po,Do,Mo,No={},Uo={},Lo={exports:{}};function Bo(){if(Ro)return Lo.exports;Ro=1;var t=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(t){return t.encoding?"rtpmap:%d %s/%s/%s":t.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(t){return null!=t.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(t){return null!=t.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(t){return"extmap:%d"+(t.direction?"/%s":"%v")+(t["encrypt-uri"]?" %s":"%v")+" %s"+(t.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(t){return null!=t.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(t){var e="candidate:%s %d %s %d %s %d typ %s";return e+=null!=t.raddr?" raddr %s rport %d":"%v%v",e+=null!=t.tcptype?" tcptype %s":"%v",null!=t.generation&&(e+=" generation %d"),(e+=null!=t["network-id"]?" network-id %d":"%v")+(null!=t["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(t){var e="ssrc:%d";return null!=t.attribute&&(e+=" %s",null!=t.value&&(e+=":%s")),e}},{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(t){return null!=t.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(t){return t.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(t){return"imageattr:%s %s %s"+(t.dir2?" %s %s":"")}},{name:"simulcast",reg:RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(t){return"simulcast:%s %s"+(t.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(t){return"ts-refclk:%s"+(null!=t.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(t){var e="mediaclk:";return e+=null!=t.id?"id=%s %s":"%v%s",e+=null!=t.mediaClockValue?"=%s":"",(e+=null!=t.rateNumerator?" rate=%s":"")+(null!=t.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(t).forEach((function(e){t[e].forEach((function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")}))})),Lo.exports}function Fo(){return jo||(jo=1,function(t){var e=function(t){return Number(t)+""===t?Number(t):t},i=function(t,i,n){var s=t.name&&t.names;t.push&&!i[t.push]?i[t.push]=[]:s&&!i[t.name]&&(i[t.name]={});var r=t.push?{}:s?i[t.name]:i;!function(t,i,n,s){if(s&&!n)i[s]=e(t[1]);else for(var r=0;r<n.length;r+=1)null!=t[r+1]&&(i[n[r]]=e(t[r+1]))}(n.match(t.reg),r,t.names,t.name),t.push&&i[t.push].push(r)},n=Bo(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(t){var e={},r=[],o=e;return t.split(/(\r\n|\r|\n)/).filter(s).forEach((function(t){var e=t[0],s=t.slice(2);"m"===e&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[e]||[]).length;a+=1){var c=n[e][a];if(c.reg.test(s))return i(c,o,s)}})),e.media=r,e};var r=function(t,i){var n=i.split(/=(.+)/,2);return 2===n.length?t[n[0]]=e(n[1]):1===n.length&&i.length>1&&(t[n[0]]=void 0),t};t.parseParams=function(t){return t.split(/;\s?/).reduce(r,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(t){return(""+t).split(" ").map(Number)},t.parseRemoteCandidates=function(t){for(var i=[],n=t.split(" ").map(e),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},t.parseImageAttributes=function(t){return t.split(" ").map((function(t){return t.substring(1,t.length-1).split(",").reduce(r,{})}))},t.parseSimulcastStreamList=function(t){return t.split(";").map((function(t){return t.split(",").map((function(t){var i,n=!1;return"~"!==t[0]?i=e(t):(i=e(t.substring(1,t.length)),n=!0),{scid:i,paused:n}}))}))}}(Uo)),Uo}function Vo(){if(Do)return Po;Do=1;var t=Bo(),e=/%[sdv%]/g,i=function(t){var i=1,n=arguments,s=n.length;return t.replace(e,(function(t){if(i>=s)return t;var e=n[i];switch(i+=1,t){case"%%":return"%";case"%s":return e+"";case"%d":return Number(e);case"%v":return""}}))},n=function(t,e,n){var s=[t+"="+(e.format instanceof Function?e.format(e.push?n:n[e.name]):e.format)];if(e.names)for(var r=0;r<e.names.length;r+=1)s.push(e.name?n[e.name][e.names[r]]:n[e.names[r]]);else s.push(n[e.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Po=function(e,i){i=i||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(t){null==t.payloads&&(t.payloads="")}));var o=i.innerOrder||r,a=[];return(i.outerOrder||s).forEach((function(i){t[i].forEach((function(t){t.name in e&&null!=e[t.name]?a.push(n(i,t,e)):t.push in e&&null!=e[t.push]&&e[t.push].forEach((function(e){a.push(n(i,t,e))}))}))})),e.media.forEach((function(e){a.push(n("m",t.m[0],e)),o.forEach((function(i){t[i].forEach((function(t){t.name in e&&null!=e[t.name]?a.push(n(i,t,e)):t.push in e&&null!=e[t.push]&&e[t.push].forEach((function(e){a.push(n(i,t,e))}))}))}))})),a.join("\r\n")+"\r\n"},Po}var qo=function(){if(Mo)return No;Mo=1;var t=Fo(),e=Vo(),i=Bo();return No.grammar=i,No.write=e,No.parse=t.parse,No.parseParams=t.parseParams,No.parseFmtpConfig=t.parseFmtpConfig,No.parsePayloads=t.parsePayloads,No.parseRemoteCandidates=t.parseRemoteCandidates,No.parseImageAttributes=t.parseImageAttributes,No.parseSimulcastStreamList=t.parseSimulcastStreamList,No}();function zo(t,e,i){var n,s,r;void 0===e&&(e=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),h=[];function l(){if(void 0!==c){var t=Date.now()-d;if(t+e>=c)return c-t}return e}var u=function(){var e=[].slice.call(arguments),i=this;return new Promise((function(n,s){var c=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!o){var n=t.apply(i,e);a&&a(n),h.forEach((function(t){return(0,t.resolve)(n)})),h=[]}}),l()),c){var u=t.apply(i,e);return a&&a(u),n(u)}h.push({resolve:n,reject:s})}))};return u.cancel=function(t){void 0!==r&&clearTimeout(r),h.forEach((function(e){return(0,e.reject)(t)})),h=[]},u}const Jo="negotiationStarted",Wo="negotiationComplete",Go="rtpVideoPayloadTypes";class Qo extends vn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=rn,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=zo((t=>hn(this,void 0,void 0,(function*(){this.emit(Jo);try{yield this.createAndSendOffer()}catch(e){if(!t)throw e;t(e)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=on(null!==(i=e.loggerName)&&void 0!==i?i:tn.PCTransport),this.loggerOptions=e,this.config=t,this._pc=this.createPC(),this.offerLock=new u}createPC(){const t=new RTCPeerConnection(this.config);return t.onicecandidate=t=>{var e;t.candidate&&(null===(e=this.onIceCandidate)||void 0===e||e.call(this,t.candidate))},t.onicecandidateerror=t=>{var e;null===(e=this.onIceCandidateError)||void 0===e||e.call(this,t)},t.oniceconnectionstatechange=()=>{var e;null===(e=this.onIceConnectionStateChange)||void 0===e||e.call(this,t.iceConnectionState)},t.onsignalingstatechange=()=>{var e;null===(e=this.onSignalingStatechange)||void 0===e||e.call(this,t.signalingState)},t.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,t.connectionState)},t.ondatachannel=t=>{var e;null===(e=this.onDataChannel)||void 0===e||e.call(this,t)},t.ontrack=t=>{var e;null===(e=this.onTrack)||void 0===e||e.call(this,t)},t}get logContext(){var t,e;return Object.assign({},null===(e=(t=this.loggerOptions).loggerContextCb)||void 0===e?void 0:e.call(t))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(t){return hn(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(t);this.pendingCandidates.push(t)}))}setRemoteDescription(t,e){return hn(this,void 0,void 0,(function*(){var i;if("answer"===t.type&&this.latestOfferId>0&&e>0&&e!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:e,latestOfferId:this.latestOfferId})),!1;let n;if("offer"===t.type){let{stereoMids:e,nackMids:i}=function(t){var e;const i=[],n=[],s=qo.parse(null!==(e=t.sdp)&&void 0!==e?e:"");let r=0;return s.media.forEach((t=>{var e;const s=Yo(t.mid);"audio"===t.type&&(t.rtp.some((t=>"opus"===t.codec&&(r=t.payload,!0))),(null===(e=t.rtcpFb)||void 0===e?void 0:e.some((t=>t.payload===r&&"nack"===t.type)))&&n.push(s),t.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(s),!0))))})),{stereoMids:i,nackMids:n}}(t);this.remoteStereoMids=e,this.remoteNackMids=i}else if("answer"===t.type){const e=qo.parse(null!==(i=t.sdp)&&void 0!==i?i:"");e.media.forEach((t=>{const e=Yo(t.mid);"audio"===t.type&&this.trackBitrates.some((i=>{if(!i.transceiver||e!=i.transceiver.mid)return!1;let n=0;if(t.rtp.some((t=>t.codec.toUpperCase()===i.codec.toUpperCase()&&(n=t.payload,!0))),0===n)return!0;let s=!1;for(const e of t.fmtp)if(e.payload===n){e.config=e.config.split(";").filter((t=>!t.includes("maxaveragebitrate"))).join(";"),i.maxbr>0&&(e.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),s=!0;break}return s||i.maxbr>0&&t.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0}))})),n=qo.write(e)}return yield this.setMungedSDP(t,n,!0),this.pendingCandidates.forEach((t=>{this.pc.addIceCandidate(t)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===t.type&&(this.emit(Wo),t.sdp)&&qo.parse(t.sdp).media.forEach((t=>{"video"===t.type&&this.emit(Go,t.rtp)})),!0}))}createAndSendOffer(t){return hn(this,void 0,void 0,(function*(){var e;const i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==t?void 0:t.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const e=this._pc.remoteDescription;if(!(null==t?void 0:t.iceRestart)||!e)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(e)}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(t);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=qo.parse(null!==(e=n.sdp)&&void 0!==e?e:"");if(s.media.forEach((t=>{Ko(t),"audio"===t.type?Ho(t,["all"],[]):"video"===t.type&&this.trackBitrates.some((e=>{if(!t.msid||!e.cid||!t.msid.includes(e.cid))return!1;let i=0;if(t.rtp.some((t=>t.codec.toUpperCase()===e.codec.toUpperCase()&&(i=t.payload,!0))),0===i)return!0;if(Tr(e.codec)&&!xr()&&this.ensureVideoDDExtensionForSVC(t,s),!Tr(e.codec))return!0;const n=Math.round(.7*e.maxbr);for(const e of t.fmtp)if(e.payload===i){e.config.includes("x-google-start-bitrate")||(e.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,qo.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}}))}createAndSetAnswer(){return hn(this,void 0,void 0,(function*(){var t;const e=yield this.pc.createAnswer(),i=qo.parse(null!==(t=e.sdp)&&void 0!==t?t:"");return i.media.forEach((t=>{Ko(t),"audio"===t.type&&Ho(t,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(e,qo.write(i)),e}))}createDataChannel(t,e){return this.pc.createDataChannel(t,e)}addTransceiver(t,e){return this.pc.addTransceiver(t,e)}addTransceiverOfKind(t,e){return this.pc.addTransceiver(t,e)}addTrack(t){if(!this._pc)throw new Bs("PC closed, cannot add track");return this._pc.addTrack(t)}setTrackCodecBitrate(t){this.trackBitrates.push(t)}setConfiguration(t){var e;if(!this._pc)throw new Bs("PC closed, cannot configure");return null===(e=this._pc)||void 0===e?void 0:e.setConfiguration(t)}canRemoveTrack(){var t;return!!(null===(t=this._pc)||void 0===t?void 0:t.removeTrack)}removeTrack(t){var e;return null===(e=this._pc)||void 0===e?void 0:e.removeTrack(t)}getConnectionState(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.connectionState)&&void 0!==e?e:"closed"}getICEConnectionState(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.iceConnectionState)&&void 0!==e?e:"closed"}getSignallingState(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.signalingState)&&void 0!==e?e:"closed"}getTransceivers(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.getTransceivers())&&void 0!==e?e:[]}getSenders(){var t,e;return null!==(e=null===(t=this._pc)||void 0===t?void 0:t.getSenders())&&void 0!==e?e:[]}getLocalDescription(){var t;return null===(t=this._pc)||void 0===t?void 0:t.localDescription}getRemoteDescription(){var t;return null===(t=this.pc)||void 0===t?void 0:t.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return hn(this,void 0,void 0,(function*(){var t;if(!this._pc)return;let e="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach((t=>{switch(t.type){case"transport":e=t.selectedCandidatePairId;break;case"candidate-pair":""===e&&t.selected&&(e=t.id),i.set(t.id,t);break;case"remote-candidate":n.set(t.id,"".concat(t.address,":").concat(t.port))}})),""===e)return;const s=null===(t=i.get(e))||void 0===t?void 0:t.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(t,e,i){return hn(this,void 0,void 0,(function*(){if(e){const n=t.sdp;t.sdp=e;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(t):yield this.pc.setLocalDescription(t))}catch(i){this.log.warn("not able to set ".concat(t.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:e})),t.sdp=n}}try{i?yield this.pc.setRemoteDescription(t):yield this.pc.setLocalDescription(t)}catch(e){let n="unknown error";e instanceof Error?n=e.message:"string"==typeof e&&(n=e);const s={error:n,sdp:t.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(t.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Fs(n)}}))}ensureVideoDDExtensionForSVC(t,e){var i,n;if(!(null===(i=t.ext)||void 0===i?void 0:i.some((t=>t.uri===br)))){if(0===this.ddExtID){let t=0;e.media.forEach((e=>{var i;"video"===e.type&&(null===(i=e.ext)||void 0===i||i.forEach((e=>{e.value>t&&(t=e.value)})))})),this.ddExtID=t+1}null===(n=t.ext)||void 0===n||n.push({value:this.ddExtID,uri:br})}}}function Ho(t,e,i){const n=Yo(t.mid);let s=0;t.rtp.some((t=>"opus"===t.codec&&(s=t.payload,!0))),s>0&&(t.rtcpFb||(t.rtcpFb=[]),i.includes(n)&&!t.rtcpFb.some((t=>t.payload===s&&"nack"===t.type))&&t.rtcpFb.push({payload:s,type:"nack"}),(e.includes(n)||1===e.length&&"all"===e[0])&&t.fmtp.some((t=>t.payload===s&&(t.config.includes("stereo=1")||(t.config+=";stereo=1"),!0))))}function Ko(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(4===t.connection.version&&e||6===t.connection.version&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}function Yo(t){return"number"==typeof t?t.toFixed(0):t}const Zo="vp8",$o={audioPreset:$s.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:er.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Zo,backupCodec:!0,preConnectBuffer:!1},Xo={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ta={deviceId:{ideal:"default"},resolution:Xs.h720.resolution},ea={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(t){this._retryDelays=void 0!==t?[...t]:dn}nextRetryDelayInMs(t){if(t.retryCount>=this._retryDelays.length)return null;const e=this._retryDelays[t.retryCount];return t.retryCount<=1?e:e+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},ia={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var na;!function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"}(na||(na={}));class sa{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(t,e,i){var n;this.peerConnectionTimeout=ia.peerConnectionTimeout,this.log=rn,this.updateState=()=>{var t,e;const i=this.state,n=this.requiredTransports.map((t=>t.getConnectionState()));n.every((t=>"connected"===t))?this.state=na.CONNECTED:n.some((t=>"failed"===t))?this.state=na.FAILED:n.some((t=>"connecting"===t))?this.state=na.CONNECTING:n.every((t=>"closed"===t))?this.state=na.CLOSED:n.some((t=>"closed"===t))?this.state=na.CLOSING:n.every((t=>"new"===t))&&(this.state=na.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(na[i]," to ").concat(na[this.state]),this.logContext),null===(t=this.onStateChange)||void 0===t||t.call(this,this.state,this.publisher.getConnectionState(),null===(e=this.subscriber)||void 0===e?void 0:e.getConnectionState()))},this.log=on(null!==(n=i.loggerName)&&void 0!==n?n:tn.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==e,this.isSubscriberConnectionRequired="subscriber-primary"===e,this.publisher=new Qo(t,i),this._mode=e,"publisher-only"!==e&&(this.subscriber=new Qo(t,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=t=>{var e;null===(e=this.onIceCandidate)||void 0===e||e.call(this,t,Ye.SUBSCRIBER)},this.subscriber.onDataChannel=t=>{var e;null===(e=this.onDataChannel)||void 0===e||e.call(this,t)},this.subscriber.onTrack=t=>{var e;null===(e=this.onTrack)||void 0===e||e.call(this,t)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=t=>{var e;null===(e=this.onIceCandidate)||void 0===e||e.call(this,t,Ye.PUBLISHER)},this.publisher.onTrack=t=>{var e;null===(e=this.onTrack)||void 0===e||e.call(this,t)},this.publisher.onOffer=(t,e)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,t,e)},this.state=na.NEW,this.connectionLock=new u,this.remoteOfferLock=new u}get logContext(){var t,e;return Object.assign({},null===(e=(t=this.loggerOptions).loggerContextCb)||void 0===e?void 0:e.call(t))}requirePublisher(){this.isPublisherConnectionRequired=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],this.updateState()}createAndSendPublisherOffer(t){return this.publisher.createAndSendOffer(t)}setPublisherAnswer(t,e){return this.publisher.setRemoteDescription(t,e)}removeTrack(t){return this.publisher.removeTrack(t)}close(){return hn(this,void 0,void 0,(function*(){var t;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const t=this.publisher;for(const e of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(e)}catch(t){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:t}))}}yield Promise.all([this.publisher.close(),null===(t=this.subscriber)||void 0===t?void 0:t.close()]),this.updateState()}))}triggerIceRestart(){return hn(this,void 0,void 0,(function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(t,e){return hn(this,void 0,void 0,(function*(){var i;e===Ye.PUBLISHER?yield this.publisher.addIceCandidate(t):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(t)}))}createSubscriberAnswerFromOffer(t,e){return hn(this,void 0,void 0,(function*(){var i,n,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:t.type,sdp:t.sdp,signalingState:null===(i=this.subscriber)||void 0===i?void 0:""+i.getSignallingState()}));const r=yield this.remoteOfferLock.lock();try{if(!(yield null===(n=this.subscriber)||void 0===n?void 0:n.setRemoteDescription(t,e)))return;return yield null===(s=this.subscriber)||void 0===s?void 0:s.createAndSetAnswer()}finally{r()}}))}updateConfiguration(t,e){var i;this.publisher.setConfiguration(t),null===(i=this.subscriber)||void 0===i||i.setConfiguration(t),e&&this.triggerIceRestart()}ensurePCTransportConnection(t,e){return hn(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,t,e))))}finally{n()}}))}negotiate(t){return hn(this,void 0,void 0,(function*(){return new ws(((e,i)=>hn(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i(new Fs("negotiation timed out"))}),this.peerConnectionTimeout);t.signal.addEventListener("abort",(()=>{clearTimeout(n),i(new Fs("negotiation aborted"))})),this.publisher.once(Jo,(()=>{t.signal.aborted||this.publisher.once(Wo,(()=>{clearTimeout(n),e()}))})),yield this.publisher.negotiate((t=>{clearTimeout(n),i(t instanceof Error?t:Error(t+""))}))}))))}))}addPublisherTransceiver(t,e){return this.publisher.addTransceiver(t,e)}addPublisherTransceiverOfKind(t,e){return this.publisher.addTransceiverOfKind(t,e)}getMidForReceiver(t){const e=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find((e=>e.receiver===t));return null==e?void 0:e.mid}addPublisherTrack(t){return this.publisher.addTrack(t)}createPublisherDataChannel(t,e){return this.publisher.createDataChannel(t,e)}getConnectedAddress(t){return t===Ye.PUBLISHER||t===Ye.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const t=[];return this.isPublisherConnectionRequired&&t.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&t.push(this.subscriber),t}ensureTransportConnected(t,e){return hn(this,arguments,void 0,(function(t,e){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==t.getConnectionState())return new Promise(((t,s)=>hn(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Ws.clearTimeout(r),s(Ms.cancelled("room connection has been cancelled"))};(null==e?void 0:e.signal.aborted)&&i(),null==e||e.signal.addEventListener("abort",i);const r=Ws.setTimeout((()=>{null==e||e.signal.removeEventListener("abort",i),s(Ms.internal("could not establish pc connection"))}),n);for(;this.state!==na.CONNECTED;)if(yield yr(50),null==e?void 0:e.signal.aborted)return void s(Ms.cancelled("room connection has been cancelled"));Ws.clearTimeout(r),null==e||e.signal.removeEventListener("abort",i),t()}))))}()}))}}class ra{static fetchRegionSettings(t,e,i){return hn(this,void 0,void 0,(function*(){const n=yield ra.fetchLock.lock();try{const n=yield fetch("".concat(function(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}(t),"/regions"),{headers:{authorization:"Bearer ".concat(e)},signal:i});if(n.ok){const t=function(t){var e;const i=t.get("Cache-Control");if(i){const t=null===(e=i.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===e?void 0:e[1];if(t)return parseInt(t,10)}}(n.headers),e=t?1e3*t:5e3;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:e}}throw 401===n.status?Ms.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):Ms.internal("Could not fetch region settings: ".concat(n.statusText))}catch(t){throw t instanceof Ms?t:(null==i?void 0:i.aborted)?Ms.cancelled("Region fetching was aborted"):Ms.serverUnreachable("Could not fetch region settings, ".concat(t instanceof Error?"".concat(t.name,": ").concat(t.message):t))}finally{n()}}))}static scheduleRefetch(t,e,i){return hn(this,void 0,void 0,(function*(){const n=ra.settingsTimeouts.get(t.hostname);clearTimeout(n),ra.settingsTimeouts.set(t.hostname,setTimeout((()=>hn(this,void 0,void 0,(function*(){try{const i=yield ra.fetchRegionSettings(t,e);ra.updateCachedRegionSettings(t,e,i)}catch(n){if(n instanceof Ms&&n.reason===Cs.NotAllowed)return void rn.debug("token is not valid, cancelling auto region refresh");rn.debug("auto refetching of region settings failed",{error:n}),ra.scheduleRefetch(t,e,i)}}))),i))}))}static updateCachedRegionSettings(t,e,i){ra.cache.set(t.hostname,i),ra.scheduleRefetch(t,e,i.maxAgeInMs)}static stopRefetch(t){const e=ra.settingsTimeouts.get(t);e&&(clearTimeout(e),ra.settingsTimeouts.delete(t))}static scheduleCleanup(t){let e=ra.connectionTrackers.get(t);e&&(e.cleanupTimeout&&clearTimeout(e.cleanupTimeout),e.cleanupTimeout=setTimeout((()=>{const e=ra.connectionTrackers.get(t);e&&0===e.connectionCount&&(rn.debug("stopping region refetch after disconnect delay",{hostname:t}),ra.stopRefetch(t)),e&&(e.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(t){const e=ra.connectionTrackers.get(t);(null==e?void 0:e.cleanupTimeout)&&(clearTimeout(e.cleanupTimeout),e.cleanupTimeout=void 0)}notifyConnected(){const t=this.serverUrl.hostname;let e=ra.connectionTrackers.get(t);e||(e={connectionCount:0},ra.connectionTrackers.set(t,e)),e.connectionCount++,ra.cancelCleanup(t)}notifyDisconnected(){const t=this.serverUrl.hostname,e=ra.connectionTrackers.get(t);e&&(e.connectionCount=Math.max(0,e.connectionCount-1),0===e.connectionCount&&ra.scheduleCleanup(t))}constructor(t,e){this.attemptedRegions=[],this.serverUrl=new URL(t),this.token=e}updateToken(t){this.token=t}isCloud(){return Rr(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return hn(this,void 0,void 0,(function*(){return ra.fetchRegionSettings(this.serverUrl,this.token,t)}))}getNextBestRegionUrl(t){return hn(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let e=ra.cache.get(this.serverUrl.hostname);(!e||Date.now()-e.updatedAtInMs>e.maxAgeInMs)&&(e=yield this.fetchRegionSettings(t),ra.updateCachedRegionSettings(this.serverUrl,this.token,e));const i=e.regionSettings.regions.filter((t=>!this.attemptedRegions.find((e=>e.url===t.url))));if(i.length>0){const t=i[0];return this.attemptedRegions.push(t),rn.debug("next region: ".concat(t.region)),t.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){ra.updateCachedRegionSettings(this.serverUrl,this.token,t)}}ra.cache=new Map,ra.settingsTimeouts=new Map,ra.connectionTrackers=new Map,ra.fetchLock=new u;class oa extends Error{constructor(t,e,i){super(e),this.code=t,this.message=ca(e,oa.MAX_MESSAGE_BYTES),this.data=i?ca(i,oa.MAX_DATA_BYTES):void 0}static fromProto(t){return new oa(t.code,t.message,t.data)}toProto(){return new Pe({code:this.code,message:this.message,data:this.data})}static builtIn(t,e){return new oa(oa.ErrorCode[t],oa.ErrorMessage[t],e)}}function aa(t){return(new TextEncoder).encode(t).length}function ca(t,e){if(aa(t)<=e)return t;let i=0,n=t.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(t.slice(0,r)).length<=e?i=r:n=r-1}return t.slice(0,i)}oa.MAX_MESSAGE_BYTES=256,oa.MAX_DATA_BYTES=15360,oa.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},oa.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 da=2e3;function ha(t,e){if(!e)return 0;let i,n;return"bytesReceived"in t?(i=t.bytesReceived,n=e.bytesReceived):"bytesSent"in t&&(i=t.bytesSent,n=e.bytesSent),void 0===i||void 0===n||void 0===t.timestamp||void 0===e.timestamp?0:8*(i-n)*1e3/(t.timestamp-e.timestamp)}const la="undefined"!=typeof MediaRecorder,ua=la?MediaRecorder:class{constructor(){throw Error("MediaRecorder is not available in this environment")}};class fa extends ua{constructor(t,e){if(!la)throw Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([t.mediaStreamTrack]),e);const s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),null==n||n.close(),n=void 0},r=t=>{null==n||n.error(t),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),n=void 0};this.byteStream=new ReadableStream({start:t=>{n=t,i=e=>hn(this,void 0,void 0,(function*(){let i;if(e.data.arrayBuffer){const t=yield e.data.arrayBuffer();i=new Uint8Array(t)}else{if(!e.data.byteArray)throw Error("no data available!");i=e.data.byteArray}void 0!==n&&t.enqueue(i)})),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",r)}}class va extends mr{get sender(){return this._sender}set sender(t){this._sender=t}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,e,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=zo((()=>hn(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>hn(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(Ds.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new u,this.pauseUpstreamLock=new u,this.trackChangeLock=new u,this.trackChangeLock.lock().then((e=>hn(this,void 0,void 0,(function*(){try{yield this.setMediaStreamTrack(t,!0)}finally{e()}})))),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==mr.Kind.Video)return;const{width:t,height:e}=this._mediaStreamTrack.getSettings();return t&&e?{width:t,height:e}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var t,e;return null!==(e=null===(t=this.processor)||void 0===t?void 0:t.processedTrack)&&void 0!==e?e:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(t,e){return hn(this,void 0,void 0,(function*(){var i;if(t===this._mediaStreamTrack&&!e)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((t=>{gr(this._mediaStreamTrack,t)})),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([t]),t&&(t.addEventListener("ended",this.handleEnded),t.addEventListener("mute",this.handleTrackMuteEvent),t.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=t.getConstraints()),this.processor&&t){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(pr(t,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:t,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:t)),this.providedByUser||this._mediaStreamTrack===t||this._mediaStreamTrack.stop(),this._mediaStreamTrack=t,t&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((e=>{pr(null!=n?n:t,e)})))}))}waitForDimensions(){return hn(this,arguments,void 0,(function(){var t=this;let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(t.kind===mr.Kind.Audio)throw Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=Ss())||void 0===i?void 0:i.os)&&(yield yr(10));const n=Date.now();for(;Date.now()-n<e;){const e=t.dimensions;if(e)return e;yield yr(50)}throw new Us("unable to get track dimensions after timeout")}()}))}setDeviceId(t){return hn(this,void 0,void 0,(function*(){return this._constraints.deviceId===t&&this._mediaStreamTrack.getSettings().deviceId===Qr(t)||(this._constraints.deviceId=t,!!this.isMuted||(yield this.restartTrack(),Qr(t)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return hn(this,arguments,void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(t.source===mr.Source.ScreenShare)return;const{deviceId:i,groupId:n}=t._mediaStreamTrack.getSettings(),s=t.kind===mr.Kind.Audio?"audioinput":"videoinput";return e?wo.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return hn(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return hn(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(t,e){return hn(this,void 0,void 0,(function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Us("unable to replace an unpublished track");let i,n;return"boolean"==typeof e?i=e:void 0!==e&&(i=e.userProvidedTrack,n=e.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(t),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}}))}restart(t){return hn(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const e=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const{deviceId:e,facingMode:i}=t,n=function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const s={audio:!1,video:!1};this.kind===mr.Kind.Video?s.video=!e&&!i||{deviceId:e,facingMode:i}:s.audio=!e||Object.assign({deviceId:e},n),this.attachedElements.forEach((t=>{gr(this.mediaStreamTrack,t)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===mr.Kind.Video&&(yield r.applyConstraints(n)),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=t,this.emit(Ds.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{e()}}))}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?Ds.Muted:Ds.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return hn(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),Cr()&&(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 t;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(t=this.processor)||void 0===t||t.destroy(),this.processor=void 0}pauseUpstream(){return hn(this,void 0,void 0,(function*(){var t;const e=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(Ds.UpstreamPaused,this);const e=Ss();if("Safari"===(null==e?void 0:e.name)&&Nr(e.version,"12.0")<0)throw new Ns("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(null))}finally{e()}}))}resumeUpstream(){return hn(this,void 0,void 0,(function*(){var t;const e=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(Ds.UpstreamResumed,this),"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}}))}getRTCStatsReport(){return hn(this,void 0,void 0,(function*(){var t;if(null===(t=this.sender)||void 0===t?void 0:t.getStats)return yield this.sender.getStats()}))}setProcessor(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield e.trackChangeLock.lock();try{e.log.debug("setting up processor",e.logContext);const s=document.createElement(e.kind),r={kind:e.kind,track:e._mediaStreamTrack,element:s,audioContext:e.audioContext};if(yield t.init(r),e.log.debug("processor initialized",e.logContext),e.processor&&(yield e.internalStopProcessor()),"unknown"===e.kind)throw TypeError("cannot set processor on track of unknown kind");if(pr(e._mediaStreamTrack,s),s.muted=!0,s.play().catch((t=>{t instanceof DOMException&&"AbortError"===t.name?(e.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},e.logContext),{error:t})),setTimeout((()=>{s.play().catch((t=>{e.log.error("failed to play processor element",Object.assign(Object.assign({},e.logContext),{err:t}))}))}),100)):e.log.error("failed to play processor element",Object.assign(Object.assign({},e.logContext),{error:t}))})),e.processor=t,e.processorElement=s,e.processor.processedTrack){for(const t of e.attachedElements)t!==e.processorElement&&i&&(gr(e._mediaStreamTrack,t),pr(e.processor.processedTrack,t));yield null===(n=e.sender)||void 0===n?void 0:n.replaceTrack(e.processor.processedTrack)}e.emit(Ds.TrackProcessorUpdate,e.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return hn(this,arguments,void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield t.trackChangeLock.lock();try{yield t.internalStopProcessor(e)}finally{i()}}()}))}internalStopProcessor(){return hn(this,arguments,void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;t.processor&&(t.log.debug("stopping processor",t.logContext),null===(i=t.processor.processedTrack)||void 0===i||i.stop(),yield t.processor.destroy(),t.processor=void 0,e||(null===(n=t.processorElement)||void 0===n||n.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(Ds.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(la)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new fa(this,{mimeType:t})}this.localTrackRecorder.start(t),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 t;return null===(t=this.localTrackRecorder)||void 0===t?void 0:t.byteStream}getPreConnectBufferMimeType(){var t;return null===(t=this.localTrackRecorder)||void 0===t?void 0:t.mimeType}}class ma extends va{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,e){let i=arguments.length>3?arguments[3]:void 0;super(t,mr.Kind.Audio,e,!(arguments.length>2&&void 0!==arguments[2])||arguments[2],arguments.length>4?arguments[4]:void 0),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>hn(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}t&&this.prevStats&&(this._currentBitrate=ha(t,this.prevStats)),this.prevStats=t})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Ds.AudioTrackFeatureUpdate,this,oe.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Ds.AudioTrackFeatureUpdate,this,oe.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return hn(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===mr.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield t.mute.call(this),this)}finally{e()}}))}unmute(){const t=Object.create(null,{unmute:{get:()=>super.unmute}});return hn(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const e=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Qr(this._constraints.deviceId);return this.source!==mr.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!e||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield t.unmute.call(this),this}finally{e()}}))}restartTrack(t){return hn(this,void 0,void 0,(function*(){let e;if(t){const i=sr({audio:t});"boolean"!=typeof i.audio&&(e=i.audio)}yield this.restart(e)}))}restart(t){const e=Object.create(null,{restart:{get:()=>super.restart}});return hn(this,void 0,void 0,(function*(){const i=yield e.restart.call(this,t);return this.checkForSilence(),i}))}startMonitor(){_r()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),da)))}setProcessor(t){return hn(this,void 0,void 0,(function*(){var e;const i=yield this.trackChangeLock.lock();try{if(!Ir()&&!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};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(i),this.processor=t,this.processor.processedTrack&&(yield null===(e=this.sender)||void 0===e?void 0:e.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(Ds.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(t){this.audioContext=t}getSenderStats(){return hn(this,void 0,void 0,(function*(){var t;if(!(null===(t=this.sender)||void 0===t?void 0:t.getStats))return;let e;return(yield this.sender.getStats()).forEach((t=>{"outbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,packetsSent:t.packetsSent,packetsLost:t.packetsLost,bytesSent:t.bytesSent,timestamp:t.timestamp,roundTripTime:t.roundTripTime,jitter:t.jitter})})),e}))}checkForSilence(){return hn(this,void 0,void 0,(function*(){const t=yield function(t){return hn(this,arguments,void 0,(function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=rr();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([t.mediaStreamTrack])).connect(n),yield yr(e),n.getByteTimeDomainData(s);const r=s.some((t=>128!==t&&0!==t));return i.close(),!r}return!1}()}))}(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(Ds.AudioSilenceDetected)),t}))}}const pa=Object.values(Xs),ga=Object.values(tr),ba=Object.values(er),ya=[Xs.h180,Xs.h360],wa=[tr.h180,tr.h360],ka=["q","h","f"];function Ta(t,e,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;t&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!e||!i)return[{}];o||(o=function(t,e,i,n){const s=function(t,e,i){if(t)return ba;const n=e>i?e/i:i/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?pa:ga}(t,e,i);let{encoding:r}=s[0];const o=Math.max(e,i);for(let t=0;t<s.length;t+=1){const e=s[t];if(r=e.encoding,e.width>=o)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(t,e,i,d),rn.debug("using video encoding",o));const h=o.maxFramerate,l=new Qs(e,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Tr(d)){const t=new xa(c),e=[];if(t.spatial>3)throw Error("unsupported scalabilityMode: ".concat(c));const i=Ss();if(Ar()||Ir()||"Chrome"===(null==i?void 0:i.name)&&Nr(null==i?void 0:i.version,"113")<0){const n="h"==t.suffix?2:3,s=function(t){return t||(t=Ss()),"Safari"===(null==t?void 0:t.name)&&Nr(t.version,"18.3")>0||"iOS"===(null==t?void 0:t.os)&&!!(null==t?void 0:t.osVersion)&&Nr(t.osVersion,"18.3")>0}(i);for(let i=0;i<t.spatial;i+=1)e.push({rid:ka[2-i],maxBitrate:o.maxBitrate/Math.pow(n,i),maxFramerate:l.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,i):void 0});e[0].scalabilityMode=c}else e.push({maxBitrate:o.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:c});return l.encoding.priority&&(e[0].priority=l.encoding.priority,e[0].networkPriority=l.encoding.priority),rn.debug("using svc encoding",{encodings:e}),e}if(!a)return[o];let u,f=[];if(f=t?null!==(s=Oa(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:Sa(t,l):null!==(r=Oa(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:Sa(t,l),f.length>0){const t=f[0];f.length>1&&([,u]=f);const n=Math.max(e,i);if(n>=960&&u)return Ea(e,i,[t,u,l],h);if(n>=480)return Ea(e,i,[t,l],h)}return Ea(e,i,[l])}function Sa(t,e){if(t)return(t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map((e=>{var i,n;return new Qs(Math.floor(t.width/e.scaleResolutionDownBy),Math.floor(t.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(i=t.encoding.maxFramerate)&&void 0!==i?i:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,t.encoding.priority)})))(e);const{width:i,height:n}=e,s=i>n?i/n:n/i;return Math.abs(s-16/9)<Math.abs(s-4/3)?ya:wa}function Ea(t,e,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=ka.length)return;const o={rid:ka[r],scaleResolutionDownBy:Math.max(1,Math.min(t,e)/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},a=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;a&&(o.maxFramerate=a);const c=Er()||0===r;i.encoding.priority&&c&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),s.push(o)})),Ir()&&"ios"===Dr()){let t;s.forEach((e=>{t?e.maxFramerate&&e.maxFramerate>t&&(t=e.maxFramerate):t=e.maxFramerate}));let e=!0;s.forEach((i=>{var n;i.maxFramerate!=t&&(e&&(e=!1,rn.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),rn.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(t)),i.maxFramerate=t)}))}return s}function Oa(t){if(t)return t.sort(((t,e)=>{const{encoding:i}=t,{encoding:n}=e;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 xa{constructor(t){const e=t.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!e)throw Error("invalid scalability mode");if(this.spatial=parseInt(e[1]),this.temporal=parseInt(e[2]),e.length>3)switch(e[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=e[3]}}toString(){var t;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(t=this.suffix)&&void 0!==t?t:"")}}class Aa extends va{get sender(){return this._sender}set sender(t){this._sender=t,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,e){super(t,mr.Kind.Video,e,!(arguments.length>2&&void 0!==arguments[2])||arguments[2],arguments.length>3?arguments[3]:void 0),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>hn(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(t){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}const e=new Map(t.map((t=>[t.rid,t]))),i=t.some((t=>"cpu"===t.qualityLimitationReason));if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(Ds.CpuConstrained)),this.prevStats){let t=0;e.forEach(((e,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);t+=ha(e,s)})),this._currentBitrate=t}this.prevStats=e})),this.senderLock=new u}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(t){var e;if(this.signalClient=t,!_r())return;const i=null===(e=this.sender)||void 0===e?void 0:e.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),da))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((t=>{t.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const t=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return hn(this,void 0,void 0,(function*(){var e,i,n,s;yield t.pauseUpstream.call(this);try{for(var r,o=!0,a=ln(this.simulcastCodecs.values());!(e=(r=yield a.next()).done);o=!0){o=!1;const t=r.value;yield null===(s=t.sender)||void 0===s?void 0:s.replaceTrack(null)}}catch(t){i={error:t}}finally{try{o||e||!(n=a.return)||(yield n.call(a))}finally{if(i)throw i.error}}}))}resumeUpstream(){const t=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return hn(this,void 0,void 0,(function*(){var e,i,n,s;yield t.resumeUpstream.call(this);try{for(var r,o=!0,a=ln(this.simulcastCodecs.values());!(e=(r=yield a.next()).done);o=!0){o=!1;const t=r.value;yield null===(s=t.sender)||void 0===s?void 0:s.replaceTrack(t.mediaStreamTrack)}}catch(t){i={error:t}}finally{try{o||e||!(n=a.return)||(yield n.call(a))}finally{if(i)throw i.error}}}))}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return hn(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==mr.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield t.mute.call(this),this)}finally{e()}}))}unmute(){const t=Object.create(null,{unmute:{get:()=>super.unmute}});return hn(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.source!==mr.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield t.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{e()}}))}setTrackMuted(t){super.setTrackMuted(t);for(const e of this.simulcastCodecs.values())e.mediaStreamTrack.enabled=!t}getSenderStats(){return hn(this,void 0,void 0,(function*(){var t;if(!(null===(t=this.sender)||void 0===t?void 0:t.getStats))return[];const e=[],i=yield this.sender.getStats();return i.forEach((t=>{var n;if("outbound-rtp"===t.type){const s={type:"video",streamId:t.id,frameHeight:t.frameHeight,frameWidth:t.frameWidth,framesPerSecond:t.framesPerSecond,framesSent:t.framesSent,firCount:t.firCount,pliCount:t.pliCount,nackCount:t.nackCount,packetsSent:t.packetsSent,bytesSent:t.bytesSent,qualityLimitationReason:t.qualityLimitationReason,qualityLimitationDurations:t.qualityLimitationDurations,qualityLimitationResolutionChanges:t.qualityLimitationResolutionChanges,rid:null!==(n=t.rid)&&void 0!==n?n:t.id,retransmittedPacketsSent:t.retransmittedPacketsSent,targetBitrate:t.targetBitrate,timestamp:t.timestamp},r=i.get(t.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),e.push(s)}})),e.sort(((t,e)=>{var i,n;return(null!==(i=e.frameWidth)&&void 0!==i?i:0)-(null!==(n=t.frameWidth)&&void 0!==n?n:0)})),e}))}setPublishingQuality(t){const e=[];for(let i=vr.LOW;i<=vr.HIGH;i+=1)e.push(new xi({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(Tr(this.codec),e)}restartTrack(t){return hn(this,void 0,void 0,(function*(){var e,i,n,s;let r;if(t){const e=sr({video:t});"boolean"!=typeof e.video&&(r=e.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var o,a=!0,c=ln(this.simulcastCodecs.values());!(e=(o=yield c.next()).done);a=!0){a=!1;const t=o.value;t.sender&&"closed"!==(null===(s=t.sender.transport)||void 0===s?void 0:s.state)&&(t.mediaStreamTrack=this.mediaStreamTrack.clone(),yield t.sender.replaceTrack(t.mediaStreamTrack))}}catch(t){i={error:t}}finally{try{a||e||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}setProcessor(t){const e=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return hn(this,arguments,void 0,(function(t){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c;if(yield e.setProcessor.call(i,t,n),null===(a=i.processor)||void 0===a?void 0:a.processedTrack)try{for(var d,h=!0,l=ln(i.simulcastCodecs.values());!(s=(d=yield l.next()).done);h=!0){h=!1;const t=d.value;yield null===(c=t.sender)||void 0===c?void 0:c.replaceTrack(i.processor.processedTrack)}}catch(t){r={error:t}}finally{try{h||s||!(o=l.return)||(yield o.call(l))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(t){return hn(this,void 0,void 0,(function*(){if(this.degradationPreference=t,this.sender)try{this.log.debug("setting degradationPreference to ".concat(t),this.logContext);const e=this.sender.getParameters();e.degradationPreference=t,this.sender.setParameters(e)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}}))}addSimulcastTrack(t,e){if(this.simulcastCodecs.has(t))return void this.log.error("".concat(t," already added, skipping adding simulcast codec"),this.logContext);const i={codec:t,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:e};return this.simulcastCodecs.set(t,i),i}setSimulcastTrackSender(t,e){const i=this.simulcastCodecs.get(t);i&&(i.sender=e,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(t){return hn(this,void 0,void 0,(function*(){var e,i,n,s,r,o;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:t,currentCodec:this.codec})),!this.codec&&t.length>0)return yield this.setPublishingLayers(Tr(t[0].codec),t[0].qualities),[];this.subscribedCodecs=t;const a=[];try{for(e=!0,i=ln(t);!(s=(n=yield i.next()).done);e=!0){e=!1;const t=n.value;if(this.codec&&this.codec!==t.codec){const e=this.simulcastCodecs.get(t.codec);if(this.log.debug("try setPublishingCodec for ".concat(t.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:e})),e&&e.sender)e.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(t.codec),this.logContext),yield Ca(e.sender,e.encodings,t.qualities,this.senderLock,Tr(t.codec),this.log,this.logContext));else for(const e of t.qualities)if(e.enabled){a.push(t.codec);break}}else yield this.setPublishingLayers(Tr(t.codec),t.qualities)}}catch(t){r={error:t}}finally{try{e||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return a}))}setPublishingLayers(t,e){return hn(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:e})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield Ca(this.sender,this.encodings,e,this.senderLock,t,this.log,this.logContext)))}))}prioritizePerformance(){return hn(this,void 0,void 0,(function*(){if(!this.sender)throw Error("sender not found");const t=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map(((t,e)=>{var i;return Object.assign(Object.assign({},t),{active:0===e,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===e&&Tr(this.codec)?"L1T3":void 0,maxFramerate:0===e?15:0,maxBitrate:0===e?t.maxBitrate:0})})),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{t()}}))}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return hn(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),Cr()&&this.isInBackground&&this.source===mr.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Ca(t,e,i,n,s,r,o){return hn(this,void 0,void 0,(function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:i,senderEncodings:e}));try{const n=t.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==e.length)return void r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:e}));let c=!1;s&&i.some((t=>t.enabled))&&i.forEach((t=>t.enabled=!0)),a.forEach(((t,n)=>{var s;let a=null!==(s=t.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=_a(a),h=i.find((t=>t.quality===d));h&&t.active!==h.enabled&&(c=!0,t.active=h.enabled,r.debug("setting layer ".concat(h.quality," to ").concat(t.active?"enabled":"disabled"),o),Er()&&(h.enabled?(t.scaleResolutionDownBy=e[n].scaleResolutionDownBy,t.maxBitrate=e[n].maxBitrate,t.maxFrameRate=e[n].maxFrameRate):(t.scaleResolutionDownBy=4,t.maxBitrate=10,t.maxFrameRate=2)))})),c&&(n.encodings=a,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:n.encodings})),yield t.setParameters(n))}finally{a()}}))}function _a(t){switch(t){case"f":default:return vr.HIGH;case"h":return vr.MEDIUM;case"q":return vr.LOW}}function Ia(t,e,i,n){if(!i)return[new ge({quality:vr.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(n){const n=new xa(i[0].scalabilityMode),s=[],r="h"==n.suffix?1.5:2,o="h"==n.suffix?2:3;for(let a=0;a<n.spatial;a+=1)s.push(new ge({quality:Math.min(vr.HIGH,n.spatial-1)-a,width:Math.ceil(t/Math.pow(r,a)),height:Math.ceil(e/Math.pow(r,a)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(o,a)):0,ssrc:0}));return s}return i.map((i=>{var n,s,r;const o=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=_a(null!==(s=i.rid)&&void 0!==s?s:"");return new ge({quality:a,width:Math.ceil(t/o),height:Math.ceil(e/o),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const Ra="_lossy",ja="_reliable",Pa="leave-reconnect";var Da,Ma,Na,Ua;!function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"}(Da||(Da={}));class La extends vn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var e;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=ia.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Da.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=rn,this.reliableDataSequence=1,this.reliableMessageBuffer=new _o,this.reliableReceivedState=new Io(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=t=>hn(this,[t],void 0,(function(t){var e=this;let{channel:i}=t;return function*(){if(i){if(i.label===ja)e.reliableDCSub=i;else{if(i.label!==Ra)return;e.lossyDCSub=i}e.log.debug("on data channel ".concat(i.id,", ").concat(i.label),e.logContext),i.onmessage=e.handleDataMessage}}()})),this.handleDataMessage=t=>hn(this,void 0,void 0,(function*(){var e,i,n,s,r;const o=yield this.dataProcessLock.lock();try{let o;if(t.data instanceof ArrayBuffer)o=t.data;else{if(!(t.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:t.data}));o=yield t.data.arrayBuffer()}const a=ye.fromBinary(new Uint8Array(o));if(a.sequence>0&&""!==a.participantSid){const t=this.reliableReceivedState.get(a.participantSid);if(t&&a.sequence<=t)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}if("speaker"===(null===(e=a.value)||void 0===e?void 0:e.case))this.emit(Ps.ActiveSpeakersUpdate,a.value.value.speakers);else if("encryptedPacket"===(null===(i=a.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);const t=yield null===(n=this.e2eeManager)||void 0===n?void 0:n.handleEncryptedData(a.value.value.encryptedValue,a.value.value.iv,a.participantIdentity,a.value.value.keyIndex),e=Te.fromBinary(t.payload),i=new ye({value:e.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&Ba(i,i.value.value),this.emit(Ps.DataPacketReceived,i,a.value.value.encryptionType)}else"user"===(null===(r=a.value)||void 0===r?void 0:r.case)&&Ba(a,a.value.value),this.emit(Ps.DataPacketReceived,a,ve.NONE)}finally{o()}})),this.handleDataError=t=>{const e=0===t.currentTarget.maxRetransmits?"lossy":"reliable";if(t instanceof ErrorEvent&&t.error){const{error:i}=t.error;this.log.error("DataChannel error on ".concat(e,": ").concat(t.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(e),Object.assign(Object.assign({},this.logContext),{event:t}))},this.handleBufferedAmountLow=t=>{this.updateAndEmitDCBufferStatus(0===t.currentTarget.maxRetransmits?we.LOSSY:we.RELIABLE)},this.handleDisconnect=(t,e)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});null!==n?(t===Pa&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ws.setTimeout((()=>this.attemptReconnect(e).finally((()=>this.reconnectTimeout=void 0))),n)):(t=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up"),this.logContext),this.emit(Ps.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((t,e)=>{this.pcState===Da.Connected&&t();const i=()=>{this.off(Ps.Disconnected,n),t()},n=()=>{this.off(Ps.Restarted,i),e()};this.once(Ps.Restarted,i),this.once(Ps.Disconnected,n)})),this.updateAndEmitDCBufferStatus=t=>{if(t===we.RELIABLE){const e=this.dataChannelForKind(t);e&&this.reliableMessageBuffer.alignBufferedAmount(e.bufferedAmount)}const e=this.isBufferStatusLow(t);void 0!==e&&e!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,e),this.emit(Ps.DCBufferStatusChanged,e,t))},this.isBufferStatusLow=t=>{const e=this.dataChannelForKind(t);if(e)return e.bufferedAmount<=e.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>hn(this,void 0,void 0,(function*(){this.url&&(yield fetch(Hr(this.url),{method:"HEAD"}).then((t=>t.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===Oo.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Oo.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(se.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>hn(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(Hr(this.url),{method:"HEAD"}),yr(4e3).then((()=>Promise.reject()))])}catch(t){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=on(null!==(e=t.loggerName)&&void 0!==e?e:tn.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new xo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new u,this.dataProcessLock=new u,this.dcBufferStatus=new Map([[we.LOSSY,!0],[we.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(Ps.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(Ps.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(Ps.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(Ps.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(Ps.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(Ps.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(Ps.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(Ps.SignalRequestResponse,t)}get logContext(){var t,e,i,n,s,r;return{room:null===(e=null===(t=this.latestJoinResponse)||void 0===t?void 0:t.room)||void 0===e?void 0:e.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:this.participantSid}}join(t,e,i,n){return hn(this,arguments,void 0,(function(t,e,i,n){var s=this;let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){s.url=t,s.token=e,s.signalOpts=i,s.maxJoinAttempts=i.maxRetries;try{s.joinAttempts+=1,s.setupSignalClientCallbacks();const o=yield s.client.join(t,e,i,n,r);return s._isClosed=!1,s.latestJoinResponse=o,s.subscriberPrimary=o.subscriberPrimary,s.pcManager||(yield s.configure(o,!r)),s.subscriberPrimary&&!o.fastPublish||s.negotiate().catch((t=>{rn.error(t,s.logContext)})),s.registerOnLineListener(),s.clientConfiguration=o.clientConfiguration,s.emit(Ps.SignalConnected,o),o}catch(o){if(o instanceof Ms)if(o.reason===Cs.ServerUnreachable){if(s.log.warn("Couldn't connect to server, attempt ".concat(s.joinAttempts," of ").concat(s.maxJoinAttempts),s.logContext),s.joinAttempts<s.maxJoinAttempts)return s.join(t,e,i,n,r)}else if(o.reason===Cs.ServiceNotFound)return s.log.warn("Initial connection failed: ".concat(o.message," – Retrying")),s.join(t,e,i,n,!0);throw o}}()}))}close(){return hn(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Ps.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return hn(this,void 0,void 0,(function*(){var t;yield null===(t=this.pcManager)||void 0===t?void 0:t.close(),this.pcManager=void 0;const e=t=>{t&&(t.close(),t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new _o,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 hn(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(t){if(this.pendingTrackResolvers[t.cid])throw new Us("a track with the same ID has already been published");return new Promise(((e,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[t.cid],i(Ms.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[t.cid]={resolve:t=>{clearTimeout(n),e(t)},reject:()=>{clearTimeout(n),i(Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(t)}))}removeTrack(t){if(t.track&&this.pendingTrackResolvers[t.track.id]){const{reject:e}=this.pendingTrackResolvers[t.track.id];e&&e(),delete this.pendingTrackResolvers[t.track.id]}try{return this.pcManager.removeTrack(t),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(t,e){this.client.sendMuteTrack(t,e)}get dataSubscriberReadyState(){var t;return null===(t=this.reliableDCSub)||void 0===t?void 0:t.readyState}getConnectedServerAddress(){return hn(this,void 0,void 0,(function*(){var t;return null===(t=this.pcManager)||void 0===t?void 0:t.getConnectedAddress()}))}setRegionUrlProvider(t){this.regionUrlProvider=t}configure(t,e){return hn(this,void 0,void 0,(function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==na.NEW)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const s=this.makeRTCConfiguration(t);this.pcManager=new sa(s,e?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(Ps.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(t,e)=>{this.client.sendIceCandidate(t,e)},this.pcManager.onPublisherOffer=(t,e)=>{this.client.sendOffer(t,e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,i,n)=>hn(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(e),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),e===na.CONNECTED){const e=this.pcState===Da.New;this.pcState=Da.Connected,e&&this.emit(Ps.Connected,t)}else e===na.FAILED&&(this.pcState!==Da.Connected&&this.pcState!==Da.Reconnecting||(this.pcState=Da.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?se.RR_SUBSCRIBER_FAILED:se.RR_PUBLISHER_FAILED)));(this.client.isDisconnected||this.client.currentState===Oo.RECONNECTING)&&[na.FAILED,na.CLOSING,na.CLOSED].includes(e)&&!this._isClosed&&this.emit(Ps.Offline)})),this.pcManager.onTrack=t=>{0!==t.streams.length&&this.emit(Ps.MediaTrackAdded,t.track,t.streams[0],t.receiver)},function(t){return void 0!==t&&t>13}(null===(n=t.serverInfo)||void 0===n?void 0:n.protocol)||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=(t,e,i)=>hn(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:t.type,sdp:t.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(t,e))})),this.client.onTrickle=(t,e)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:t,target:e})),this.pcManager.addIceCandidate(t,e))},this.client.onOffer=(t,e,i)=>hn(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=e,!this.pcManager)return;this.midToTrackId=i;const n=yield this.pcManager.createSubscriberAnswerFromOffer(t,e);n&&this.client.sendAnswer(n,e)})),this.client.onLocalTrackPublished=t=>{var e;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:t.cid,track:null===(e=t.track)||void 0===e?void 0:e.sid})),!this.pendingTrackResolvers[t.cid])return void this.log.error("missing track resolver for ".concat(t.cid),Object.assign(Object.assign({},this.logContext),{cid:t.cid}));const{resolve:i}=this.pendingTrackResolvers[t.cid];delete this.pendingTrackResolvers[t.cid],i(t.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(Ps.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(Ps.LocalTrackSubscribed,t)},this.client.onTokenRefresh=t=>{var e;this.token=t,null===(e=this.regionUrlProvider)||void 0===e||e.updateToken(t)},this.client.onRemoteMuteChanged=(t,e)=>{this.emit(Ps.RemoteMute,t,e)},this.client.onSubscribedQualityUpdate=t=>{this.emit(Ps.SubscribedQualityUpdate,t)},this.client.onRoomMoved=t=>{var e;this.participantSid=null===(e=t.participant)||void 0===e?void 0:e.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=t.room),this.emit(Ps.RoomMoved,t)},this.client.onMediaSectionsRequirement=t=>{var e,i;const n={direction:"recvonly"};for(let i=0;i<t.numAudios;i++)null===(e=this.pcManager)||void 0===e||e.addPublisherTransceiverOfKind("audio",n);for(let e=0;e<t.numVideos;e++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("video",n);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",se.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==t?void 0:t.reason})),t.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:t.regions})),t.action){case pi.DISCONNECT:this.emit(Ps.Disconnected,null==t?void 0:t.reason),this.close();break;case pi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Pa);break;case pi.RESUME:this.handleDisconnect(Pa)}}}makeRTCConfiguration(t){var e;const i=Object.assign({},this.rtcConfig);if((null===(e=this.signalOpts)||void 0===e?void 0:e.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),t.iceServers&&!i.iceServers){const e=[];t.iceServers.forEach((t=>{const i={urls:t.urls};t.username&&(i.username=t.username),t.credential&&(i.credential=t.credential),e.push(i)})),i.iceServers=e}return t.clientConfiguration&&t.clientConfiguration.forceRelay===ie.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ra,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ja,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval((()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const t=this.dataChannelForKind(we.LOSSY);t&&(t.bufferedAmountLowThreshold=Math.min(Math.max(this.lossyDataStatByterate/10,8192),262144))}),1e3))}createSender(t,e,i){return hn(this,void 0,void 0,(function*(){if(wr())return yield this.createTransceiverRTCRtpSender(t,e,i);if(kr())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(t.mediaStreamTrack);throw new Bs("Required webRTC APIs not supported on this device")}))}createSimulcastSender(t,e,i,n){return hn(this,void 0,void 0,(function*(){if(wr())return this.createSimulcastTransceiverSender(t,e,i,n);if(kr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(t.mediaStreamTrack);throw new Bs("Cannot stream on this device")}))}createTransceiverRTCRtpSender(t,e,i){return hn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Bs("publisher is closed");const n=[];t.mediaStream&&n.push(t.mediaStream),to(t)&&(t.codec=e.videoCodec);const s={direction:"sendonly",streams:n};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(t,e,i,n){return hn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Bs("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s);if(i.videoCodec)return t.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(t){return hn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Bs("publisher is closed");return this.pcManager.addPublisherTrack(t)}))}attemptReconnect(t){return hn(this,void 0,void 0,(function*(){var e,i,n;if(!this._isClosed)if(this.attemptingReconnect)rn.warn("already attempting reconnect, returning early",this.logContext);else{(null===(e=this.clientConfiguration)||void 0===e?void 0:e.resumeConnection)!==ie.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:na.NEW)!==na.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let e=!0;t instanceof Bs?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof Js||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",se.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(Ps.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(t){try{return this.reconnectPolicy.nextRetryDelayInMs(t)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(t){return hn(this,void 0,void 0,(function*(){var e,i,n;try{if(!this.url||!this.token)throw new Bs("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Ps.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Js;i=yield this.join(null!=t?t:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(t){if(t instanceof Ms&&t.reason===Cs.NotAllowed)throw new Bs("could not reconnect, token might be expired");throw new Js}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(Ps.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Oo.CONNECTED)throw new Js("Signal connection got severed during reconnect");null===(e=this.regionUrlProvider)||void 0===e||e.resetAttempts(),this.emit(Ps.Restarted)}catch(t){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),t}}))}resumeConnection(t){return hn(this,void 0,void 0,(function*(){var e;if(!this.url||!this.token)throw new Bs("could not reconnect, url or token not saved");if(!this.pcManager)throw new Bs("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Ps.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(t){let e="";if(t instanceof Error&&(e=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof Ms&&t.reason===Cs.NotAllowed)throw new Bs("could not reconnect, token might be expired");if(t instanceof Ms&&t.reason===Cs.LeaveRequest)throw t;throw new Js(e)}if(this.emit(Ps.SignalResumed),i){const t=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(t),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Oo.CONNECTED)throw new Js("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(e=this.reliableDC)||void 0===e?void 0:e.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(Ps.Resumed)}))}waitForPCInitialConnection(t,e){return hn(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Bs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(e,t)}))}waitForPCReconnected(){return hn(this,void 0,void 0,(function*(){this.pcState=Da.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield yr(2e3),!this.pcManager)throw new Bs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Da.Connected}catch(t){throw this.pcState=Da.Disconnected,Ms.internal("could not establish PC connection, ".concat(t.message))}}))}publishRpcResponse(t,e,i,n){return hn(this,void 0,void 0,(function*(){const s=new ye({destinationIdentities:[t],kind:we.RELIABLE,value:{case:"rpcResponse",value:new je({requestId:e,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,we.RELIABLE)}))}publishRpcAck(t,e){return hn(this,void 0,void 0,(function*(){const i=new ye({destinationIdentities:[t],kind:we.RELIABLE,value:{case:"rpcAck",value:new Re({requestId:e})}});yield this.sendDataPacket(i,we.RELIABLE)}))}sendDataPacket(t,e){return hn(this,void 0,void 0,(function*(){if(yield this.ensurePublisherConnected(e),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const e=function(t){var e,i,n,s,r;if("sipDtmf"!==(null===(e=t.value)||void 0===e?void 0:e.case)&&"metrics"!==(null===(i=t.value)||void 0===i?void 0:i.case)&&"speaker"!==(null===(n=t.value)||void 0===n?void 0:n.case)&&"transcription"!==(null===(s=t.value)||void 0===s?void 0:s.case)&&"encryptedPacket"!==(null===(r=t.value)||void 0===r?void 0:r.case))return new Te({value:t.value})}(t);if(e){const i=yield this.e2eeManager.encryptData(e.toBinary());t.value={case:"encryptedPacket",value:new ke({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}e===we.RELIABLE&&(t.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=t.toBinary(),n=this.dataChannelForKind(e);if(n){if(e===we.RELIABLE)yield this.waitForBufferStatusLow(e),this.reliableMessageBuffer.push({data:i,sequence:t.sequence});else{if(!this.isBufferStatusLow(e))return this.lossyDataDropCount+=1,void(this.lossyDataDropCount%100==0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext));this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(e)}))}resendReliableMessagesForResume(t){return hn(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(we.RELIABLE);const e=this.dataChannelForKind(we.RELIABLE);e&&(this.reliableMessageBuffer.popToSequence(t),this.reliableMessageBuffer.getAll().forEach((t=>{e.send(t.data)}))),this.updateAndEmitDCBufferStatus(we.RELIABLE)}))}waitForBufferStatusLow(t){return new ws(((e,i)=>hn(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(t))e();else{const n=()=>i(new Bs("engine closed"));for(this.once(Ps.Closing,n);!this.dcBufferStatus.get(t);)yield yr(10);this.off(Ps.Closing,n),e()}}))))}ensureDataTransportConnected(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!e.pcManager)throw new Bs("PC manager is closed");const s=i?e.pcManager.subscriber:e.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw Ms.internal("".concat(r," connection not set"));let o=!1;i||e.dataChannelForKind(t,i)||(e.createDataChannels(),o=!0),o||i||e.pcManager.publisher.isICEConnected||"checking"===e.pcManager.publisher.getICEConnectionState()||(o=!0),o&&e.negotiate().catch((t=>{rn.error(t,e.logContext)}));const a=e.dataChannelForKind(t,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+e.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=e.dataChannelForKind(t,i))||void 0===n?void 0:n.readyState))return;yield yr(50)}throw Ms.internal("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))}()}))}ensurePublisherConnected(t){return hn(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(t,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===na.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return hn(this,void 0,void 0,(function*(){return new ws(((t,e)=>hn(this,void 0,void 0,(function*(){if(!this.pcManager)return void e(new Fs("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&e(new Fs("cannot negotiate on closed engine")),this.on(Ps.Closing,n),this.pcManager.publisher.once(Go,(t=>{const e=new Map;t.forEach((t=>{const i=t.codec.toLowerCase();(function(t){return Ks.includes(t)})(i)&&e.set(t.payload,i)})),this.emit(Ps.RTPVideoMapUpdate,e)}));try{yield this.pcManager.negotiate(i),t()}catch(t){t instanceof Fs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",se.RR_UNKNOWN),e(t instanceof Error?t:Error(t+""))}finally{this.off(Ps.Closing,n)}}))))}))}dataChannelForKind(t,e){if(e){if(t===we.LOSSY)return this.lossyDCSub;if(t===we.RELIABLE)return this.reliableDCSub}else{if(t===we.LOSSY)return this.lossyDC;if(t===we.RELIABLE)return this.reliableDC}}sendSyncState(t,e){var i,n,s,r;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const o=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),c=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),d=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getLocalDescription(),h=null===(r=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===r||r,l=[],u=[];t.forEach((t=>{t.isDesired!==h&&l.push(t.trackSid),t.isEnabled||u.push(t.trackSid)})),this.client.sendSyncState(new Di({answer:"publisher-only"===this.pcManager.mode?a?Co({sdp:a.sdp,type:a.type}):void 0:d?Co({sdp:d.sdp,type:d.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?Co({sdp:o.sdp,type:o.type}):void 0:c?Co({sdp:c.sdp,type:c.type}):void 0,subscription:new li({trackSids:l,subscribe:!h,participantTracks:[]}),publishTracks:dr(e),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:u,datachannelReceiveStates:this.reliableReceivedState.map(((t,e)=>new Mi({publisherSid:e,lastSeq:t})))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const t=[],e=(e,i)=>{void 0!==(null==e?void 0:e.id)&&null!==e.id&&t.push(new Ni({label:e.label,id:e.id,target:i}))};return e(this.dataChannelForKind(we.LOSSY),Ye.PUBLISHER),e(this.dataChannelForKind(we.RELIABLE),Ye.PUBLISHER),e(this.dataChannelForKind(we.LOSSY,!0),Ye.SUBSCRIBER),e(this.dataChannelForKind(we.RELIABLE,!0),Ye.SUBSCRIBER),t}clearReconnectTimeout(){this.reconnectTimeout&&Ws.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){_r()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){_r()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(t){var e;const i=null===(e=this.pcManager)||void 0===e?void 0:e.getMidForReceiver(t);if(i){const t=Object.entries(this.midToTrackId).find((t=>{let[e]=t;return e===i}));if(t)return t[1]}}}function Ba(t,e){const i=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=i,e.participantIdentity=i;const n=0!==t.destinationIdentities.length?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=n,e.destinationIdentities=n}class Fa{get info(){return this._info}validateBytesReceived(){if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.bytesReceived<this.totalByteSize)throw new zs("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),_s.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new zs("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),_s.LengthExceeded)}}constructor(t,e,i,n){this.reader=e,this.totalByteSize=i,this._info=t,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class Va extends Fa{handleChunkReceived(t){var e;this.bytesReceived+=t.content.byteLength,this.validateBytesReceived(),null===(e=this.onProgress)||void 0===e||e.call(this,this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0)}[Symbol.asyncIterator](){const t=this.reader.getReader();let e=new Gr,i=null,n=null;if(this.signal){const t=this.signal;n=()=>{var i;null===(i=e.reject)||void 0===i||i.call(e,t.reason)},t.addEventListener("abort",n),i=t}const s=()=>{t.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>hn(this,void 0,void 0,(function*(){var i,n;try{const{done:s,value:r}=yield Promise.race([t.read(),e.promise,null!==(n=null===(i=this.outOfBandFailureRejectingFuture)||void 0===i?void 0:i.promise)&&void 0!==n?n:new Promise((()=>{}))]);return s?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r),{done:!1,value:r.content})}catch(t){throw s(),t}})),return(){return hn(this,void 0,void 0,(function*(){return s(),{done:!0,value:void 0}}))}}}withAbortSignal(t){return this.signal=t,this}readAll(){return hn(this,arguments,void 0,(function(){var t=this;let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s;let r=new Set;const o=e.signal?t.withAbortSignal(e.signal):t;try{for(var a,c=!0,d=ln(o);!(i=(a=yield d.next()).done);c=!0)c=!1,r.add(a.value)}catch(t){n={error:t}}finally{try{c||i||!(s=d.return)||(yield s.call(d))}finally{if(n)throw n.error}}return Array.from(r)}()}))}}class qa extends Fa{constructor(t,e,i,n){super(t,e,i,n),this.receivedChunks=new Map}handleChunkReceived(t){var e;const i=Yr(t.chunkIndex),n=this.receivedChunks.get(i);n&&n.version>t.version||(this.receivedChunks.set(i,t),this.bytesReceived+=t.content.byteLength,this.validateBytesReceived(),null===(e=this.onProgress)||void 0===e||e.call(this,this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0))}[Symbol.asyncIterator](){const t=this.reader.getReader(),e=new TextDecoder("utf-8",{fatal:!0});let i=new Gr,n=null,s=null;if(this.signal){const t=this.signal;s=()=>{var e;null===(e=i.reject)||void 0===e||e.call(i,t.reason)},t.addEventListener("abort",s),n=t}const r=()=>{t.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>hn(this,void 0,void 0,(function*(){var n,s;try{const{done:r,value:o}=yield Promise.race([t.read(),i.promise,null!==(s=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==s?s:new Promise((()=>{}))]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let t;this.handleChunkReceived(o);try{t=e.decode(o.content)}catch(t){throw new zs("Cannot decode datastream chunk ".concat(o.chunkIndex," as text: ").concat(t),_s.DecodeFailed)}return{done:!1,value:t}}}catch(t){throw r(),t}})),return(){return hn(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(t){return this.signal=t,this}readAll(){return hn(this,arguments,void 0,(function(){var t=this;let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s;let r="";const o=e.signal?t.withAbortSignal(e.signal):t;try{for(var a,c=!0,d=ln(o);!(i=(a=yield d.next()).done);c=!0)c=!1,r+=a.value}catch(t){n={error:t}}finally{try{c||i||!(s=d.return)||(yield s.call(d))}finally{if(n)throw n.error}}return r}()}))}}class za{constructor(){this.log=rn,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(t,e){if(this.textStreamHandlers.has(t))throw new zs('A text stream handler for topic "'.concat(t,'" has already been set.'),_s.HandlerAlreadyRegistered);this.textStreamHandlers.set(t,e)}unregisterTextStreamHandler(t){this.textStreamHandlers.delete(t)}registerByteStreamHandler(t,e){if(this.byteStreamHandlers.has(t))throw new zs('A byte stream handler for topic "'.concat(t,'" has already been set.'),_s.HandlerAlreadyRegistered);this.byteStreamHandlers.set(t,e)}unregisterByteStreamHandler(t){this.byteStreamHandlers.delete(t)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(t){var e,i,n,s;const r=Array.from(this.textStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t)),o=Array.from(this.byteStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t));if(r.length>0||o.length>0){const a=new zs("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),_s.AbnormalEnd);for(const[t,n]of o)null===(i=(e=n.outOfBandFailureRejectingFuture).reject)||void 0===i||i.call(e,a),this.byteStreamControllers.delete(t);for(const[t,e]of r)null===(s=(n=e.outOfBandFailureRejectingFuture).reject)||void 0===s||s.call(n,a),this.textStreamControllers.delete(t)}}handleDataStreamPacket(t,e){return hn(this,void 0,void 0,(function*(){switch(t.value.case){case"streamHeader":return this.handleStreamHeader(t.value.value,t.participantIdentity,e);case"streamChunk":return this.handleStreamChunk(t.value.value,e);case"streamTrailer":return this.handleStreamTrailer(t.value.value,e);default:throw Error('DataPacket of value "'.concat(t.value.case,'" is not data stream related!'))}}))}handleStreamHeader(t,e,i){return hn(this,void 0,void 0,(function*(){var n;if("byteHeader"===t.contentHeader.case){const s=this.byteStreamHandlers.get(t.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",t.topic);let r;const o=new Gr;o.promise.catch((t=>{this.log.error(t)}));const a={id:t.streamId,name:null!==(n=t.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Yr(t.timestamp),attributes:t.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(t.streamId))throw new zs("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),_s.AlreadyOpened);this.byteStreamControllers.set(t.streamId,{info:a,controller:r,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:o})}});s(new Va(a,c,Yr(t.totalLength),o),{identity:e})}else if("textHeader"===t.contentHeader.case){const n=this.textStreamHandlers.get(t.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);let s;const r=new Gr;r.promise.catch((t=>{this.log.error(t)}));const o={id:t.streamId,mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Number(t.timestamp),attributes:t.attributes,encryptionType:i},a=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(t.streamId))throw new zs("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),_s.AlreadyOpened);this.textStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:r})}});n(new qa(o,a,Yr(t.totalLength),r),{identity:e})}}))}handleStreamChunk(t,e){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==e?(i.controller.error(new zs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(i.info.encryptionType),_s.EncryptionTypeMismatch)),this.byteStreamControllers.delete(t.streamId)):t.content.length>0&&i.controller.enqueue(t));const n=this.textStreamControllers.get(t.streamId);n&&(n.info.encryptionType!==e?(n.controller.error(new zs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(n.info.encryptionType),_s.EncryptionTypeMismatch)),this.textStreamControllers.delete(t.streamId)):t.content.length>0&&n.controller.enqueue(t))}handleStreamTrailer(t,e){const i=this.textStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==e?i.controller.error(new zs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(i.info.encryptionType),_s.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),t.attributes),i.controller.close(),this.textStreamControllers.delete(t.streamId)));const n=this.byteStreamControllers.get(t.streamId);n&&(n.info.encryptionType!==e?n.controller.error(new zs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(n.info.encryptionType),_s.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),t.attributes),n.controller.close()),this.byteStreamControllers.delete(t.streamId))}}class Ja{constructor(t,e,i){this.writableStream=t,this.defaultWriter=t.getWriter(),this.onClose=i,this.info=e}write(t){return this.defaultWriter.write(t)}close(){return hn(this,void 0,void 0,(function*(){var t;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(t=this.onClose)||void 0===t||t.call(this)}))}}class Wa extends Ja{}class Ga extends Ja{}class Qa{constructor(t,e){this.engine=t,this.log=e}setupEngine(t){this.engine=t}sendText(t,e){return hn(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(t).byteLength,r=null===(i=null==e?void 0:e.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),o=Array(r?r.length+1:1).fill(0),a=(t,i)=>{var n;o[i]=t;const s=o.reduce(((t,e)=>t+e),0);null===(n=null==e?void 0:e.onProgress)||void 0===n||n.call(e,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==e?void 0:e.destinationIdentities,topic:null==e?void 0:e.topic,attachedStreamIds:r,attributes:null==e?void 0:e.attributes});return yield c.write(t),a(1,0),yield c.close(),(null==e?void 0:e.attachments)&&r&&(yield Promise.all(e.attachments.map(((t,i)=>hn(this,void 0,void 0,(function*(){return this._sendFile(r[i],t,{topic:e.topic,mimeType:t.type,onProgress:t=>{a(t,i+1)}})})))))),c.info}))}streamText(t){return hn(this,void 0,void 0,(function*(){var e,i,n;const s=null!==(e=null==t?void 0:t.streamId)&&void 0!==e?e:crypto.randomUUID(),r={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:null==t?void 0:t.totalSize,attributes:null==t?void 0:t.attributes,encryptionType:(null===(n=this.engine.e2eeManager)||void 0===n?void 0:n.isDataChannelEncryptionEnabled)?ve.GCM:ve.NONE},o=new Ge({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:Zr(r.timestamp),totalLength:Zr(null==t?void 0:t.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Je({version:null==t?void 0:t.version,attachedStreamIds:null==t?void 0:t.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?ze.UPDATE:ze.CREATE})}}),a=null==t?void 0:t.destinationIdentities,c=new ye({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,we.RELIABLE);let d=0;const h=this.engine,l=new WritableStream({write(t){return hn(this,void 0,void 0,(function*(){for(const e of function(t){const e=[];let i=(new TextEncoder).encode(t);for(;i.length>15e3;){let t=15e3;for(;t>0;){const e=i[t];if(void 0!==e&&128!=(192&e))break;t--}e.push(i.slice(0,t)),i=i.slice(t)}return i.length>0&&e.push(i),e}(t)){const t=new Qe({content:e,streamId:s,chunkIndex:Zr(d)}),i=new ye({destinationIdentities:a,value:{case:"streamChunk",value:t}});yield h.sendDataPacket(i,we.RELIABLE),d+=1}}))},close(){return hn(this,void 0,void 0,(function*(){const t=new He({streamId:s}),e=new ye({destinationIdentities:a,value:{case:"streamTrailer",value:t}});yield h.sendDataPacket(e,we.RELIABLE)}))},abort(t){console.log("Sink error:",t)}});let u=()=>hn(this,void 0,void 0,(function*(){yield f.close()}));h.once(Ps.Closing,u);const f=new Wa(l,r,(()=>this.engine.off(Ps.Closing,u)));return f}))}sendFile(t,e){return hn(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,t,e),{id:i}}))}_sendFile(t,e,i){return hn(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:t,totalSize:e.size,name:e.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:e.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=e.stream().getReader();for(;;){const{done:t,value:e}=yield r.read();if(t)break;yield s.write(e)}return yield s.close(),s.info}))}streamBytes(t){return hn(this,void 0,void 0,(function*(){var e,i,n,s,r,o;const a=null!==(e=null==t?void 0:t.streamId)&&void 0!==e?e:crypto.randomUUID(),c=null==t?void 0:t.destinationIdentities,d={id:a,mimeType:null!==(i=null==t?void 0:t.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==t?void 0:t.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==t?void 0:t.attributes,size:null==t?void 0:t.totalSize,name:null!==(s=null==t?void 0:t.name)&&void 0!==s?s:"unknown",encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?ve.GCM:ve.NONE},h=new Ge({totalLength:Zr(null!==(o=d.size)&&void 0!==o?o:0),mimeType:d.mimeType,streamId:a,topic:d.topic,timestamp:Zr(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new We({name:d.name})}}),l=new ye({destinationIdentities:c,value:{case:"streamHeader",value:h}});yield this.engine.sendDataPacket(l,we.RELIABLE);let f=0;const v=new u,m=this.engine,p=this.log,g=new WritableStream({write(t){return hn(this,void 0,void 0,(function*(){const e=yield v.lock();let i=0;try{for(;i<t.byteLength;){const e=t.slice(i,i+15e3),n=new ye({destinationIdentities:c,value:{case:"streamChunk",value:new Qe({content:e,streamId:a,chunkIndex:Zr(f)})}});yield m.sendDataPacket(n,we.RELIABLE),f+=1,i+=e.byteLength}}finally{e()}}))},close(){return hn(this,void 0,void 0,(function*(){const t=new He({streamId:a}),e=new ye({destinationIdentities:c,value:{case:"streamTrailer",value:t}});yield m.sendDataPacket(e,we.RELIABLE)}))},abort(t){p.error("Sink error:",t)}});return new Ga(g,d)}))}}class Ha extends mr{constructor(t,e,i,n,s){super(t,i,s),this.sid=e,this.receiver=n}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?Ds.Muted:Ds.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const e=i=>{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",e),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Ds.Ended,this))};t.addEventListener("removetrack",e)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return hn(this,void 0,void 0,(function*(){var t;if(null===(t=this.receiver)||void 0===t?void 0:t.getStats)return yield this.receiver.getStats()}))}setPlayoutDelay(t){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=t: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()),da)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var e;this.timeSyncHandle=requestAnimationFrame((()=>t()));const i=null===(e=this.receiver)||void 0===e?void 0:e.getSynchronizationSources()[0];if(i){const{timestamp:t,rtpTimestamp:e}=i;e&&this.rtpTimestamp!==e&&(this.emit(Ds.TimeSyncUpdate,{timestamp:t,rtpTimestamp:e}),this.rtpTimestamp=e)}};t()}}class Ka extends Ha{constructor(t,e,i,n,s,r){super(t,e,mr.Kind.Audio,i,r),this.monitorReceiver=()=>hn(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const t=yield this.getReceiverStats();t&&this.prevStats&&this.receiver&&(this._currentBitrate=ha(t,this.prevStats)),this.prevStats=t})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(t){var e;for(const i of this.attachedElements)this.audioContext?null===(e=this.gainNode)||void 0===e||e.gain.setTargetAtTime(t,0,.1):i.volume=t;Ir()&&this._mediaStreamTrack._setVolume(t),this.elementVolume=t}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ir())return 1;let t=0;return this.attachedElements.forEach((e=>{e.volume>t&&(t=e.volume)})),t}setSinkId(t){return hn(this,void 0,void 0,(function*(){this.sinkId=t,yield Promise.all(this.attachedElements.map((e=>{if(Sr(e))return e.setSinkId(t)})))}))}attach(t){const e=0===this.attachedElements.length;return t?super.attach(t):t=super.attach(),this.sinkId&&Sr(t)&&t.setSinkId(this.sinkId).catch((t=>{this.log.error("Failed to set sink id on remote audio track",t,this.logContext)})),this.audioContext&&e&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,t),t.volume=0,t.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),t}detach(t){let e;return t?(e=super.detach(t),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(e=super.detach(),this.disconnectWebAudio()),e}setAudioContext(t){this.audioContext=t,t&&this.attachedElements.length>0?this.connectWebAudio(t,this.attachedElements[0]):t||this.disconnectWebAudio()}setWebAudioPlugins(t){this.webAudioPluginNodes=t,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(t,e){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(e.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((t=>{i.connect(t),i=t})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(Ds.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(Ds.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var t,e;null===(t=this.gainNode)||void 0===t||t.disconnect(),null===(e=this.sourceNode)||void 0===e||e.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return hn(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let t;return(yield this.receiver.getStats()).forEach((e=>{"inbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})})),t}))}}class Ya extends Ha{constructor(t,e,i,n,s){super(t,e,mr.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>hn(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const t=yield this.getReceiverStats();t&&this.prevStats&&this.receiver&&(this._currentBitrate=ha(t,this.prevStats)),this.prevStats=t})),this.debouncedHandleResize=zo((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(t){super.setStreamState(t),this.log.debug("setStreamState",t),this.isAdaptiveStream&&t===mr.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(t){super.setMuted(t),this.attachedElements.forEach((e=>{t?gr(this._mediaStreamTrack,e):pr(this._mediaStreamTrack,e)}))}attach(t){if(t?super.attach(t):t=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((e=>e.element===t))){const e=new Za(t);this.observeElementInfo(e)}return t}observeElementInfo(t){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((e=>e===t))?(t.handleResize=()=>{this.debouncedHandleResize()},t.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(t),t.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(t){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const e=this.elementInfos.filter((e=>e===t));for(const t of e)t.stopObserving();this.elementInfos=this.elementInfos.filter((e=>e!==t)),this.updateVisibility(),this.debouncedHandleResize()}detach(t){let e=[];if(t)return this.stopObservingElement(t),super.detach(t);e=super.detach();for(const t of e)this.stopObservingElement(t);return e}getDecoderImplementation(){var t;return null===(t=this.prevStats)||void 0===t?void 0:t.decoderImplementation}getReceiverStats(){return hn(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const t=yield this.receiver.getStats();let e,i="",n=new Map;return t.forEach((t=>{"inbound-rtp"===t.type?(i=t.codecId,e={type:"video",streamId:t.id,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation}):"codec"===t.type&&n.set(t.id,t)})),e&&""!==i&&n.get(i)&&(e.mimeType=n.get(i).mimeType),e}))}stopObservingElement(t){const e=this.elementInfos.filter((e=>e.element===t));for(const t of e)this.stopObservingElementInfo(t)}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return hn(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(t){var e,i;const n=this.elementInfos.reduce(((t,e)=>Math.max(t,e.visibilityChangedAt||0)),0),s=!(null!==(i=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,r=this.elementInfos.some((t=>t.pictureInPicture)),o=this.elementInfos.some((t=>t.visible))&&!s||r;(this.lastVisible!==o||t)&&(!o&&Date.now()-n<100?Ws.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(Ds.VisibilityChanged,o,this)))}updateDimensions(){var t,e;let i=0,n=0;const s=this.getPixelDensity();for(const t of this.elementInfos){const e=t.width()*s,r=t.height()*s;e+r>i+n&&(i=e,n=r)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(e=this.lastDimensions)||void 0===e?void 0:e.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Ds.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var t;const e=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pixelDensity;return"screen"===e?Mr():e||(Mr()>2?2:1)}}class Za{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(t,e){this.onVisibilityChanged=t=>{var e;const{target:i,isIntersecting:n}=t;i===this.element&&(this.isIntersecting=n,this.isPiP=$a(this.element),this.visibilityChangedAt=Date.now(),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this))},this.onEnterPiP=()=>{var t,e,i;null===(e=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===e||e.addEventListener("pagehide",this.onLeavePiP),this.isPiP=$a(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var t;this.isPiP=$a(this.element),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this)},this.element=t,this.isIntersecting=null!=e?e:Xa(t),this.isPiP=_r()&&$a(t),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var t,e,i;this.isIntersecting=Xa(this.element),this.isPiP=$a(this.element),this.element.handleResize=()=>{var t;null===(t=this.handleResize)||void 0===t||t.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,qr().observe(this.element),Fr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(t=window.documentPictureInPicture)||void 0===t||t.addEventListener("enter",this.onEnterPiP),null===(i=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var t,e,i,n,s;null===(t=qr())||void 0===t||t.unobserve(this.element),null===(e=Fr())||void 0===e||e.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function $a(t){var e,i;return document.pictureInPictureElement===t||!!(null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)&&Xa(t,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Xa(t,e){const i=e||window;let n=t.offsetTop,s=t.offsetLeft;const r=t.offsetWidth,o=t.offsetHeight,{hidden:a}=t,{display:c}=getComputedStyle(t);for(;t.offsetParent;)n+=(t=t.offsetParent).offsetTop,s+=t.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&s+r>i.pageXOffset&&!a&&"none"!==c}class tc extends vn.EventEmitter{constructor(t,e,i,n){var s;super(),this.metadataMuted=!1,this.encryption=ve.NONE,this.log=rn,this.handleMuted=()=>{this.emit(Ds.Muted)},this.handleUnmuted=()=>{this.emit(Ds.Unmuted)},this.log=on(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:tn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=e,this.trackName=i,this.source=mr.Source.Unknown}setTrack(t){this.track&&(this.track.off(Ds.Muted,this.handleMuted),this.track.off(Ds.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(Ds.Muted,this.handleMuted),t.on(Ds.Unmuted,this.handleUnmuted))}get logContext(){var t;return Object.assign(Object.assign({},null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this)),hr(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ve.NONE}get audioTrack(){if(Xr(this.track))return this.track}get videoTrack(){if(to(this.track))return this.track}updateInfo(t){this.trackSid=t.sid,this.trackName=t.name,this.source=mr.sourceFromProto(t.source),this.mimeType=t.mimeType,this.kind===mr.Kind.Video&&t.width>0&&(this.dimensions={width:t.width,height:t.height},this.simulcasted=t.simulcast),this.encryption=t.encryption,this.trackInfo=t,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:t}))}}!function(t){!function(t){t.Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed"}(t.SubscriptionStatus||(t.SubscriptionStatus={})),function(t){t.Allowed="allowed",t.NotAllowed="not_allowed"}(t.PermissionStatus||(t.PermissionStatus={}))}(tc||(tc={}));class ec extends tc{get isUpstreamPaused(){var t;return null===(t=this.track)||void 0===t?void 0:t.isUpstreamPaused}constructor(t,e,i,n){super(t,e.sid,e.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Ds.Ended)},this.handleCpuConstrained=()=>{this.track&&to(this.track)&&this.emit(Ds.CpuConstrained,this.track)},this.updateInfo(e),this.setTrack(i)}setTrack(t){this.track&&(this.track.off(Ds.Ended,this.handleTrackEnded),this.track.off(Ds.CpuConstrained,this.handleCpuConstrained)),super.setTrack(t),t&&(t.on(Ds.Ended,this.handleTrackEnded),t.on(Ds.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 hn(this,void 0,void 0,(function*(){var t;return null===(t=this.track)||void 0===t?void 0:t.mute()}))}unmute(){return hn(this,void 0,void 0,(function*(){var t;return null===(t=this.track)||void 0===t?void 0:t.unmute()}))}pauseUpstream(){return hn(this,void 0,void 0,(function*(){var t;yield null===(t=this.track)||void 0===t?void 0:t.pauseUpstream()}))}resumeUpstream(){return hn(this,void 0,void 0,(function*(){var t;yield null===(t=this.track)||void 0===t?void 0:t.resumeUpstream()}))}getTrackFeatures(){var t;if(Xr(this.track)){const e=this.track.getSourceTrackSettings(),i=new Set;return e.autoGainControl&&i.add(oe.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&i.add(oe.TF_ECHO_CANCELLATION),e.noiseSuppression&&i.add(oe.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&i.add(oe.TF_STEREO),(null===(t=this.options)||void 0===t?void 0:t.dtx)||i.add(oe.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(oe.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function ic(t,e){return hn(this,void 0,void 0,(function*(){null!=t||(t={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=lr(t);let o=r.audio,a=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),t.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const t=r.audio.deviceId;r.audio.deviceId={exact:t},i=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:t}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const t=r.video.deviceId;r.video.deviceId={exact:t},i=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:t}})}!0===r.audio?r.audio={deviceId:"default"}:"object"==typeof r.audio&&null!==r.audio&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),!0===r.video?r.video={deviceId:"default"}:"object"!=typeof r.video||r.video.deviceId||(r.video.deviceId="default");const c=sr(ir(r,Xo,ta)),d=navigator.mediaDevices.getUserMedia(c);r.audio&&(wo.userMediaPromiseMap.set("audioinput",d),d.catch((()=>wo.userMediaPromiseMap.delete("audioinput")))),r.video&&(wo.userMediaPromiseMap.set("videoinput",d),d.catch((()=>wo.userMediaPromiseMap.delete("videoinput"))));try{const t=yield d;return yield Promise.all(t.getTracks().map((i=>hn(this,void 0,void 0,(function*(){let r;const o="audio"===i.kind?c.audio:c.video;"boolean"!=typeof o&&(r=o);const a=i.getSettings().deviceId;(null==r?void 0:r.deviceId)&&Qr(r.deviceId)!==a?r.deviceId=a:r||(r={deviceId:a});const d=function(t,e,i){switch(t.kind){case"audio":return new ma(t,e,!1,void 0,i);case"video":return new Aa(t,e,!1,i);default:throw new Us("unsupported track type: ".concat(t.kind))}}(i,r,e);return d.kind===mr.Kind.Video?d.source=mr.Source.Camera:d.kind===mr.Kind.Audio&&(d.source=mr.Source.Microphone),d.mediaStream=t,Xr(d)&&n?yield d.setProcessor(n):to(d)&&s&&(yield d.setProcessor(s)),d})))))}catch(n){if(!i)throw n;return ic(Object.assign(Object.assign({},t),{audio:o,video:a}),e)}}))}!function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"}(Ma||(Ma={}));class nc extends vn.EventEmitter{get logContext(){var t,e;return Object.assign({},null===(e=null===(t=this.loggerOptions)||void 0===t?void 0:t.loggerContextCb)||void 0===e?void 0:e.call(t))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((t=>t.isEncrypted))}get isAgent(){var t;return(null===(t=this.permissions)||void 0===t?void 0:t.agent)||this.kind===ue.AGENT}get isActive(){var t;return(null===(t=this.participantInfo)||void 0===t?void 0:t.state)===le.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,e,i,n,s,r){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ue.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Ma.Unknown,this.log=rn,this.log=on(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:tn.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=t,this.identity=e,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(t){for(const[,e]of this.trackPublications)if(e.source===t)return e}getTrackPublicationByName(t){for(const[,e]of this.trackPublications)if(e.trackName===t)return e}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Gr,this.once(js.Active,(()=>{var t,e;null===(e=null===(t=this.activeFuture)||void 0===t?void 0:t.resolve)||void 0===e||e.call(t),this.activeFuture=void 0}))),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var t;const e=this.getTrackPublication(mr.Source.Camera);return!(null===(t=null==e?void 0:e.isMuted)||void 0===t||t)}get isMicrophoneEnabled(){var t;const e=this.getTrackPublication(mr.Source.Microphone);return!(null===(t=null==e?void 0:e.isMuted)||void 0===t||t)}get isScreenShareEnabled(){return!!this.getTrackPublication(mr.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(""+this.participantInfo.joinedAt)):new Date}updateInfo(t){var e;return!(this.participantInfo&&this.participantInfo.sid===t.sid&&this.participantInfo.version>t.version||(this.identity=t.identity,this.sid=t.sid,this._setName(t.name),this._setMetadata(t.metadata),this._setAttributes(t.attributes),t.state===le.ACTIVE&&(null===(e=this.participantInfo)||void 0===e?void 0:e.state)!==le.ACTIVE&&this.emit(js.Active),t.permission&&this.setPermissions(t.permission),this.participantInfo=t,0))}_setMetadata(t){const e=this.metadata!==t,i=this.metadata;this.metadata=t,e&&this.emit(js.ParticipantMetadataChanged,i)}_setName(t){const e=this.name!==t;this.name=t,e&&this.emit(js.ParticipantNameChanged,t)}_setAttributes(t){const e=function(t,e){var i;void 0===t&&(t={}),void 0===e&&(e={});const n=[...Object.keys(e),...Object.keys(t)],s={};for(const r of n)t[r]!==e[r]&&(s[r]=null!==(i=e[r])&&void 0!==i?i:"");return s}(this.attributes,t);this._attributes=t,Object.keys(e).length>0&&this.emit(js.AttributesChanged,e)}setPermissions(t){var e,i,n,s,r,o;const a=this.permissions,c=t.canPublish!==(null===(e=this.permissions)||void 0===e?void 0:e.canPublish)||t.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||t.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||t.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||t.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((t,e)=>{var i;return t!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[e])}))||t.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=t,c&&this.emit(js.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(js.IsSpeakingChanged,t))}setConnectionQuality(t){const e=this._connectionQuality;this._connectionQuality=function(t){switch(t){case ee.EXCELLENT:return Ma.Excellent;case ee.GOOD:return Ma.Good;case ee.POOR:return Ma.Poor;case ee.LOST:return Ma.Lost;default:return Ma.Unknown}}(t),e!==this._connectionQuality&&this.emit(js.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var t,e;this.activeFuture&&(null===(e=(t=this.activeFuture).reject)||void 0===e||e.call(t,Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(t){this.audioContext=t,this.audioTrackPublications.forEach((e=>Xr(e.track)&&e.track.setAudioContext(t)))}addTrackPublication(t){switch(t.on(Ds.Muted,(()=>{this.emit(js.TrackMuted,t)})),t.on(Ds.Unmuted,(()=>{this.emit(js.TrackUnmuted,t)})),t.track&&(t.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case mr.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case mr.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class sc extends nc{constructor(t,e,i,n,s,r){super(t,e,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=ve.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Gr)},this.handleReconnected=()=>{var t,e;null===(e=null===(t=this.reconnectFuture)||void 0===t?void 0:t.resolve)||void 0===e||e.call(t),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var t,e,i,n,s,r;this.reconnectFuture&&(this.reconnectFuture.promise.catch((t=>this.log.warn(t.message,this.logContext))),null===(e=null===(t=this.reconnectFuture)||void 0===t?void 0:t.reject)||void 0===e||e.call(t,Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(r=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=t=>{var e,i;t.participant&&this.updateInfo(t.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Gr),null===(i=(e=this.signalConnectedFuture).resolve)||void 0===i||i.call(e)},this.handleSignalRequestResponse=t=>{const{requestId:e,reason:i,message:n}=t,s=this.pendingSignalRequests.get(e);s&&(i!==Ji.OK&&s.reject(new qs(n,i)),this.pendingSignalRequests.delete(e))},this.handleDataPacket=t=>{switch(t.value.case){case"rpcResponse":let e=t.value.value,i=null,n=null;"payload"===e.value.case?i=e.value.value:"error"===e.value.case&&(n=oa.fromProto(e.value.value)),this.handleIncomingRpcResponse(e.requestId,i,n);break;case"rpcAck":this.handleIncomingRpcAck(t.value.value.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((t=>function(t){var e,i,n;if(!t.participantSid&&!t.participantIdentity)throw Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ii({participantIdentity:null!==(e=t.participantIdentity)&&void 0!==e?e:"",participantSid:null!==(i=t.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=t.allowAll)&&void 0!==n&&n,trackSids:t.allowedTrackSids||[]})}(t))))},this.onTrackUnmuted=t=>{this.onTrackMuted(t,t.isUpstreamPaused)},this.onTrackMuted=(t,e)=>{void 0===e&&(e=!0),t.sid?this.engine.updateMuteStatus(t.sid,e):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),hr(t)))},this.onTrackUpstreamPaused=t=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),hr(t))),this.onTrackMuted(t,!0)},this.onTrackUpstreamResumed=t=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),hr(t))),this.onTrackMuted(t,t.isMuted)},this.onTrackFeatureUpdate=t=>{const e=this.audioTrackPublications.get(t.sid);e?this.engine.client.sendUpdateLocalAudioTrack(e.trackSid,e.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(t.sid),this.logContext)},this.onTrackCpuConstrained=(t,e)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),hr(e))),this.emit(js.LocalTrackCpuConstrained,t,e)},this.handleSubscribedQualityUpdate=t=>hn(this,void 0,void 0,(function*(){var e,i,n,s;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const r=this.videoTrackPublications.get(t.trackSid);if(!r)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:t.trackSid}));if(!r.videoTrack)return;const o=yield r.videoTrack.setPublishingCodecs(t.subscribedCodecs);try{for(var a,c=!0,d=ln(o);!(e=(a=yield d.next()).done);c=!0){c=!1;const t=a.value;Ys(t)&&(this.log.debug("publish ".concat(t," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),hr(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,t,r.options))}}catch(t){i={error:t}}finally{try{c||e||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}})),this.handleLocalTrackUnpublished=t=>{const e=this.trackPublications.get(t.trackSid);e?this.unpublishTrack(e.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:t.trackSid}))},this.handleTrackEnded=t=>hn(this,void 0,void 0,(function*(){if(t.source===mr.Source.ScreenShare||t.source===mr.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),hr(t))),this.unpublishTrack(t);else if(t.isUserProvided)yield t.mute();else if(io(t)||eo(t))try{if(_r())try{const e=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:t.source===mr.Source.Camera?"camera":"microphone"});if(e&&"denied"===e.state)throw this.log.warn("user has revoked access to ".concat(t.source),Object.assign(Object.assign({},this.logContext),hr(t))),e.onchange=()=>{"denied"!==e.state&&(t.isMuted||t.restartTrack(),e.onchange=null)},Error("GetUserMedia Permission denied")}catch(t){}t.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),hr(t))),io(t)?yield t.restartTrack({deviceId:"default"}):yield t.restartTrack())}catch(e){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),hr(t))),yield t.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==ve.NONE}getTrackPublication(t){const e=super.getTrackPublication(t);if(e)return e}getTrackPublicationByName(t){const e=super.getTrackPublicationByName(t);if(e)return e}setupEngine(t){var e;this.engine=t,this.engine.on(Ps.RemoteMute,((t,e)=>{const i=this.trackPublications.get(t);i&&i.track&&(e?i.mute():i.unmute())})),(null===(e=this.signalConnectedFuture)||void 0===e?void 0:e.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(Ps.Connected,this.handleReconnected).on(Ps.SignalConnected,this.handleSignalConnected).on(Ps.SignalRestarted,this.handleReconnected).on(Ps.SignalResumed,this.handleReconnected).on(Ps.Restarting,this.handleReconnecting).on(Ps.Resuming,this.handleReconnecting).on(Ps.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Ps.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Ps.Closing,this.handleClosing).on(Ps.SignalRequestResponse,this.handleSignalRequestResponse).on(Ps.DataPacketReceived,this.handleDataPacket)}setMetadata(t){return hn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:t})}))}setName(t){return hn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:t})}))}setAttributes(t){return hn(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:t})}))}requestMetadataUpdate(t){return hn(this,arguments,void 0,(function(t){var e=this;let{metadata:i,name:n,attributes:s}=t;return function*(){return new ws(((t,r)=>hn(e,void 0,void 0,(function*(){var e,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(e=null!=i?i:this.metadata)&&void 0!==e?e:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:t,reject:t=>{r(t),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((t=>{let[e,i]=t;return this.attributes[e]===i||""===i&&!this.attributes[e]}))))return this.pendingSignalRequests.delete(c),void t();yield yr(50)}r(new qs("Request to update local metadata timed out","TimeoutError"))}catch(t){r(t instanceof Error?t:Error(t+""))}}))))}()}))}setCameraEnabled(t,e,i){return this.setTrackEnabled(mr.Source.Camera,t,e,i)}setMicrophoneEnabled(t,e,i){return this.setTrackEnabled(mr.Source.Microphone,t,e,i)}setScreenShareEnabled(t,e,i){return this.setTrackEnabled(mr.Source.ScreenShare,t,e,i)}setE2EEEnabled(t){return hn(this,void 0,void 0,(function*(){this.encryptionType=t?ve.GCM:ve.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,e,i,n){return hn(this,void 0,void 0,(function*(){var s,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:e})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(t);if(e)if(o)yield o.unmute();else{let e;if(this.pendingPublishing.has(t)){const e=yield this.waitForPendingPublicationOfSource(t);return e||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t})),yield null==e?void 0:e.unmute(),e}this.pendingPublishing.add(t);try{switch(t){case mr.Source.Camera:e=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case mr.Source.Microphone:e=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case mr.Source.ScreenShare:e=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Us(t)}}catch(i){throw null==e||e.forEach((t=>{t.stop()})),i instanceof Error&&this.emit(js.MediaDevicesError,i,ar(t)),this.pendingPublishing.delete(t),i}for(const n of e){const e=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);t===mr.Source.Microphone&&Xr(n)&&e.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{const t=[];for(const i of e)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),hr(i))),t.push(this.publishTrack(i,n));const i=yield Promise.all(t);[o]=i}catch(t){throw null==e||e.forEach((t=>{t.stop()})),t}finally{this.pendingPublishing.delete(t)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(t)&&(o=yield this.waitForPendingPublicationOfSource(t),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t}))),o&&o.track)if(t===mr.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const t=this.getTrackPublication(mr.Source.ScreenShareAudio);t&&t.track&&this.unpublishTrack(t.track)}else yield o.mute();return o}))}enableCameraAndMicrophone(){return hn(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(mr.Source.Camera)&&!this.pendingPublishing.has(mr.Source.Microphone)){this.pendingPublishing.add(mr.Source.Camera),this.pendingPublishing.add(mr.Source.Microphone);try{const t=yield this.createTracks({audio:!0,video:!0});yield Promise.all(t.map((t=>this.publishTrack(t))))}finally{this.pendingPublishing.delete(mr.Source.Camera),this.pendingPublishing.delete(mr.Source.Microphone)}}}))}createTracks(t){return hn(this,void 0,void 0,(function*(){var e,i;null!=t||(t={});const n=ir(t,null===(e=this.roomOptions)||void 0===e?void 0:e.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield ic(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((t=>(Xr(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=mr.Source.Microphone,this.emit(js.AudioStreamAcquired)),to(t)&&(this.cameraError=void 0,t.source=mr.Source.Camera),t)))}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}}))}createScreenTracks(t){return hn(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Ns("getDisplayMedia not supported");void 0!==t.resolution||function(){const t=Ss();return"Safari"===(null==t?void 0:t.name)&&t.version.startsWith("17.")||"iOS"===(null==t?void 0:t.os)&&!!(null==t?void 0:t.osVersion)&&Nr(t.osVersion,"17")>=0}()||(t.resolution=er.h1080fps30.resolution);const e=function(t){var e,i;let n=null===(e=t.video)||void 0===e||e;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=xr()?Object.assign(Object.assign({},n),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:null!==(i=t.audio)&&void 0!==i&&i,video:n,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}(t),i=yield navigator.mediaDevices.getDisplayMedia(e),n=i.getVideoTracks();if(0===n.length)throw new Us("no video track found");const s=new Aa(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=mr.Source.ScreenShare,t.contentHint&&(s.mediaStreamTrack.contentHint=t.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(js.AudioStreamAcquired);const t=new ma(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=mr.Source.ScreenShareAudio,r.push(t)}return r}))}publishTrack(t,e){return hn(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(t,e)}))}publishOrRepublishTrack(t,e){return hn(this,arguments,void 0,(function(t,e){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,o,a;let c,d;if(io(t)&&t.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),$r(t)&&i.pendingPublishPromises.has(t)&&(yield i.pendingPublishPromises.get(t)),t instanceof MediaStreamTrack)c=t.getConstraints();else{let e;switch(c=t.constraints,t.source){case mr.Source.Microphone:e="audioinput";break;case mr.Source.Camera:e="videoinput"}e&&i.activeDeviceMap.has(e)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(e)}))}if(t instanceof MediaStreamTrack)switch(t.kind){case"audio":t=new ma(t,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":t=new Aa(t,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Us("unsupported MediaStreamTrack kind ".concat(t.kind))}else t.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach((e=>{e.track&&e.track===t&&(d=e)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),hr(d))),d;const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),e),l="channelCount"in t.mediaStreamTrack.getSettings()&&2===t.mediaStreamTrack.getSettings().channelCount||2===t.mediaStreamTrack.getConstraints().channelCount,u=null!==(r=h.forceStereo)&&void 0!==r?r:l;u&&(void 0===h.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),hr(t))),void 0===h.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=h.dtx)&&void 0!==o||(h.dtx=!1),null!==(a=h.red)&&void 0!==a||(h.red=!1)),!function(){const t=Ss(),e="17.2";if(t)return"Safari"!==t.name&&"iOS"!==t.os||!!("iOS"===t.os&&t.osVersion&&Nr(t.osVersion,e)>=0)||"Safari"===t.name&&Nr(t.version,e)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),h.simulcast=!1),h.source&&(t.source=h.source);const f=new Promise(((e,n)=>hn(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==Oo.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:hr(t)}));let i=!1;const s=setTimeout((()=>{i=!0,t.stop(),n(new Vs("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(s),i)return;const r=yield this.publish(t,h,u);e(r)}else try{const i=yield this.publish(t,h,u);e(i)}catch(t){n(t)}}catch(t){n(t)}}))));i.pendingPublishPromises.set(t,f);try{return yield f}catch(t){throw t}finally{i.pendingPublishPromises.delete(t)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Gr),this.signalConnectedFuture.promise}hasPermissionsToPublish(t){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),hr(t))),!1;const{canPublish:e,canPublishSources:i}=this.permissions;return!(!e||0!==i.length&&!i.map((t=>function(t){switch(t){case Xt.CAMERA:return mr.Source.Camera;case Xt.MICROPHONE:return mr.Source.Microphone;case Xt.SCREEN_SHARE:return mr.Source.ScreenShare;case Xt.SCREEN_SHARE_AUDIO:return mr.Source.ScreenShareAudio;default:return mr.Source.Unknown}}(t))).includes(t.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),hr(t))),!1)}publish(t,e,i){return hn(this,void 0,void 0,(function*(){var n,s,r,o,a,c,d,h,l,u;if(!this.hasPermissionsToPublish(t))throw new Vs("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>$r(t)&&e.source===t.source))&&t.source!==mr.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),hr(t))),e.stopMicTrackOnMute&&Xr(t)&&(t.stopOnMute=!0),t.source===mr.Source.ScreenShare&&Er()&&(e.simulcast=!1),"av1"!==e.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(xr()||Er())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t)for(const i of t.codecs)if("video/av1"===i.mimeType.toLowerCase()){e=!0;break}return e}()||(e.videoCodec=void 0),"vp9"!==e.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Er())return!1;if(xr()){const t=Ss();if((null==t?void 0:t.version)&&Nr(t.version,"16")<0)return!1;if("iOS"===(null==t?void 0:t.os)&&(null==t?void 0:t.osVersion)&&Nr(t.osVersion,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t)for(const i of t.codecs)if("video/vp9"===i.mimeType.toLowerCase()){e=!0;break}return e}()||(e.videoCodec=void 0),void 0===e.videoCodec&&(e.videoCodec=Zo),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((t=>e.videoCodec===cr(t.mime)))||(e.videoCodec=cr(this.enabledPublishVideoCodecs[0].mime)));const f=e.videoCodec;t.on(Ds.Muted,this.onTrackMuted),t.on(Ds.Unmuted,this.onTrackUnmuted),t.on(Ds.Ended,this.handleTrackEnded),t.on(Ds.UpstreamPaused,this.onTrackUpstreamPaused),t.on(Ds.UpstreamResumed,this.onTrackUpstreamResumed),t.on(Ds.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],m=!(null===(n=e.dtx)||void 0===n||n),p=t.getSourceTrackSettings();p.autoGainControl&&v.push(oe.TF_AUTO_GAIN_CONTROL),p.echoCancellation&&v.push(oe.TF_ECHO_CANCELLATION),p.noiseSuppression&&v.push(oe.TF_NOISE_SUPPRESSION),p.channelCount&&p.channelCount>1&&v.push(oe.TF_STEREO),m&&v.push(oe.TF_NO_DTX),io(t)&&t.hasPreConnectBuffer&&v.push(oe.TF_PRECONNECT_BUFFER);const g=new ii({cid:t.mediaStreamTrack.id,name:e.name,type:mr.kindToProto(t.kind),muted:t.isMuted,source:mr.sourceToProto(t.source),disableDtx:m,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=e.red)||void 0===s||s),stream:null==e?void 0:e.stream,backupCodecPolicy:null==e?void 0:e.backupCodecPolicy,audioFeatures:v});let b;if(t.kind===mr.Kind.Video){let i={width:0,height:0};try{i=yield t.waitForDimensions()}catch(e){const n=null!==(o=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==o?o:Xs.h720.resolution;i={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{dims:i}))}g.width=i.width,g.height=i.height,eo(t)&&(Tr(f)&&(t.source===mr.Source.ScreenShare&&(e.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),hr(t))))),e.scalabilityMode=null!==(a=e.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),g.simulcastCodecs=[new ei({codec:f,cid:t.mediaStreamTrack.id})],!0===e.backupCodec&&(e.backupCodec={codec:Zo}),e.backupCodec&&f!==e.backupCodec.codec&&g.encryption===ve.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new ei({codec:e.backupCodec.codec,cid:""})))),b=Ta(t.source===mr.Source.ScreenShare,g.width,g.height,e),g.layers=Ia(g.width,g.height,b,Tr(e.videoCodec))}else t.kind===mr.Kind.Audio&&(b=[{maxBitrate:null===(c=e.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(h=null===(d=e.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==h?h:"high",networkPriority:null!==(u=null===(l=e.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high"}]);if(!this.engine||this.engine.isClosed)throw new Bs("cannot publish track when not connected");const y=()=>hn(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new Bs("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,e,b),this.emit(js.LocalSenderCreated,t.sender,t),eo(t)&&(null!==(i=e.degradationPreference)&&void 0!==i||(e.degradationPreference=function(t){return t.source===mr.Source.ScreenShare||t.constraints.height&&Qr(t.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(e.degradationPreference)),b)if(Er()&&t.kind===mr.Kind.Audio){let e;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===t.sender){e=i;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(n=b[0])||void 0===n?void 0:n.maxBitrate)?b[0].maxBitrate/1e3:0})}else t.codec&&Tr(t.codec)&&(null===(s=b[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:t.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()}));let w;const k=new Promise(((e,i)=>hn(this,void 0,void 0,(function*(){var n;try{w=yield this.engine.addTrack(g),e(w)}catch(e){t.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(t.sender),yield this.engine.negotiate().catch((e=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{error:e}))}))),i(e)}}))));if(this.enabledPublishVideoCodecs.length>0){const t=yield Promise.all([k,y()]);w=t[0]}else{let i;if(w=yield k,w.codecs.forEach((t=>{void 0===i&&(i=t.mimeType)})),i&&t.kind===mr.Kind.Video){const n=cr(i);n!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{codec:n})),e.videoCodec=n,b=Ta(t.source===mr.Source.ScreenShare,g.width,g.height,e))}yield y()}const T=new ec(t.kind,w,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(T.on(Ds.CpuConstrained,(t=>this.onTrackCpuConstrained(t,T))),T.options=e,t.sid=w.sid,this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:w})),eo(t)?t.startMonitor(this.engine.client):io(t)&&t.startMonitor(),this.addTrackPublication(T),this.emit(js.LocalTrackPublished,T),io(t)&&w.audioFeatures.includes(oe.TF_PRECONNECT_BUFFER)){const e=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(js.LocalTrackSubscribed,(e=>{if(e.trackSid===w.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),hr(t))),t.stopPreConnectBuffer()}})),e){const n=new Promise(((n,s)=>hn(this,void 0,void 0,(function*(){var r,o,a,c,d;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),hr(t)));const f=setTimeout((()=>{s(Error("agent not active within 10 seconds"))}),1e4),v=yield this.waitUntilActiveAgentPresent();clearTimeout(f),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),hr(t)));const m=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[v.identity],attributes:{trackId:T.trackSid,sampleRate:(null!==(c=p.sampleRate)&&void 0!==c?c:"48000")+"",channels:(null!==(d=p.channelCount)&&void 0!==d?d:"1")+""}});try{for(var h,l=!0,u=ln(e);!(r=(h=yield u.next()).done);l=!0){l=!1;const t=h.value;yield m.write(t)}}catch(t){o={error:t}}finally{try{l||r||!(a=u.return)||(yield a.call(u))}finally{if(o)throw o.error}}yield m.close(),n()}catch(t){s(t)}}))));n.then((()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),hr(t)))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{error:e}))}))}}return T}))}get isLocal(){return!0}publishAdditionalCodecForTrack(t,e,i){return hn(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==ve.NONE)return;let s;if(this.trackPublications.forEach((e=>{e.track&&e.track===t&&(s=e)})),!s)throw new Us("track is not published");if(!eo(t))throw new Us("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(t,e,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;e!==i.backupCodec.codec&&rn.warn("requested a different codec than specified as backup",{serverRequested:e,backup:i.backupCodec.codec}),i.videoCodec=e,i.videoEncoding=i.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=t.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=t.dimensions)||void 0===o?void 0:o.height;return t.source===mr.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),Ta(t.source===mr.Source.ScreenShare,c,d,i)}(t,e,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),hr(t)));const a=t.addSimulcastTrack(e,o);if(!a)return;const c=new ii({cid:a.mediaStreamTrack.id,type:mr.kindToProto(t.kind),muted:t.isMuted,source:mr.sourceToProto(t.source),sid:t.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Ia(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Bs("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>hn(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(t,a,r,o),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(e," for track ").concat(t.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))}))}unpublishTrack(t,e){return hn(this,void 0,void 0,(function*(){var i,n;if($r(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),hr(t))),yield e)}const s=this.getPublicationForTrack(t),r=s?hr(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(t=s.track).off(Ds.Muted,this.onTrackMuted),t.off(Ds.Unmuted,this.onTrackUnmuted),t.off(Ds.Ended,this.handleTrackEnded),t.off(Ds.UpstreamPaused,this.onTrackUpstreamPaused),t.off(Ds.UpstreamResumed,this.onTrackUpstreamResumed),t.off(Ds.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===e&&(e=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),e?t.stop():t.stopMonitor();let o=!1;const a=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<na.FAILED&&a)try{for(const t of this.engine.pcManager.publisher.getTransceivers())t.sender===a&&(t.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),eo(t)){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(o=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(t){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:t}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case mr.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case mr.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(js.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(t){return hn(this,void 0,void 0,(function*(){return(yield Promise.all(t.map((t=>this.unpublishTrack(t))))).filter((t=>!!t))}))}republishAllTracks(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){e.republishPromise&&(yield e.republishPromise),e.republishPromise=new ws(((n,s)=>hn(e,void 0,void 0,(function*(){try{const e=[];this.trackPublications.forEach((i=>{i.track&&(t&&(i.options=Object.assign(Object.assign({},i.options),t)),e.push(i))})),yield Promise.all(e.map((t=>hn(this,void 0,void 0,(function*(){const e=t.track;yield this.unpublishTrack(e,!1),!i||e.isMuted||e.source===mr.Source.ScreenShare||e.source===mr.Source.ScreenShareAudio||!io(e)&&!eo(e)||e.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:t.trackSid})),yield e.restartTrack()),yield this.publishOrRepublishTrack(e,t.options,!0)}))))),n()}catch(t){s(t instanceof Error?t:Error(t+""))}finally{this.republishPromise=void 0}})))),yield e.republishPromise}()}))}publishData(t){return hn(this,arguments,void 0,(function(t){var e=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?we.RELIABLE:we.LOSSY;let s=new Oe({participantIdentity:e.identity,payload:t,destinationIdentities:i.destinationIdentities,topic:i.topic});const r=new ye({kind:n,value:{case:"user",value:s}});yield e.engine.sendDataPacket(r,n)}()}))}publishDtmf(t,e){return hn(this,void 0,void 0,(function*(){const i=new ye({kind:we.RELIABLE,value:{case:"sipDtmf",value:new xe({code:t,digit:e})}});yield this.engine.sendDataPacket(i,we.RELIABLE)}))}sendChatMessage(t,e){return hn(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:t,timestamp:Date.now(),attachedFiles:null==e?void 0:e.attachments},n=new ye({value:{case:"chatMessage",value:new _e(Object.assign(Object.assign({},i),{timestamp:U.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,we.RELIABLE),this.emit(js.ChatMessage,i),i}))}editChatMessage(t,e){return hn(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},e),{message:t,editTimestamp:Date.now()}),n=new ye({value:{case:"chatMessage",value:new _e(Object.assign(Object.assign({},i),{timestamp:U.parse(i.timestamp),editTimestamp:U.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,we.RELIABLE),this.emit(js.ChatMessage,i),i}))}sendText(t,e){return hn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(t,e)}))}streamText(t){return hn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(t)}))}sendFile(t,e){return hn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(t,e)}))}streamBytes(t){return hn(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(t)}))}performRpc(t){let{destinationIdentity:e,method:i,payload:n,responseTimeout:s=15e3}=t;return new ws(((t,r)=>hn(this,void 0,void 0,(function*(){var o,a,c,d;if(aa(n)>15360)return void r(oa.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(o=this.engine.latestJoinResponse)||void 0===o?void 0:o.serverInfo)||void 0===a?void 0:a.version)&&Nr(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void r(oa.builtIn("UNSUPPORTED_SERVER"));const h=Math.max(s,8e3),l=crypto.randomUUID();yield this.publishRpcRequest(e,l,i,n,h);const u=setTimeout((()=>{this.pendingAcks.delete(l),r(oa.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(f)}),7e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:e});const f=setTimeout((()=>{this.pendingResponses.delete(l),r(oa.builtIn("RESPONSE_TIMEOUT"))}),s);this.pendingResponses.set(l,{resolve:(e,i)=>{clearTimeout(f),this.pendingAcks.has(l)&&(this.log.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?r(i):t(null!=e?e:"")},participantIdentity:e})}))))}registerRpcMethod(t,e){this.rpcHandlers.has(t)&&this.log.warn("you're overriding the RPC handler for method ".concat(t,", in the future this will throw an error")),this.rpcHandlers.set(t,e)}unregisterRpcMethod(t){this.rpcHandlers.delete(t)}setTrackSubscriptionPermissions(t){this.participantTrackPermissions=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],this.allParticipantsAllowedToSubscribe=t,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(t){const e=this.pendingAcks.get(t);e?(e.resolve(),this.pendingAcks.delete(t)):console.error("Ack received for unexpected RPC request",t)}handleIncomingRpcResponse(t,e,i){const n=this.pendingResponses.get(t);n?(n.resolve(e,i),this.pendingResponses.delete(t)):console.error("Response received for unexpected RPC request",t)}publishRpcRequest(t,e,i,n,s){return hn(this,void 0,void 0,(function*(){const r=new ye({destinationIdentities:[t],kind:we.RELIABLE,value:{case:"rpcRequest",value:new Ie({id:e,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,we.RELIABLE)}))}handleParticipantDisconnected(t){for(const[e,{participantIdentity:i}]of this.pendingAcks)i===t&&this.pendingAcks.delete(e);for(const[e,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===t&&(n(null,oa.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(e))}setEnabledPublishCodecs(t){this.enabledPublishVideoCodecs=t.filter((t=>"video"===t.mime.split("/")[0].toLowerCase()))}updateInfo(t){return!!super.updateInfo(t)&&(t.tracks.forEach((t=>{var e,i;const n=this.trackPublications.get(t.sid);if(n){const s=n.isMuted||null!==(i=null===(e=n.track)||void 0===e?void 0:e.isUpstreamPaused)&&void 0!==i&&i;s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),hr(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}})),!0)}setActiveAgent(t){var e,i,n,s;this.firstActiveAgent=t,t&&!this.firstActiveAgent&&(this.firstActiveAgent=t),t?null===(i=null===(e=this.activeAgentFuture)||void 0===e?void 0:e.resolve)||void 0===i||i.call(e,t):null===(s=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Gr),this.activeAgentFuture.promise)}getPublicationForTrack(t){let e;return this.trackPublications.forEach((i=>{const n=i.track;n&&(t instanceof MediaStreamTrack?(io(n)||eo(n))&&n.mediaStreamTrack===t&&(e=i):t===n&&(e=i))})),e}waitForPendingPublicationOfSource(t){return hn(this,void 0,void 0,(function*(){const e=Date.now();for(;Date.now()<e+1e4;){const e=Array.from(this.pendingPublishPromises.entries()).find((e=>{let[i]=e;return i.source===t}));if(e)return e[1];yield yr(20)}}))}}class rc extends tc{constructor(t,e,i,n){super(t,e.sid,e.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=t=>{this.setTrack(void 0),this.emit(Ds.Ended,t)},this.handleVisibilityChange=t=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(t),this.logContext),this.visible=t,this.emitTrackUpdate()},this.handleVideoDimensionsChange=t=>{this.log.debug("adaptivestream video dimensions ".concat(t.width,"x").concat(t.height),this.logContext),this.videoDimensionsAdaptiveStream=t,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(e)}setSubscribed(t){const e=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const n=new li({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new De({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Ds.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(e),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?tc.SubscriptionStatus.Unsubscribed:super.isSubscribed?tc.SubscriptionStatus.Subscribed:tc.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?tc.PermissionStatus.Allowed:tc.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(t){this.isManualOperationAllowed()&&this.requestedDisabled!==!t&&(this.requestedDisabled=!t,this.emitTrackUpdate())}setVideoQuality(t){this.isManualOperationAllowed()&&this.requestedMaxQuality!==t&&(this.requestedMaxQuality=t,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(t){var e,i;this.isManualOperationAllowed()&&((null===(e=this.requestedVideoDimensions)||void 0===e?void 0:e.width)===t.width&&(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)===t.height||(ro(this.track)&&(this.requestedVideoDimensions=t),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(t){this.isManualOperationAllowed()&&ro(this.track)&&this.fps!==t&&(this.fps=t,this.emitTrackUpdate())}get videoQuality(){var t;return null!==(t=this.requestedMaxQuality)&&void 0!==t?t:vr.HIGH}setTrack(t){const e=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==t&&(n&&(n.off(Ds.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Ds.VisibilityChanged,this.handleVisibilityChange),n.off(Ds.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Ds.Unsubscribed,n)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(Ds.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(Ds.VisibilityChanged,this.handleVisibilityChange),t.on(Ds.Ended,this.handleEnded),this.emit(Ds.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(e))}setAllowed(t){const e=this.subscriptionStatus,i=this.permissionStatus;this.allowed=t,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(e)}setSubscriptionError(t){this.emit(Ds.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const e=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):e!==t.muted&&this.emit(t.muted?Ds.Muted:Ds.Unmuted)}emitSubscriptionUpdateIfChanged(t){const e=this.subscriptionStatus;t!==e&&this.emit(Ds.SubscriptionStatusChanged,e,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(Ds.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return ro(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new ui({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===mr.Kind.Video){let e=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(e)ur(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const t=function(t,e){var i;return null===(i=t.layers)||void 0===i?void 0:i.find((t=>t.quality===e))}(this.trackInfo,this.requestedMaxQuality);t&&ur(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),e=this.videoDimensionsAdaptiveStream;e?(t.width=Math.ceil(e.width),t.height=Math.ceil(e.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),t.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:vr.HIGH})),t.quality=vr.HIGH)}this.emit(Ds.UpdateSettings,t)}}class oc extends nc{static fromParticipantInfo(t,e,i){return new oc(t,e.sid,e.identity,e.name,e.metadata,e.attributes,i,e.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(t,e,i,n,s,r,o){super(e,i||"",n,s,r,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:ue.STANDARD),this.signalClient=t,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(Ds.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),hr(t)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)})),t.on(Ds.UpdateSubscription,(t=>{t.participantTracks.forEach((t=>{t.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(t)})),t.on(Ds.SubscriptionPermissionChanged,(e=>{this.emit(js.TrackSubscriptionPermissionChanged,t,e)})),t.on(Ds.SubscriptionStatusChanged,(e=>{this.emit(js.TrackSubscriptionStatusChanged,t,e)})),t.on(Ds.Subscribed,(e=>{this.emit(js.TrackSubscribed,e,t)})),t.on(Ds.Unsubscribed,(e=>{this.emit(js.TrackUnsubscribed,e,t)})),t.on(Ds.SubscriptionFailed,(e=>{this.emit(js.TrackSubscriptionFailed,t.trackSid,e)}))}getTrackPublication(t){const e=super.getTrackPublication(t);if(e)return e}getTrackPublicationByName(t){const e=super.getTrackPublicationByName(t);if(e)return e}setVolume(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mr.Source.Microphone;this.volumeMap.set(e,t);const i=this.getTrackPublication(e);i&&i.track&&i.track.setVolume(t)}getVolume(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:mr.Source.Microphone;const e=this.getTrackPublication(t);return e&&e.track?e.track.getVolume():this.volumeMap.get(t)}addSubscribedMediaTrack(t,e,i,n,s,r){let o,a=this.getTrackPublicationBySid(e);return a||e.startsWith("TR")||this.trackPublications.forEach((e=>{a||t.kind!==""+e.kind||(a=e)})),a?"ended"===t.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),hr(a))),void this.emit(js.TrackSubscriptionFailed,e)):(o="video"===t.kind?new Ya(t,e,n,s):new Ka(t,e,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)&&no(o)&&Xr(o)&&o.setVolume(this.volumeMap.get(a.source)),a):0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:e})),void this.emit(js.TrackSubscriptionFailed,e)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,e,i,n,s,r-1)}),150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(t){return this.trackPublications.get(t)}updateInfo(t){if(!super.updateInfo(t))return!1;const e=new Map,i=new Map;return t.tracks.forEach((t=>{var n,s;let r=this.getTrackPublicationBySid(t.sid);if(r)r.updateInfo(t);else{const e=mr.kindFromProto(t.type);if(!e)return;r=new rc(e,t,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(t),i.set(t.sid,r);const o=Array.from(this.trackPublications.values()).find((t=>t.source===(null==r?void 0:r.source)));o&&r.source!==mr.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:hr(o),newTrack:hr(r)})),this.addTrackPublication(r)}e.set(t.sid,r)})),this.trackPublications.forEach((t=>{e.has(t.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),hr(t))),this.unpublishTrack(t.trackSid,!0))})),i.forEach((t=>{this.emit(js.TrackPublished,t)})),!0}unpublishTrack(t,e){const i=this.trackPublications.get(t);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case mr.Kind.Audio:this.audioTrackPublications.delete(t);break;case mr.Kind.Video:this.videoTrackPublications.delete(t)}e&&this.emit(js.TrackUnpublished,i)}setAudioOutput(t){return hn(this,void 0,void 0,(function*(){this.audioOutput=t;const e=[];this.audioTrackPublications.forEach((i=>{var n;Xr(i.track)&&no(i.track)&&e.push(i.track.setSinkId(null!==(n=t.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(e)}))}emit(t){for(var e=arguments.length,i=Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:t,args:i})),super.emit(t,...i)}}!function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"}(Na||(Na={}));class ac extends vn.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(t){var e,i,n,s,r;if(super(),e=this,this.state=Na.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=rn,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(t,e,i)=>hn(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!wr()&&!kr())throw Ir()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const s=yield this.disconnectLock.lock();if(this.state===Na.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(Na.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:""+n.getServerUrl())!==oo(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Rr(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new ra(t,e):this.regionUrlProvider.updateToken(e),this.regionUrlProvider.fetchRegionSettings().then((t=>{var e;null===(e=this.regionUrlProvider)||void 0===e||e.setServerReportedRegions(t)})).catch((t=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:t}))})));const r=(n,o,a)=>hn(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const h=new AbortController;this.abortController=h,null==s||s();try{if(yield bo.getInstance().getBackOffPromise(t),h.signal.aborted)throw Ms.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=a?a:t,e,i,h),this.abortController=void 0,n()}catch(e){if(this.regionUrlProvider&&e instanceof Ms&&e.reason!==Cs.Cancelled&&e.reason!==Cs.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(t){if(t instanceof Ms&&(401===t.status||t.reason===Cs.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(t)}[Cs.InternalError,Cs.ServerUnreachable,Cs.Timeout].includes(e.reason)&&(this.log.debug("Adding failed connection attempt to back off"),bo.getInstance().addFailedConnectionAttempt(t)),i&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(e.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield r(n,o,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Kr(e)),o(e))}else{let t=ne.UNKNOWN_REASON;e instanceof Ms&&(t=Kr(e)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),o(e)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Gr(((t,e)=>{r(t,e,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(t,e,i,n,s,r)=>hn(this,void 0,void 0,(function*(){var o,a,c;const d=yield i.join(t,e,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal,!s.singlePeerConnection);let h=d.serverInfo;if(h||(h={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=h,this.log.debug("connected to Livekit Server ".concat(Object.entries(h).map((t=>{let[e,i]=t;return"".concat(e,": ").concat(i)})).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!h.version)throw new Ls("unknown server version");return"0.15.1"===h.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=t=>{const e=t.participant;if(this.localParticipant.sid=e.sid,this.localParticipant.identity=e.identity,this.localParticipant.setEnabledPublishCodecs(t.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(t.sifTrailer)}catch(t){this.log.error(t instanceof Error?t.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:t}))}this.handleParticipantUpdates([e,...t.otherParticipants]),t.room&&this.handleRoomUpdate(t.room)},this.attemptConnection=(t,e,i,n)=>hn(this,void 0,void 0,(function*(){var s,r;this.state===Na.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ia),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(t,e,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Rs.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();const e=n.signal.aborted?Ms.cancelled("Signal connection aborted"):Ms.serverUnreachable("could not establish signal connection");throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof Ms&&(e.reason=t.reason,e.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),Ms.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(t){throw yield this.engine.close(),this.recreateEngine(),t}_r()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),_r()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Na.Connected),this.emit(Rs.Connected),bo.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,i=Array(t),n=0;n<t;n++)i[n]=arguments[n];return hn(e,[...i],void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s;const r=yield t.disconnectLock.lock();try{if(t.state===Na.Disconnected)return void t.log.debug("already disconnected",t.logContext);if(t.log.info("disconnect from room",Object.assign({},t.logContext)),t.state===Na.Connecting||t.state===Na.Reconnecting||t.isResuming){const e="Abort connection attempt due to user initiated disconnect";t.log.warn(e,t.logContext),null===(i=t.abortController)||void 0===i||i.abort(e),null===(s=null===(n=t.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,Ms.cancelled("Client initiated disconnect")),t.connectFuture=void 0}t.engine&&(t.engine.client.isDisconnected||(yield t.engine.client.sendLeave()),yield t.engine.close()),t.handleDisconnect(e,ne.CLIENT_INITIATED),t.engine=void 0}finally{r()}}()}))},this.onPageLeave=()=>hn(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>hn(this,void 0,void 0,(function*(){const t=[],e=Ss();if(e&&"iOS"===e.os){const e="livekit-dummy-audio-el";let i=document.getElementById(e);if(!i){i=document.createElement("audio"),i.id=e,i.autoplay=!0,i.hidden=!0;const t=Wr();t.enabled=!0;const n=new MediaStream([t]);i.srcObject=n,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(Rs.Disconnected,(()=>{null==i||i.remove(),i=null}))}t.push(i)}this.remoteParticipants.forEach((e=>{e.audioTrackPublications.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((t=>(t.muted=!1,t.play())))]),this.handleAudioPlaybackStarted()}catch(t){throw this.handleAudioPlaybackFailed(t),t}})),this.startVideo=()=>hn(this,void 0,void 0,(function*(){const t=[];for(const e of this.remoteParticipants.values())e.videoTrackPublications.forEach((e=>{var i;null===(i=e.track)||void 0===i||i.attachedElements.forEach((e=>{t.includes(e)||t.push(e)}))}));yield Promise.all(t.map((t=>t.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((t=>{"NotAllowedError"===t.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const t of this.remoteParticipants.values())this.handleParticipantDisconnected(t.identity,t);this.setAndEmitConnectionState(Na.Reconnecting)&&this.emit(Rs.Reconnecting)},this.handleSignalRestarted=t=>hn(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),Object.assign(Object.assign({},this.logContext),{region:t.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:t.serverRegion}))}catch(t){return}this.setAndEmitConnectionState(Na.Connected),this.emit(Rs.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=t=>{t.forEach((t=>{var e;if(t.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(t);""===t.identity&&(t.identity=null!==(e=this.sidToIdentity.get(t.sid))&&void 0!==e?e:"");let i=this.remoteParticipants.get(t.identity);t.state===le.DISCONNECTED?this.handleParticipantDisconnected(t.identity,i):i=this.getOrCreateParticipant(t.identity,t)}))},this.handleActiveSpeakersUpdate=t=>{const e=[],i={};t.forEach((t=>{if(i[t.sid]=!0,t.sid===this.localParticipant.sid)this.localParticipant.audioLevel=t.level,this.localParticipant.setIsSpeaking(!0),e.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(t.sid);i&&(i.audioLevel=t.level,i.setIsSpeaking(!0),e.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((t=>{i[t.sid]||(t.audioLevel=0,t.setIsSpeaking(!1))})),this.activeSpeakers=e,this.emitWhenConnected(Rs.ActiveSpeakersChanged,e)},this.handleSpeakersChanged=t=>{const e=new Map;this.activeSpeakers.forEach((t=>{const i=this.remoteParticipants.get(t.identity);i&&i.sid!==t.sid||e.set(t.sid,t)})),t.forEach((t=>{let i=this.getRemoteParticipantBySid(t.sid);t.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=t.level,i.setIsSpeaking(t.active),t.active?e.set(t.sid,i):e.delete(t.sid))}));const i=Array.from(e.values());i.sort(((t,e)=>e.audioLevel-t.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(Rs.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const e=this.getRemoteParticipantBySid(t.participantSid);if(!e)return;const i=e.getTrackPublicationBySid(t.trackSid);if(!i||!i.track)return;const n=mr.streamStateFromProto(t.state);i.track.setStreamState(n),n!==i.track.streamState&&(e.emit(js.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Rs.TrackStreamStateChanged,i,i.track.streamState,e))}))},this.handleSubscriptionPermissionUpdate=t=>{const e=this.getRemoteParticipantBySid(t.participantSid);if(!e)return;const i=e.getTrackPublicationBySid(t.trackSid);i&&i.setAllowed(t.allowed)},this.handleSubscriptionError=t=>{const e=Array.from(this.remoteParticipants.values()).find((e=>e.trackPublications.has(t.trackSid)));if(!e)return;const i=e.getTrackPublicationBySid(t.trackSid);i&&i.setSubscriptionError(t.err)},this.handleDataPacket=(t,e)=>{const i=this.remoteParticipants.get(t.participantIdentity);if("user"===t.value.case)this.handleUserPacket(i,t.value.value,t.kind,e);else if("transcription"===t.value.case)this.handleTranscription(i,t.value.value);else if("sipDtmf"===t.value.case)this.handleSipDtmf(i,t.value.value);else if("chatMessage"===t.value.case)this.handleChatMessage(i,t.value.value);else if("metrics"===t.value.case)this.handleMetrics(t.value.value,i);else if("streamHeader"===t.value.case||"streamChunk"===t.value.case||"streamTrailer"===t.value.case)this.handleDataStream(t,e);else if("rpcRequest"===t.value.case){const e=t.value.value;this.handleIncomingRpcRequest(t.participantIdentity,e.id,e.method,e.payload,e.responseTimeoutMs,e.version)}},this.handleUserPacket=(t,e,i,n)=>{this.emit(Rs.DataReceived,e.payload,t,i,e.topic,n),null==t||t.emit(js.DataReceived,e.payload,i,n)},this.handleSipDtmf=(t,e)=>{this.emit(Rs.SipDTMFReceived,e,t),null==t||t.emit(js.SipDTMFReceived,e)},this.handleTranscription=(t,e)=>{const i=e.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(e.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(e.trackId),s=function(t,e){return t.segments.map((t=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=t;var c;const d=null!==(c=e.get(i))&&void 0!==c?c:Date.now(),h=Date.now();return a?e.delete(i):e.set(i,d),{id:i,text:n,startTime:Number.parseInt(""+r),endTime:Number.parseInt(""+o),final:a,language:s,firstReceivedTime:d,lastReceivedTime:h}}))}(e,this.transcriptionReceivedTimes);null==n||n.emit(Ds.TranscriptionReceived,s),null==i||i.emit(js.TranscriptionReceived,s,n),this.emit(Rs.TranscriptionReceived,s,i,n)},this.handleChatMessage=(t,e)=>{const i=function(t){const{id:e,timestamp:i,message:n,editTimestamp:s}=t;return{id:e,timestamp:Number.parseInt(""+i),editTimestamp:s?Number.parseInt(""+s):void 0,message:n}}(e);this.emit(Rs.ChatMessage,i,t)},this.handleMetrics=(t,e)=>{this.emit(Rs.MetricsReceived,t,e)},this.handleDataStream=(t,e)=>{this.incomingDataStreamManager.handleDataStreamPacket(t,e)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Rs.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:t})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Rs.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Rs.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Rs.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>hn(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=Ss())||void 0===t?void 0:t.os)&&(yield this.selectDefaultDevices()),this.emit(Rs.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const e=this.roomInfo;this.roomInfo=t,e&&e.metadata!==t.metadata&&this.emitWhenConnected(Rs.RoomMetadataChanged,t.metadata),(null==e?void 0:e.activeRecording)!==t.activeRecording&&this.emitWhenConnected(Rs.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=t=>{t.updates.forEach((t=>{if(t.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(t.quality);const e=this.getRemoteParticipantBySid(t.participantSid);e&&e.setConnectionQuality(t.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(Rs.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(Rs.ParticipantNameChanged,t,this.localParticipant)},this.onLocalAttributesChanged=t=>{this.emit(Rs.ParticipantAttributesChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(Rs.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(Rs.TrackUnmuted,t,this.localParticipant)},this.onTrackProcessorUpdate=t=>{var e;null===(e=null==t?void 0:t.onPublish)||void 0===e||e.call(t,this)},this.onLocalTrackPublished=t=>hn(this,void 0,void 0,(function*(){var e,i,n,s,r,o;null===(e=t.track)||void 0===e||e.on(Ds.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.on(Ds.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=t.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(Rs.LocalTrackPublished,t,this.localParticipant),io(t.track)&&(yield t.track.checkForSilence())&&this.emit(Rs.LocalAudioSilenceDetected,t);const a=yield null===(o=t.track)||void 0===o?void 0:o.getDeviceId(!1),c=ar(t.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(Rs.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=t=>{var e,i;null===(e=t.track)||void 0===e||e.off(Ds.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.off(Ds.Restarted,this.onLocalTrackRestarted),this.emit(Rs.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>hn(this,void 0,void 0,(function*(){const e=yield t.getDeviceId(!1),i=ar(t.source);i&&e&&e!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(e," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,e),this.emit(Rs.ActiveDeviceChanged,i,e))})),this.onLocalConnectionQualityChanged=t=>{this.emit(Rs.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=(t,e)=>{this.emit(Rs.MediaDevicesError,t,e)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(Rs.ParticipantPermissionsChanged,t,this.localParticipant)},this.onLocalChatMessageSent=t=>{this.emit(Rs.ChatMessage,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},ea),t),this.log=on(null!==(i=this.options.loggerName)&&void 0!==i?i:tn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Xo),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ta),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},$o),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new za,this.outgoingDataStreamManager=new Qa(this.engine,this.log),this.disconnectLock=new u,this.localParticipant=new sc("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Qr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Qr(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Qr(this.options.audioOutput.deviceId)).catch((t=>this.log.warn("Could not set audio output: ".concat(t.message),this.logContext))),_r()){const t=new AbortController;null===(r=null===(s=navigator.mediaDevices)||void 0===s?void 0:s.addEventListener)||void 0===r||r.call(s,"devicechange",this.handleDeviceChange,{signal:t.signal}),ac.cleanupRegistry&&ac.cleanupRegistry.register(this,(()=>{t.abort()}))}}registerTextStreamHandler(t,e){return this.incomingDataStreamManager.registerTextStreamHandler(t,e)}unregisterTextStreamHandler(t){return this.incomingDataStreamManager.unregisterTextStreamHandler(t)}registerByteStreamHandler(t,e){return this.incomingDataStreamManager.registerByteStreamHandler(t,e)}unregisterByteStreamHandler(t){return this.incomingDataStreamManager.unregisterByteStreamHandler(t)}registerRpcMethod(t,e){if(this.rpcHandlers.has(t))throw Error("RPC handler already registered for method ".concat(t,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(t,e)}unregisterRpcMethod(t){this.rpcHandlers.delete(t)}setE2EEEnabled(t){return hn(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(t)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(t,this.localParticipant.identity)}))}setupE2EE(){var t;const e=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=e):this.e2eeManager=new go(i,e),this.e2eeManager.on(fo.ParticipantEncryptionStatusChanged,((t,e)=>{(function(t){return t.isLocal})(e)&&(this.isE2EEEnabled=t),this.emit(Rs.ParticipantEncryptionStatusChanged,t,e)})),this.e2eeManager.on(fo.EncryptionError,((t,e)=>{const i=e?this.getParticipantByIdentity(e):void 0;this.emit(Rs.EncryptionError,t,i)})),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get logContext(){var t;return{room:this.name,roomID:null===(t=this.roomInfo)||void 0===t?void 0:t.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var t,e;return null!==(e=null===(t=this.roomInfo)||void 0===t?void 0:t.activeRecording)&&void 0!==e&&e}getSid(){return this.state===Na.Disconnected?ws.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?ws.resolve(this.roomInfo.sid):new ws(((t,e)=>{const i=e=>{""!==e.sid&&(this.engine.off(Ps.RoomUpdate,i),t(e.sid))};this.engine.on(Ps.RoomUpdate,i),this.once(Rs.Disconnected,(()=>{this.engine.off(Ps.RoomUpdate,i),e(new Bs("Room disconnected before room server id was available"))}))}))}get name(){var t,e;return null!==(e=null===(t=this.roomInfo)||void 0===t?void 0:t.name)&&void 0!==e?e:""}get metadata(){var t;return null===(t=this.roomInfo)||void 0===t?void 0:t.metadata}get numParticipants(){var t,e;return null!==(e=null===(t=this.roomInfo)||void 0===t?void 0:t.numParticipants)&&void 0!==e?e:0}get numPublishers(){var t,e;return null!==(e=null===(t=this.roomInfo)||void 0===t?void 0:t.numPublishers)&&void 0!==e?e:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new La(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Ps.ParticipantUpdate,this.handleParticipantUpdates).on(Ps.RoomUpdate,this.handleRoomUpdate).on(Ps.SpeakersChanged,this.handleSpeakersChanged).on(Ps.StreamStateChanged,this.handleStreamStateUpdate).on(Ps.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Ps.SubscriptionError,this.handleSubscriptionError).on(Ps.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Ps.MediaTrackAdded,((t,e,i)=>{this.onTrackAdded(t,e,i)})).on(Ps.Disconnected,(t=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t)})).on(Ps.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Ps.DataPacketReceived,this.handleDataPacket).on(Ps.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Na.SignalReconnecting)&&this.emit(Rs.SignalReconnecting)})).on(Ps.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Na.Connected)&&this.emit(Rs.Reconnected)})).on(Ps.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Na.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Ps.Restarting,this.handleRestarting).on(Ps.SignalRestarted,this.handleSignalRestarted).on(Ps.Offline,(()=>{this.setAndEmitConnectionState(Na.Reconnecting)&&this.emit(Rs.Reconnecting)})).on(Ps.DCBufferStatusChanged,((t,e)=>{this.emit(Rs.DCBufferStatusChanged,t,e)})).on(Ps.LocalTrackSubscribed,(t=>{const e=this.localParticipant.getTrackPublications().find((e=>{let{trackSid:i}=e;return i===t}));e?(this.localParticipant.emit(js.LocalTrackSubscribed,e),this.emitWhenConnected(Rs.LocalTrackSubscribed,e,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})).on(Ps.RoomMoved,(t=>{this.log.debug("room moved",t),t.room&&this.handleRoomUpdate(t.room),this.remoteParticipants.forEach(((t,e)=>{this.handleParticipantDisconnected(e,t)})),this.emit(Rs.Moved,t.room.name),this.handleParticipantUpdates(t.participant?[t.participant,...t.otherParticipants]:t.otherParticipants)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return wo.getInstance().getDevices(t,e)}prepareConnection(t,e){return hn(this,void 0,void 0,(function*(){if(this.state===Na.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(Rr(new URL(t))&&e){this.regionUrlProvider=new ra(t,e);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Na.Disconnected&&(this.regionUrl=i,yield fetch(Hr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Hr(t),{method:"HEAD"})}catch(t){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:t}))}}}))}getParticipantByIdentity(t){return this.localParticipant.identity===t?this.localParticipant:this.remoteParticipants.get(t)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(t,e){return hn(this,void 0,void 0,(function*(){let i,n=()=>hn(this,void 0,void 0,(function*(){}));switch(t){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Ui({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Ui({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Ui({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Ui({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=()=>hn(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ui({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>hn(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ui({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 Ui({scenario:{case:"switchCandidateProtocol",value:"force-tls"===t?2:1}}),n=()=>hn(this,void 0,void 0,(function*(){const t=this.engine.client.onLeave;t&&t(new mi({reason:ne.CLIENT_INITIATED,action:pi.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===e||"number"!=typeof e)throw Error("subscriber-bandwidth requires a number as argument");i=new Ui({scenario:{case:"subscriberBandwidth",value:Zr(e)}});break;case"leave-full-reconnect":i=new Ui({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(t){return this.localParticipant.activeDeviceMap.get(t)}switchActiveDevice(t,e){return hn(this,arguments,void 0,(function(t,e){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,o,a,c,d,h;let l=!0,u=!1;const f=n?{exact:e}:e;if("audioinput"===t){u=0===i.localParticipant.audioTrackPublications.size;const e=null!==(s=i.getActiveDevice(t))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=f;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((t=>t.source===mr.Source.Microphone));try{l=(yield Promise.all(n.map((t=>{var e;return null===(e=t.audioTrack)||void 0===e?void 0:e.setDeviceId(f)})))).every((t=>!0===t))}catch(t){throw i.options.audioCaptureDefaults.deviceId=e,t}const r=n.some((t=>{var e,i;return null!==(i=null===(e=t.track)||void 0===e?void 0:e.isMuted)&&void 0!==i&&i}));l&&r&&(u=!0)}else if("videoinput"===t){u=0===i.localParticipant.videoTrackPublications.size;const e=null!==(r=i.getActiveDevice(t))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=f;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((t=>t.source===mr.Source.Camera));try{l=(yield Promise.all(n.map((t=>{var e;return null===(e=t.videoTrack)||void 0===e?void 0:e.setDeviceId(f)})))).every((t=>!0===t))}catch(t){throw i.options.videoCaptureDefaults.deviceId=e,t}const s=n.some((t=>{var e,i;return null!==(i=null===(e=t.track)||void 0===e?void 0:e.isMuted)&&void 0!==i&&i}));l&&s&&(u=!0)}else if("audiooutput"===t){if(u=!0,!Sr()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(e=null!==(o=yield wo.getInstance().normalizeDeviceId("audiooutput",e))&&void 0!==o?o:""),null!==(a=(h=i.options).audioOutput)&&void 0!==a||(h.audioOutput={});const n=null!==(c=i.getActiveDevice(t))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=e;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(e)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((t=>t.setAudioOutput({deviceId:e}))))}catch(t){throw i.options.audioOutput.deviceId=n,t}}return u&&(i.localParticipant.activeDeviceMap.set(t,e),i.emit(Rs.ActiveDeviceChanged,t,e)),l}()}))}setupLocalParticipantEvents(){this.localParticipant.on(js.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(js.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(js.AttributesChanged,this.onLocalAttributesChanged).on(js.TrackMuted,this.onLocalTrackMuted).on(js.TrackUnmuted,this.onLocalTrackUnmuted).on(js.LocalTrackPublished,this.onLocalTrackPublished).on(js.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(js.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(js.MediaDevicesError,this.onMediaDevicesError).on(js.AudioStreamAcquired,this.startAudio).on(js.ChatMessage,this.onLocalChatMessageSent).on(js.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var t;null===(t=this.engine)||void 0===t||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,e,i){if(this.state===Na.Connecting||this.state===Na.Reconnecting){const n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:t.id,mediaStreamId:e.id,tracksInStream:e.getTracks().map((t=>t.id))}),this.onTrackAdded(t,e,i),s()},s=()=>{this.off(Rs.Reconnected,n),this.off(Rs.Connected,n),this.off(Rs.Disconnected,s)};return this.once(Rs.Reconnected,n),this.once(Rs.Connected,n),void this.once(Rs.Disconnected,s)}if(this.state===Na.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===t.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(t){const e=t.split("|");return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}(e.id),s=n[0];let r=n[1],o=t.id;if(r&&r.startsWith("TR")&&(o=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find((t=>t.sid===s));if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);if(!o.startsWith("TR")){const t=this.engine.getTrackIdForReceiver(i);if(!t)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(s),this.logContext);o=t}let c;o.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(s,", streamId: ").concat(r,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:s,streamId:r,trackId:o})),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=a.addSubscribedMediaTrack(t,o,e,i,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit(Rs.EncryptionError,Error("Encrypted ".concat(d.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],e=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.state!==Na.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach((t=>{t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid)}))})),this.localParticipant.trackPublications.forEach((e=>{var i,n,s;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop()):null===(s=e.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(js.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(js.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(js.AttributesChanged,this.onLocalAttributesChanged).off(js.TrackMuted,this.onLocalTrackMuted).off(js.TrackUnmuted,this.onLocalTrackUnmuted).off(js.LocalTrackPublished,this.onLocalTrackPublished).off(js.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(js.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(js.MediaDevicesError,this.onMediaDevicesError).off(js.AudioStreamAcquired,this.startAudio).off(js.ChatMessage,this.onLocalChatMessageSent).off(js.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),_r()&&(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(Na.Disconnected),this.emit(Rs.Disconnected,e)}}}handleParticipantDisconnected(t,e){var i;this.remoteParticipants.delete(t),e&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(t),e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid,!0)})),this.emit(Rs.ParticipantDisconnected,e),e.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(e.identity))}handleIncomingRpcRequest(t,e,i,n,s,r){return hn(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(t,e),1!==r)return void(yield this.engine.publishRpcResponse(t,e,null,oa.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(t,e,null,oa.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:e,callerIdentity:t,payload:n,responseTimeout:s});aa(r)>15360?(a=oa.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=r}catch(t){t instanceof oa?a=t:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),t),a=oa.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(t,e,c,a)}))}selectDefaultDevices(){return hn(this,void 0,void 0,(function*(){var t,e,i;const n=wo.getInstance().previousDevices,s=yield wo.getInstance().getDevices(void 0,!1),r=Ss();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let t of s){const e=n.find((e=>e.deviceId===t.deviceId));e&&""!==e.label&&e.kind===t.kind&&e.label!==t.label&&"default"===this.getActiveDevice(t.kind)&&this.emit(Rs.ActiveDeviceChanged,t.kind,t.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let r of o){const o=or(r),a=this.localParticipant.getTrackPublication(o);if(a&&(null===(t=a.track)||void 0===t?void 0:t.isUserProvided))continue;const c=s.filter((t=>t.kind===r)),d=this.getActiveDevice(r);d===(null===(e=n.filter((t=>t.kind===r))[0])||void 0===e?void 0:e.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(r,c[0].deviceId):"audioinput"===r&&!Ar()||"videoinput"===r||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(r)))||"audiooutput"===r&&Ar()||(yield this.switchActiveDevice(r,c[0].deviceId))}}))}acquireAudioContext(){return hn(this,void 0,void 0,(function*(){var t,e;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!==(t=rr())&&void 0!==t?t:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((t=>t.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),yr(200)])}catch(t){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:t}))}const i="running"===(null===(e=this.audioContext)||void 0===e?void 0:e.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Rs.AudioPlaybackStatusChanged,i))}))}createParticipant(t,e){var i;let n;return n=e?oc.fromParticipantInfo(this.engine.client,e,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new oc(this.engine.client,"",t,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((t=>this.log.warn("Could not set audio output: ".concat(t.message),this.logContext))),n}getOrCreateParticipant(t,e){if(this.remoteParticipants.has(t)){const i=this.remoteParticipants.get(t);return e&&i.updateInfo(e)&&this.sidToIdentity.set(e.sid,e.identity),i}const i=this.createParticipant(t,e);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(e.sid,e.identity),this.emitWhenConnected(Rs.ParticipantConnected,i),i.on(js.TrackPublished,(t=>{this.emitWhenConnected(Rs.TrackPublished,t,i)})).on(js.TrackSubscribed,((t,e)=>{t.kind===mr.Kind.Audio?(t.on(Ds.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(Ds.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===mr.Kind.Video&&(t.on(Ds.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(Ds.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Rs.TrackSubscribed,t,e,i)})).on(js.TrackUnpublished,(t=>{this.emit(Rs.TrackUnpublished,t,i)})).on(js.TrackUnsubscribed,((t,e)=>{this.emit(Rs.TrackUnsubscribed,t,e,i)})).on(js.TrackMuted,(t=>{this.emitWhenConnected(Rs.TrackMuted,t,i)})).on(js.TrackUnmuted,(t=>{this.emitWhenConnected(Rs.TrackUnmuted,t,i)})).on(js.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(Rs.ParticipantMetadataChanged,t,i)})).on(js.ParticipantNameChanged,(t=>{this.emitWhenConnected(Rs.ParticipantNameChanged,t,i)})).on(js.AttributesChanged,(t=>{this.emitWhenConnected(Rs.ParticipantAttributesChanged,t,i)})).on(js.ConnectionQualityChanged,(t=>{this.emitWhenConnected(Rs.ConnectionQualityChanged,t,i)})).on(js.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(Rs.ParticipantPermissionsChanged,t,i)})).on(js.TrackSubscriptionStatusChanged,((t,e)=>{this.emitWhenConnected(Rs.TrackSubscriptionStatusChanged,t,e,i)})).on(js.TrackSubscriptionFailed,((t,e)=>{this.emit(Rs.TrackSubscriptionFailed,t,i,e)})).on(js.TrackSubscriptionPermissionChanged,((t,e)=>{this.emitWhenConnected(Rs.TrackSubscriptionPermissionChanged,t,e,i)})).on(js.Active,(()=>{this.emitWhenConnected(Rs.ParticipantActive,i),i.kind===ue.AGENT&&this.localParticipant.setActiveAgent(i)})),e&&i.updateInfo(e),i}sendSyncState(){const t=Array.from(this.remoteParticipants.values()).reduce(((t,e)=>(t.push(...e.getTrackPublications()),t)),[]),e=this.localParticipant.getTrackPublications();this.engine.sendSyncState(t,e)}updateSubscriptions(){for(const t of this.remoteParticipants.values())for(const e of t.videoTrackPublications.values())e.isSubscribed&&so(e)&&e.emitTrackUpdate()}getRemoteParticipantBySid(t){const e=this.sidToIdentity.get(t);if(e)return this.remoteParticipants.get(e)}registerConnectionReconcile(){this.clearConnectionReconcile();let t=0;this.connectionReconcileInterval=Ws.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?t=0:(t++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:t,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),t>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ne.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ws.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(Rs.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((t=>{let[e,i]=t;this.emit(e,...i)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var e=arguments.length,i=Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];if(this.state===Na.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===Na.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){return hn(this,void 0,void 0,(function*(){var e,i,n,s;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new ae({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:U.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new he({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Rs.SignalConnected),this.emit(Rs.Connected),this.setAndEmitConnectionState(Na.Connected),r.video){const t=new ec(mr.Kind.Video,new pe({source:Xt.CAMERA,sid:""+Math.floor(1e4*Math.random()),type:$t.AUDIO,name:"video-dummy"}),new Aa(r.useRealTracks&&(null===(e=window.navigator.mediaDevices)||void 0===e?void 0:e.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:zr(160*(null!==(i=o.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(t),this.localParticipant.emit(js.LocalTrackPublished,t)}if(r.audio){const t=new ec(mr.Kind.Audio,new pe({source:Xt.MICROPHONE,sid:""+Math.floor(1e4*Math.random()),type:$t.AUDIO}),new ma(r.useRealTracks&&(null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Wr(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(js.LocalTrackPublished,t)}for(let t=0;t<o.count-1;t+=1){let e=new he({sid:""+Math.floor(1e4*Math.random()),identity:"simulated-".concat(t),state:le.ACTIVE,tracks:[],joinedAt:U.parse(Date.now())});const i=this.getOrCreateParticipant(e.identity,e);if(o.video){const n=zr(160*(null!==(s=o.aspectRatios[t%o.aspectRatios.length])&&void 0!==s?s:1),160,!1,!0),r=new pe({source:Xt.CAMERA,sid:""+Math.floor(1e4*Math.random()),type:$t.AUDIO});i.addSubscribedMediaTrack(n,r.sid,new MediaStream([n]),new RTCRtpReceiver),e.tracks=[...e.tracks,r]}if(o.audio){const t=Wr(),n=new pe({source:Xt.MICROPHONE,sid:""+Math.floor(1e4*Math.random()),type:$t.AUDIO});i.addSubscribedMediaTrack(t,n.sid,new MediaStream([t]),new RTCRtpReceiver),e.tracks=[...e.tracks,n]}i.updateInfo(e)}}))}emit(t){for(var e=arguments.length,i=Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];if(t!==Rs.ActiveSpeakersChanged&&t!==Rs.TranscriptionReceived){const e=cc(i).filter((t=>void 0!==t));t!==Rs.TrackSubscribed&&t!==Rs.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:e})),this.log.debug("room event ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:e}))}return super.emit(t,...i)}}function cc(t){return t.map((t=>{if(t)return Array.isArray(t)?cc(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t}))}function dc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return t+""}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}ac.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((t=>{t()})),function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"}(Ua||(Ua={})),new TextEncoder,new TextDecoder;class hc extends Error{constructor(t,e){var i;super(t,e),dc(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}function lc(){return lc=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)({}).hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},lc.apply(null,arguments)}dc(hc,"code","ERR_JOSE_GENERIC"),dc(class extends hc{constructor(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(t,{cause:{claim:i,reason:n,payload:e}}),dc(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),dc(this,"claim",void 0),dc(this,"reason",void 0),dc(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=e}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),dc(class extends hc{constructor(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(t,{cause:{claim:i,reason:n,payload:e}}),dc(this,"code","ERR_JWT_EXPIRED"),dc(this,"claim",void 0),dc(this,"reason",void 0),dc(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=e}},"code","ERR_JWT_EXPIRED"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED"),dc(class extends hc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),dc(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID"),dc(class extends hc{constructor(){super(...arguments),dc(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID"),dc(class extends hc{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),dc(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY"),dc(class extends hc{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),dc(this,Symbol.asyncIterator,void 0),dc(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS"),dc(class extends hc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),dc(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT"),dc(class extends hc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),dc(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const uc=new Uint8Array(0);class fc{static getFullOptions(t){return lc({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},t)}constructor(t,e){var i=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(t){"connected"!==i.status&&"connecting"!==i.status||(i.updateStatus("disconnecting"),await i.handleEndSession(),i.updateStatus("disconnected"),i.options.onDisconnect&&i.options.onDisconnect(t))},this.onMessage=async function(t){switch(t.type){case"interruption":return void i.handleInterruption(t);case"agent_response":return void i.handleAgentResponse(t);case"user_transcript":return void i.handleUserTranscript(t);case"internal_tentative_agent_response":return void i.handleTentativeAgentResponse(t);case"client_tool_call":try{await i.handleClientToolCall(t)}catch(e){i.onError("Unexpected error in client tool call handling: "+(e instanceof Error?e.message:e+""),{clientToolName:t.client_tool_call.tool_name,toolCallId:t.client_tool_call.tool_call_id})}return;case"audio":return void i.handleAudio(t);case"vad_score":return void i.handleVadScore(t);case"ping":return void i.connection.sendMessage({type:"pong",event_id:t.ping_event.event_id});case"mcp_tool_call":return void i.handleMCPToolCall(t);case"mcp_connection_status":return void i.handleMCPConnectionStatus(t);case"agent_tool_request":return void i.handleAgentToolRequest(t);case"agent_tool_response":return void i.handleAgentToolResponse(t);case"conversation_initiation_metadata":return void i.handleConversationMetadata(t);case"asr_initiation_metadata":return void i.handleAsrInitiationMetadata(t);case"agent_chat_response_part":return void i.handleAgentChatResponsePart(t);case"error":return void i.handleErrorEvent(t);default:return void(i.options.onDebug&&i.options.onDebug(t))}},this.setVolume=({volume:t})=>{this.volume=t},this.options=t,this.connection=e,this.options.onConnect&&this.options.onConnect({conversationId:e.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange((t=>this.updateMode(t))),this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}async handleEndSession(){this.connection.close()}updateMode(t){t!==this.mode&&(this.mode=t,this.options.onModeChange&&this.options.onModeChange({mode:t}))}updateStatus(t){t!==this.status&&(this.status=t,this.options.onStatusChange&&this.options.onStatusChange({status:t}))}updateCanSendFeedback(){const t=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==t&&(this.canSendFeedback=t,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:t}))}handleInterruption(t){t.interruption_event&&(this.lastInterruptTimestamp=t.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:t.interruption_event.event_id}))}handleAgentResponse(t){this.options.onMessage&&this.options.onMessage({source:"ai",role:"agent",message:t.agent_response_event.agent_response})}handleUserTranscript(t){this.options.onMessage&&this.options.onMessage({source:"user",role:"user",message:t.user_transcription_event.user_transcript})}handleTentativeAgentResponse(t){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:t.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(t){this.options.onVadScore&&this.options.onVadScore({vadScore:t.vad_score_event.vad_score})}async handleClientToolCall(t){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,t.client_tool_call.tool_name))try{var e;const i=null!=(e=await this.options.clientTools[t.client_tool_call.tool_name](t.client_tool_call.parameters))?e:"Client tool execution successful.",n="object"==typeof i?JSON.stringify(i):i+"";this.connection.sendMessage({type:"client_tool_result",tool_call_id:t.client_tool_call.tool_call_id,result:n,is_error:!1})}catch(e){this.onError("Client tool execution failed with following error: "+(null==e?void 0:e.message),{clientToolName:t.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:t.client_tool_call.tool_call_id,result:"Client tool execution failed: "+(null==e?void 0:e.message),is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(t.client_tool_call);this.onError(`Client tool with name ${t.client_tool_call.tool_name} is not defined on client`,{clientToolName:t.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:t.client_tool_call.tool_call_id,result:`Client tool with name ${t.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(t){}handleMCPToolCall(t){this.options.onMCPToolCall&&this.options.onMCPToolCall(t.mcp_tool_call)}handleMCPConnectionStatus(t){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(t.mcp_connection_status)}handleAgentToolRequest(t){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(t.agent_tool_request)}handleAgentToolResponse(t){"end_call"===t.agent_tool_response.tool_name&&this.endSessionWithDetails({reason:"agent",context:new CloseEvent("end_call",{reason:"Agent ended the call"})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(t.agent_tool_response)}handleConversationMetadata(t){this.options.onConversationMetadata&&this.options.onConversationMetadata(t.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(t){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(t.asr_initiation_metadata_event)}handleAgentChatResponsePart(t){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(t.text_response_part)}handleErrorEvent(t){const e=t.error_event.error_type,i=t.error_event.message||t.error_event.reason||"Unknown error";"max_duration_exceeded"!==e?this.onError("Server error: "+i,{errorType:e,code:t.error_event.code,debugMessage:t.error_event.debug_message,details:t.error_event.details}):this.endSessionWithDetails({reason:"error",message:i,context:new Event("max_duration_exceeded")})}onError(t,e){console.error(t,e),this.options.onError&&this.options.onError(t,e)}getId(){return this.connection.conversationId}isOpen(){return"connected"===this.status}setMicMuted(t){this.connection.setMicMuted(t)}getInputByteFrequencyData(){return uc}getOutputByteFrequencyData(){return uc}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(t){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:t?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(0===this.lastFeedbackEventId?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")}sendContextualUpdate(t){this.connection.sendMessage({type:"contextual_update",text:t})}sendUserMessage(t){this.connection.sendMessage({type:"user_message",text:t})}sendUserActivity(){this.connection.sendMessage({type:"user_activity"})}sendMCPToolApprovalResult(t,e){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:t,is_approved:e})}}class vc{constructor(t={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=t.onDebug}debug(t){this.onDebug&&this.onDebug(t)}onMessage(t){this.onMessageCallback=t;const e=this.queue;this.queue=[],e.length>0&&queueMicrotask((()=>{e.forEach(t)}))}onDisconnect(t){this.onDisconnectCallback=t;const e=this.disconnectionDetails;e&&queueMicrotask((()=>{t(e)}))}onModeChange(t){this.onModeChangeCallback=t}updateMode(t){var e;null==(e=this.onModeChangeCallback)||e.call(this,t)}disconnect(t){var e;this.disconnectionDetails||(this.disconnectionDetails=t,null==(e=this.onDisconnectCallback)||e.call(this,t))}handleMessage(t){this.onMessageCallback?this.onMessageCallback(t):this.queue.push(t)}}function mc(t){const[e,i]=t.split("_");if(!["pcm","ulaw"].includes(e))throw Error("Invalid format: "+t);const n=Number.parseInt(i);if(Number.isNaN(n))throw Error("Invalid sample rate: "+i);return{format:e,sampleRate:n}}const pc="0.13.0";function gc(t){return!!t.type}const bc="conversation_initiation_client_data";function yc(t){var e;const i={type:bc};var n,s,r,o,a,c,d,h;return t.overrides&&(i.conversation_config_override={agent:{prompt:null==(n=t.overrides.agent)?void 0:n.prompt,first_message:null==(s=t.overrides.agent)?void 0:s.firstMessage,language:null==(r=t.overrides.agent)?void 0:r.language},tts:{voice_id:null==(o=t.overrides.tts)?void 0:o.voiceId,speed:null==(a=t.overrides.tts)?void 0:a.speed,stability:null==(c=t.overrides.tts)?void 0:c.stability,similarity_boost:null==(d=t.overrides.tts)?void 0:d.similarityBoost},conversation:{text_only:null==(h=t.overrides.conversation)?void 0:h.textOnly}}),t.customLlmExtraBody&&(i.custom_llm_extra_body=t.customLlmExtraBody),t.dynamicVariables&&(i.dynamic_variables=t.dynamicVariables),t.userId&&(i.user_id=t.userId),null!=(e=t.overrides)&&e.client&&(i.source_info={source:t.overrides.client.source,version:t.overrides.client.version}),i}class wc extends Error{constructor(t,e){super(t),this.closeCode=void 0,this.closeReason=void 0,this.name="SessionConnectionError",this.closeCode=null==e?void 0:e.closeCode,this.closeReason=null==e?void 0:e.closeReason}}class kc extends vc{constructor(t,e,i,n){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=t,this.conversationId=e,this.inputFormat=i,this.outputFormat=n,this.socket.addEventListener("error",(t=>{setTimeout((()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:t})),0)})),this.socket.addEventListener("close",(t=>{this.disconnect(1e3===t.code?{reason:"agent",context:t,closeCode:t.code,closeReason:t.reason||void 0}:{reason:"error",message:t.reason||"The connection was closed by the server.",context:t,closeCode:t.code,closeReason:t.reason||void 0})})),this.socket.addEventListener("message",(t=>{try{const e=JSON.parse(t.data);if(!gc(e))return void this.debug({type:"invalid_event",message:"Received invalid socket event",data:t.data});this.handleMessage(e)}catch(e){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:e instanceof Error?e.message:e+"",data:t.data})}}))}static async create(t){let e=null;try{var i,n,s;const r=null!=(i=t.origin)?i:"wss://api.elevenlabs.io";let o;const a=(null==(n=t.overrides)||null==(n=n.client)?void 0:n.version)||pc,c=(null==(s=t.overrides)||null==(s=s.client)?void 0:s.source)||"js_sdk";if(t.signedUrl){const e=t.signedUrl.includes("?")?"&":"?";o=`${t.signedUrl}${e}source=${c}&version=${a}`}else o=`${r}/v1/convai/conversation?agent_id=${t.agentId}&source=${c}&version=${a}`;const d=["convai"];t.authorization&&d.push("bearer."+t.authorization),e=new WebSocket(o,d);const h=await new Promise(((i,n)=>{e.addEventListener("open",(()=>{var i;const n=yc(t);null==(i=e)||i.send(JSON.stringify(n))}),{once:!0}),e.addEventListener("error",(()=>{setTimeout((()=>n(new wc("The connection was closed due to a socket error."))),0)})),e.addEventListener("close",(t=>{n(new wc(t.reason||(1e3===t.code?"Connection closed normally before session could be established.":"Connection closed unexpectedly before session could be established."),{closeCode:t.code,closeReason:t.reason||void 0}))})),e.addEventListener("message",(t=>{const e=JSON.parse(t.data);gc(e)&&("conversation_initiation_metadata"===e.type?i(e.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))}),{once:!0})})),{conversation_id:l,agent_output_audio_format:u,user_input_audio_format:f}=h,v=mc(null!=f?f:"pcm_16000"),m=mc(u);return new kc(e,l,v,m)}catch(t){var r;throw null==(r=e)||r.close(),t}}close(){this.socket.close(1e3,"User ended conversation")}sendMessage(t){this.socket.send(JSON.stringify(t))}async setMicMuted(t){console.warn(`WebSocket connection setMicMuted called with ${t}, but this is handled by VoiceConversation`)}}function Tc(t){const e=new Uint8Array(t);return window.btoa(String.fromCharCode(...e))}function Sc(t){const e=window.atob(t),i=e.length,n=new Uint8Array(i);for(let t=0;t<i;t++)n[t]=e.charCodeAt(t);return n.buffer}const Ec=new Map;function Oc(t,e){return async(i,n)=>{const s=Ec.get(t);if(s)return i.addModule(s);if(n)try{return await i.addModule(n),void Ec.set(t,n)}catch(e){throw Error(`Failed to load the ${t} worklet module from path: ${n}. Error: ${e}`)}const r=new Blob([e],{type:"application/javascript"}),o=URL.createObjectURL(r);try{return await i.addModule(o),void Ec.set(t,o)}catch(t){URL.revokeObjectURL(o)}try{const n="data:application/javascript;base64,"+btoa(e);await i.addModule(n),Ec.set(t,n)}catch(e){throw Error(`Failed to load the ${t} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}const xc=Oc("rawAudioProcessor",'/*\n * ulaw encoding logic taken from the wavefile library\n * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js\n * USED BY @elevenlabs/client\n */\n\nconst BIAS = 0x84;\nconst CLIP = 32635;\nconst encodeTable = [\n 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,\n 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,\n 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,\n 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7\n];\n\nfunction encodeSample(sample) {\n let sign;\n let exponent;\n let mantissa;\n let muLawSample;\n sign = (sample >> 8) & 0x80;\n if (sign !== 0) sample = -sample;\n sample = sample + BIAS;\n if (sample > CLIP) sample = CLIP;\n exponent = encodeTable[(sample>>7) & 0xFF];\n mantissa = (sample >> (exponent+3)) & 0x0F;\n muLawSample = ~(sign | (exponent << 4) | mantissa);\n \n return muLawSample;\n}\n\nclass RawAudioProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n \n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.isMuted = false;\n this.buffer = []; // Initialize an empty buffer\n this.bufferSize = data.sampleRate / 4;\n this.format = data.format;\n\n if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) {\n globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => {\n this.resampler = resampler;\n });\n }\n break;\n case "setMuted":\n this.isMuted = data.isMuted;\n break;\n }\n };\n }\n process(inputs) {\n if (!this.buffer) {\n return true;\n }\n \n const input = inputs[0]; // Get the first input node\n if (input.length > 0) {\n let channelData = input[0]; // Get the first channel\'s data\n\n // Resample the audio if necessary\n if (this.resampler) {\n channelData = this.resampler.full(channelData);\n }\n\n // Add channel data to the buffer\n this.buffer.push(...channelData);\n // Get max volume \n let sum = 0.0;\n for (let i = 0; i < channelData.length; i++) {\n sum += channelData[i] * channelData[i];\n }\n const maxVolume = Math.sqrt(sum / channelData.length);\n // Check if buffer size has reached or exceeded the threshold\n if (this.buffer.length >= this.bufferSize) {\n const float32Array = this.isMuted \n ? new Float32Array(this.buffer.length)\n : new Float32Array(this.buffer);\n\n let encodedArray = this.format === "ulaw"\n ? new Uint8Array(float32Array.length)\n : new Int16Array(float32Array.length);\n\n // Iterate through the Float32Array and convert each sample to PCM16\n for (let i = 0; i < float32Array.length; i++) {\n // Clamp the value to the range [-1, 1]\n let sample = Math.max(-1, Math.min(1, float32Array[i]));\n\n // Scale the sample to the range [-32768, 32767]\n let value = sample < 0 ? sample * 32768 : sample * 32767;\n if (this.format === "ulaw") {\n value = encodeSample(Math.round(value));\n }\n\n encodedArray[i] = value;\n }\n\n // Send the buffered data to the main script\n this.port.postMessage([encodedArray, maxVolume]);\n\n // Clear the buffer after sending\n this.buffer = [];\n }\n }\n return true; // Continue processing\n }\n}\nregisterProcessor("rawAudioProcessor", RawAudioProcessor);\n');class Ac extends vc{constructor(t,e,i,n,s={}){super(s),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=t,this.conversationId=e,this.inputFormat=i,this.outputFormat=n,this.setupRoomEventListeners()}static async create(t){let e;if("conversationToken"in t&&t.conversationToken)e=t.conversationToken;else{if(!("agentId"in t)||!t.agentId)throw Error("Either conversationToken or agentId is required for WebRTC connection");try{var i,n,s;const o=(null==(i=t.overrides)||null==(i=i.client)?void 0:i.version)||pc,a=(null==(n=t.overrides)||null==(n=n.client)?void 0:n.source)||"js_sdk",c=`${r=null!=(s=t.origin)?s:"https://api.elevenlabs.io",r.replace(/^wss:\/\//,"https://")}/v1/convai/conversation/token?agent_id=${t.agentId}&source=${a}&version=${o}`,d=await fetch(c);if(!d.ok)throw Error(`ElevenLabs API returned ${d.status} ${d.statusText}`);if(e=(await d.json()).token,!e)throw Error("No conversation token received from API")}catch(e){let i=e instanceof Error?e.message:e+"";throw e instanceof Error&&e.message.includes("401")&&(i="Your agent has authentication enabled, but no signed URL or conversation token was provided."),Error(`Failed to fetch conversation token for agent ${t.agentId}: ${i}`)}}var r;const o=new ac;try{const i="room_"+Date.now(),n=mc("pcm_48000"),s=mc("pcm_48000"),r=new Ac(o,i,n,s,t),c=t.livekitUrl||"wss://livekit.rtc.elevenlabs.io";var a;await o.connect(c,e),await new Promise((t=>{if(r.isConnected)t();else{const e=()=>{o.off(Rs.Connected,e),t()};o.on(Rs.Connected,e)}})),o.name&&(r.conversationId=(null==(a=o.name.match(/(conv_[a-zA-Z0-9]+)/))?void 0:a[0])||o.name),t.textOnly||await o.localParticipant.setMicrophoneEnabled(!0);const d=yc(t);return r.debug({type:bc,message:d}),await r.sendMessage(d),r}catch(t){throw await o.disconnect(),t}}setupRoomEventListeners(){var t=this;this.room.on(Rs.Connected,(async function(){t.isConnected=!0,console.info("WebRTC room connected")})),this.room.on(Rs.Disconnected,(t=>{this.isConnected=!1,this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:null==t?void 0:""+t})})})),this.room.on(Rs.ConnectionStateChanged,(t=>{t===Na.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:"LiveKit connection state changed to "+t,context:new Event("connection_state_changed")}))})),this.room.on(Rs.DataReceived,((t,e)=>{try{const e=JSON.parse((new TextDecoder).decode(t));if("audio"===e.type)return;gc(e)?this.handleMessage(e):console.warn("Invalid socket event received:",e)}catch(e){console.warn("Failed to parse incoming data message:",e),console.warn("Raw payload:",(new TextDecoder).decode(t))}})),this.room.on(Rs.TrackSubscribed,(async function(e,i,n){if(e.kind===mr.Kind.Audio&&n.identity.includes("agent")){const i=e,n=i.attach();if(n.autoplay=!0,n.controls=!1,t.outputDeviceId&&n.setSinkId)try{await n.setSinkId(t.outputDeviceId)}catch(t){console.warn("Failed to set output device for new audio element:",t)}n.style.display="none",document.body.appendChild(n),t.audioElements.push(n),1===t.audioElements.length&&(null==t.onDebug||t.onDebug({type:"audio_element_ready"})),await t.setupAudioCapture(i)}})),this.room.on(Rs.ActiveSpeakersChanged,(async function(e){t.updateMode(e.length>0&&e[0].identity.startsWith("agent")?"speaking":"listening")})),this.room.on(Rs.ParticipantDisconnected,(t=>{var e;null!=(e=t.identity)&&e.startsWith("agent")&&this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:"agent disconnected"})})}))}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach((t=>{t.track&&t.track.stop()}))}catch(t){console.warn("Error stopping local tracks:",t)}this.audioCaptureContext&&(this.audioCaptureContext.close().catch((t=>{console.warn("Error closing audio capture context:",t)})),this.audioCaptureContext=null),this.audioElements.forEach((t=>{t.parentNode&&t.parentNode.removeChild(t)})),this.audioElements=[],this.room.disconnect()}}async sendMessage(t){if(this.isConnected&&this.room.localParticipant){if(!("user_audio_chunk"in t))try{const e=(new TextEncoder).encode(JSON.stringify(t));await this.room.localParticipant.publishData(e,{reliable:!0})}catch(e){this.debug({type:"send_message_error",message:{message:t,error:e}}),console.error("Failed to send message via WebRTC:",e)}}else console.warn("Cannot send message: room not connected or no local participant")}getRoom(){return this.room}async setMicMuted(t){if(!this.isConnected||!this.room.localParticipant)return void console.warn("Cannot set microphone muted: room not connected or no local participant");const e=this.room.localParticipant.getTrackPublication(mr.Source.Microphone);if(null!=e&&e.track)try{t?await e.track.mute():await e.track.unmute()}catch(e){await this.room.localParticipant.setMicrophoneEnabled(!t)}else await this.room.localParticipant.setMicrophoneEnabled(!t)}async setupAudioCapture(t){try{const e=new AudioContext;this.audioCaptureContext=e,this.outputAnalyser=e.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;const i=new MediaStream([t.mediaStreamTrack]),n=e.createMediaStreamSource(i);n.connect(this.outputAnalyser),await xc(e.audioWorklet);const s=new AudioWorkletNode(e,"rawAudioProcessor");this.outputAnalyser.connect(s),s.port.postMessage({type:"setFormat",format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),s.port.onmessage=t=>{const[e,i]=t.data;if(i>.01){const t=Tc(e.buffer),i=this.audioEventId++;this.handleMessage({type:"audio",audio_event:{audio_base_64:t,event_id:i}})}},n.connect(s)}catch(t){console.warn("Failed to set up audio capture:",t)}}setAudioVolume(t){this.audioElements.forEach((e=>{e.volume=t}))}async setAudioOutputDevice(t){if(!("setSinkId"in HTMLAudioElement.prototype))throw Error("setSinkId is not supported in this browser");const e=this.audioElements.map((async function(e){try{await e.setSinkId(t)}catch(t){throw console.error("Failed to set sink ID for audio element:",t),t}}));await Promise.all(e),this.outputDeviceId=t}async setAudioInputDevice(t){if(!this.isConnected||!this.room.localParticipant)throw Error("Cannot change input device: room not connected or no local participant");try{const e=this.room.localParticipant.getTrackPublication(mr.Source.Microphone);null!=e&&e.track&&(await e.track.stop(),await this.room.localParticipant.unpublishTrack(e.track));const i={deviceId:{exact:t},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},n=await function(t){return hn(this,void 0,void 0,(function*(){return(yield ic({audio:null==t||t,video:!1}))[0]}))}(i);await this.room.localParticipant.publishTrack(n,{name:"microphone",source:mr.Source.Microphone})}catch(t){console.error("Failed to change input device:",t);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(t){console.error("Failed to recover microphone after device switch error:",t)}throw t}}getOutputByteFrequencyData(){return this.outputAnalyser?(null!=this.outputFrequencyData||(this.outputFrequencyData=new Uint8Array(this.outputAnalyser.frequencyBinCount)),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}}async function Cc(t){const e=function(t){return t.connectionType?t.connectionType:"conversationToken"in t&&t.conversationToken?"webrtc":"websocket"}(t);switch(e){case"websocket":return kc.create(t);case"webrtc":return Ac.create(t);default:throw Error("Unknown connection type: "+e)}}function _c(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}async function Ic(t={default:0,android:3e3}){let e=t.default;var i;if(/android/i.test(navigator.userAgent))e=null!=(i=t.android)?i:e;else if(_c()){var n;e=null!=(n=t.ios)?n:e}e>0&&await new Promise((t=>setTimeout(t,e)))}class Rc extends fc{static async startSession(t){const e=fc.getFullOptions(t);e.onStatusChange&&e.onStatusChange({status:"connecting"}),e.onCanSendFeedbackChange&&e.onCanSendFeedbackChange({canSendFeedback:!1}),e.onModeChange&&e.onModeChange({mode:"listening"}),e.onCanSendFeedbackChange&&e.onCanSendFeedbackChange({canSendFeedback:!1});let i=null;try{return await Ic(e.connectionDelay),i=await Cc(t),new Rc(e,i)}catch(t){var n;throw e.onStatusChange&&e.onStatusChange({status:"disconnected"}),null==(n=i)||n.close(),t}}}const jc={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}};class Pc{static async create({sampleRate:t,format:e,preferHeadphonesForIosDevices:i,inputDeviceId:n,workletPaths:s,libsampleratePath:r}){let o=null,a=null;try{const c=lc({sampleRate:{ideal:t}},jc);if(_c()&&i){const t=(await window.navigator.mediaDevices.enumerateDevices()).find((t=>"audioinput"===t.kind&&["airpod","headphone","earphone"].find((e=>t.label.toLowerCase().includes(e)))));t&&(c.deviceId={ideal:t.deviceId})}n&&(c.deviceId=Pc.getDeviceIdConstraint(n));const d=navigator.mediaDevices.getSupportedConstraints().sampleRate;o=new window.AudioContext(d?{sampleRate:t}:{});const h=o.createAnalyser();if(!d){const t=r||"https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js";await o.audioWorklet.addModule(t)}await xc(o.audioWorklet,null==s?void 0:s.rawAudioProcessor);const l=lc({voiceIsolation:!0},c);a=await navigator.mediaDevices.getUserMedia({audio:l});const u=o.createMediaStreamSource(a),f=new AudioWorkletNode(o,"rawAudioProcessor");return f.port.postMessage({type:"setFormat",format:e,sampleRate:t}),u.connect(h),h.connect(f),await o.resume(),new Pc(o,h,f,a,u)}catch(t){var c,d;throw null==(c=a)||c.getTracks().forEach((t=>{t.stop()})),null==(d=o)||d.close(),t}}static getDeviceIdConstraint(t){if(t)return _c()?{ideal:t}:{exact:t}}constructor(t,e,i,n,s){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=t,this.analyser=e,this.worklet=i,this.inputStream=n,this.mediaStreamSource=s}async close(){this.inputStream.getTracks().forEach((t=>{t.stop()})),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(t){this.worklet.port.postMessage({type:"setMuted",isMuted:t})}async setInputDevice(t){try{const e=lc({},jc);t&&(e.deviceId=Pc.getDeviceIdConstraint(t));const i=lc({voiceIsolation:!0},e),n=await navigator.mediaDevices.getUserMedia({audio:i});this.inputStream.getTracks().forEach((t=>{t.stop()})),this.mediaStreamSource.disconnect(),this.inputStream=n,this.mediaStreamSource=this.context.createMediaStreamSource(n),this.mediaStreamSource.connect(this.analyser)}catch(t){throw console.error("Failed to switch input device:",t),t}}}const Dc=Oc("audioConcatProcessor",'/*\n * ulaw decoding logic taken from the wavefile library\n * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js\n * USED BY @elevenlabs/client\n */\n\nconst decodeTable = [0,132,396,924,1980,4092,8316,16764];\n\nfunction decodeSample(muLawSample) {\n let sign;\n let exponent;\n let mantissa;\n let sample;\n muLawSample = ~muLawSample;\n sign = (muLawSample & 0x80);\n exponent = (muLawSample >> 4) & 0x07;\n mantissa = muLawSample & 0x0F;\n sample = decodeTable[exponent] + (mantissa << (exponent+3));\n if (sign !== 0) sample = -sample;\n\n return sample;\n}\n\nclass AudioConcatProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffers = []; // Initialize an empty buffer\n this.cursor = 0;\n this.currentBuffer = null;\n this.wasInterrupted = false;\n this.finished = false;\n \n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.format = data.format;\n break;\n case "buffer":\n this.wasInterrupted = false;\n this.buffers.push(\n this.format === "ulaw"\n ? new Uint8Array(data.buffer)\n : new Int16Array(data.buffer)\n );\n break;\n case "interrupt":\n this.wasInterrupted = true;\n break;\n case "clearInterrupted":\n if (this.wasInterrupted) {\n this.wasInterrupted = false;\n this.buffers = [];\n this.currentBuffer = null;\n }\n }\n };\n }\n process(_, outputs) {\n let finished = false;\n const output = outputs[0][0];\n for (let i = 0; i < output.length; i++) {\n if (!this.currentBuffer) {\n if (this.buffers.length === 0) {\n finished = true;\n break;\n }\n this.currentBuffer = this.buffers.shift();\n this.cursor = 0;\n }\n\n let value = this.currentBuffer[this.cursor];\n if (this.format === "ulaw") {\n value = decodeSample(value);\n }\n output[i] = value / 32768;\n this.cursor++;\n\n if (this.cursor >= this.currentBuffer.length) {\n this.currentBuffer = null;\n }\n }\n\n if (this.finished !== finished) {\n this.finished = finished;\n this.port.postMessage({ type: "process", finished });\n }\n\n return true; // Continue processing\n }\n}\n\nregisterProcessor("audioConcatProcessor", AudioConcatProcessor);\n');class Mc{static async create({sampleRate:t,format:e,outputDeviceId:i,workletPaths:n}){let s=null,r=null;try{s=new AudioContext({sampleRate:t});const o=s.createAnalyser(),a=s.createGain();r=new Audio,r.src="",r.load(),r.autoplay=!0,r.style.display="none",document.body.appendChild(r);const c=s.createMediaStreamDestination();r.srcObject=c.stream,a.connect(o),o.connect(c),await Dc(s.audioWorklet,null==n?void 0:n.audioConcatProcessor);const d=new AudioWorkletNode(s,"audioConcatProcessor");return d.port.postMessage({type:"setFormat",format:e}),d.connect(a),await s.resume(),i&&r.setSinkId&&await r.setSinkId(i),new Mc(s,o,a,d,r)}catch(t){var o,a;throw null!=(o=r)&&o.parentNode&&r.parentNode.removeChild(r),null==(a=r)||a.pause(),s&&"closed"!==s.state&&await s.close(),t}}constructor(t,e,i,n,s){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=t,this.analyser=e,this.gain=i,this.worklet=n,this.audioElement=s}async setOutputDevice(t){if(!("setSinkId"in HTMLAudioElement.prototype))throw Error("setSinkId is not supported in this browser");await this.audioElement.setSinkId(t||"")}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}}class Nc extends fc{static async requestWakeLock(){if("wakeLock"in navigator)try{return await navigator.wakeLock.request("screen")}catch(t){}return null}static async startSession(t){var e;const i=fc.getFullOptions(t);i.onStatusChange&&i.onStatusChange({status:"connecting"}),i.onCanSendFeedbackChange&&i.onCanSendFeedbackChange({canSendFeedback:!1});let n=null,s=null,r=null,o=null,a=null;(null==(e=t.useWakeLock)||e)&&(a=await Nc.requestWakeLock());try{var c;return o=await navigator.mediaDevices.getUserMedia({audio:!0}),await Ic(i.connectionDelay),s=await Cc(t),[n,r]=await Promise.all([Pc.create(lc({},s.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),Mc.create(lc({},s.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),null==(c=o)||c.getTracks().forEach((t=>{t.stop()})),o=null,new Nc(i,s,n,r,a)}catch(t){var d,h,l,u;i.onStatusChange&&i.onStatusChange({status:"disconnected"}),null==(d=o)||d.getTracks().forEach((t=>{t.stop()})),null==(h=s)||h.close(),await(null==(l=n)?void 0:l.close()),await(null==(u=r)?void 0:u.close());try{var f;await(null==(f=a)?void 0:f.release()),a=null}catch(t){}throw t}}constructor(t,e,i,n,s){super(t,e),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.visibilityChangeHandler=null,this.onInputWorkletMessage=t=>{"connected"===this.status&&this.connection.sendMessage({user_audio_chunk:Tc(t.data[0].buffer)})},this.onOutputWorkletMessage=({data:t})=>{"process"===t.type&&this.updateMode(t.finished?"listening":"speaking")},this.addAudioBase64Chunk=t=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"}),this.output.worklet.port.postMessage({type:"buffer",buffer:Sc(t)})},this.fadeOutAudio=()=>{this.updateMode("listening"),this.output.worklet.port.postMessage({type:"interrupt"}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout((()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"})}),2e3)},this.calculateVolume=t=>{if(0===t.length)return 0;let e=0;for(let i=0;i<t.length;i++)e+=t[i]/255;return e/=t.length,e<0?0:e>1?1:e},this.setVolume=({volume:t})=>{const e=Number.isFinite(t)?Math.min(1,Math.max(0,t)):1;this.volume=e,this.connection instanceof Ac?this.connection.setAudioVolume(e):this.output.gain.gain.value=e},this.input=i,this.output=n,this.wakeLock=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage,s&&(this.visibilityChangeHandler=()=>{var t;"visible"===document.visibilityState&&null!=(t=this.wakeLock)&&t.released&&Nc.requestWakeLock().then((t=>{this.wakeLock=t}))},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}async handleEndSession(){await super.handleEndSession(),this.visibilityChangeHandler&&document.removeEventListener("visibilitychange",this.visibilityChangeHandler);try{var t;await(null==(t=this.wakeLock)?void 0:t.release()),this.wakeLock=null}catch(t){}await this.input.close(),await this.output.close()}handleInterruption(t){super.handleInterruption(t),this.fadeOutAudio()}handleAudio(t){var e,i;super.handleAudio(t),t.audio_event.alignment&&this.options.onAudioAlignment&&this.options.onAudioAlignment(t.audio_event.alignment),this.lastInterruptTimestamp<=t.audio_event.event_id&&(t.audio_event.audio_base_64&&(null==(e=(i=this.options).onAudio)||e.call(i,t.audio_event.audio_base_64),this.connection instanceof Ac||this.addAudioBase64Chunk(t.audio_event.audio_base_64)),this.currentEventId=t.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}setMicMuted(t){this.connection instanceof Ac?this.connection.setMicMuted(t):this.input.setMuted(t)}getInputByteFrequencyData(){return null!=this.inputFrequencyData||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof Ac?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(null!=this.outputFrequencyData||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:t,format:e,preferHeadphonesForIosDevices:i,inputDeviceId:n}){try{if(this.connection instanceof kc)try{return await this.input.setInputDevice(n),this.input}catch(t){console.warn("Failed to change device on existing input, recreating:",t)}this.connection instanceof Ac&&await this.connection.setAudioInputDevice(n||""),await this.input.close();const s=await Pc.create({sampleRate:null!=t?t:this.connection.inputFormat.sampleRate,format:null!=e?e:this.connection.inputFormat.format,preferHeadphonesForIosDevices:i,inputDeviceId:n,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath});return this.input=s,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(t){throw console.error("Error changing input device",t),t}}async changeOutputDevice({sampleRate:t,format:e,outputDeviceId:i}){try{if(this.connection instanceof kc)try{return await this.output.setOutputDevice(i),this.output}catch(t){console.warn("Failed to change device on existing output, recreating:",t)}this.connection instanceof Ac&&await this.connection.setAudioOutputDevice(i||""),await this.output.close();const n=await Mc.create({sampleRate:null!=t?t:this.connection.outputFormat.sampleRate,format:null!=e?e:this.connection.outputFormat.format,outputDeviceId:i,workletPaths:this.options.workletPaths});return this.output=n,this.output}catch(t){throw console.error("Error changing output device",t),t}}}var Uc,Lc,Bc;!function(t){t.SESSION_STARTED="session_started",t.PARTIAL_TRANSCRIPT="partial_transcript",t.COMMITTED_TRANSCRIPT="committed_transcript",t.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",t.AUTH_ERROR="auth_error",t.ERROR="error",t.OPEN="open",t.CLOSE="close",t.QUOTA_EXCEEDED="quota_exceeded",t.COMMIT_THROTTLED="commit_throttled",t.TRANSCRIBER_ERROR="transcriber_error",t.UNACCEPTED_TERMS="unaccepted_terms",t.RATE_LIMITED="rate_limited",t.INPUT_ERROR="input_error",t.QUEUE_OVERFLOW="queue_overflow",t.RESOURCE_EXHAUSTED="resource_exhausted",t.SESSION_TIME_LIMIT_EXCEEDED="session_time_limit_exceeded",t.CHUNK_SIZE_EXCEEDED="chunk_size_exceeded",t.INSUFFICIENT_AUDIO_ACTIVITY="insufficient_audio_activity"}(Uc||(Uc={})),function(t){t.PCM_8000="pcm_8000",t.PCM_16000="pcm_16000",t.PCM_22050="pcm_22050",t.PCM_24000="pcm_24000",t.PCM_44100="pcm_44100",t.PCM_48000="pcm_48000",t.ULAW_8000="ulaw_8000"}(Lc||(Lc={})),function(t){t.MANUAL="manual",t.VAD="vad"}(Bc||(Bc={}));const Fc=i(class extends n{constructor(t){super(),!1!==t&&this.__registerHost(),this.__attachShadow(),this.conversationStarted=o(this,"conversationStarted"),this.conversationEnded=o(this,"conversationEnded"),this.widgetError=o(this,"widgetError"),this.statusChanged=o(this,"statusChanged"),this.messageReceived=o(this,"messageReceived"),this.positionX="right",this.positionY="bottom",this.variant="floating",this.mode="dark",this.primaryColor="#6366f1",this.brandName="Customer Support",this.language="en",this.autoExpand=!1,this.showBranding=!0,this.fabPrompt="Do you need help?",this.fabButtonText="Start",this.status="disconnected",this.isExpanded=!1,this.termsAccepted=!1,this.errorMessage=null,this.inputVolume=0,this.outputVolume=0,this.messages=[],this.inputText="",this.copiedIndex=null,this.selectedMode="text",this.conversation=null,this.volumeInterval=null,this.messagesContainer=null,this.mediaStream=null,this.isTextOnlyMode=!0,this.pendingMessage=null,this.handleInputKeyDown=t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.handleSendText())},this.handleInputChange=t=>{this.inputText=t.target.value},this.handleToggleExpand=()=>{this.isExpanded=!this.isExpanded},this.copyToClipboard=(t,e)=>{navigator.clipboard.writeText(t),this.copiedIndex=e,setTimeout((()=>{this.copiedIndex=null}),2e3)},this.handleAcceptTerms=()=>{this.termsAccepted=!0},this.handleDeclineTerms=()=>{this.isExpanded=!1}}componentWillLoad(){this.autoExpand&&(this.isExpanded=!0)}disconnectedCallback(){this.cleanup()}async startConversation(t=!0){await this.handleStartConversation(t)}async endConversation(){await this.handleEndConversation()}async getStatus(){return this.status}async sendMessage(t){await this.handleSendText(t)}scrollToBottom(){if(this.messagesContainer){const t=this.messagesContainer;setTimeout((()=>{t.scrollTop=t.scrollHeight}),50)}}async getMicStream(){if(this.mediaStream)return this.mediaStream;try{const t=await navigator.mediaDevices.getUserMedia({audio:!0});return this.mediaStream=t,this.errorMessage=null,t}catch(t){throw t instanceof DOMException&&"NotAllowedError"===t.name&&(this.errorMessage=this.t("microphoneError")),t}}async handleStartConversation(t=!0,e=!1){if("connecting"!==this.status&&"connected"!==this.status)try{this.errorMessage=null,this.status="connecting",this.isTextOnlyMode=t,this.statusChanged.emit(this.status),e||(this.messages=[]),t||await this.getMicStream();const i=this.pendingMessage;let n,s;const r=new Promise(((t,e)=>{n=t,s=e})),o=setTimeout((()=>{s(Error("Connection timeout"))}),15e3),a=t?Rc:Nc;this.conversation=await a.startSession({agentId:this.agentId,connectionType:t?"websocket":"webrtc",overrides:{conversation:{textOnly:t,client_events:t?["agent_response","agent_chat_response_part","user_transcript"]:void 0}},onStatusChange:e=>{const i=e.status,r=this.status;this.status=i,this.statusChanged.emit(i),"connected"===i&&"connected"!==r&&(clearTimeout(o),this.conversationStarted.emit(),t||this.startVolumeMonitoring(),n()),"disconnected"===i&&("connected"===r?(this.conversationEnded.emit(),this.stopVolumeMonitoring()):"connecting"===r&&(clearTimeout(o),s(Error("Connection failed"))))},onMessage:t=>{if(t.message){const e={role:"user"===(t.role||t.source)?"user":"assistant",content:t.message};this.messages=[...this.messages,e],this.messageReceived.emit(e),this.scrollToBottom()}},onError:t=>{this.errorMessage=this.t("connectionError"),this.status="disconnected",this.statusChanged.emit(this.status),this.widgetError.emit({message:t+""})}}),await r,i&&this.conversation&&(this.conversation.sendUserMessage(i),this.pendingMessage=null)}catch(t){this.status="disconnected",this.statusChanged.emit(this.status),this.pendingMessage=null,this.errorMessage=t instanceof DOMException&&"NotAllowedError"===t.name?this.t("microphoneError"):this.t("connectionError"),this.widgetError.emit({message:this.errorMessage})}}async handleEndConversation(){this.conversation&&(this.status="disconnecting",this.statusChanged.emit(this.status),await this.conversation.endSession(),this.conversation=null,this.status="disconnected",this.statusChanged.emit(this.status),this.mediaStream&&(this.mediaStream.getTracks().forEach((t=>t.stop())),this.mediaStream=null))}async handleSendText(t){const e=t||this.inputText.trim();if(e)if("disconnected"===this.status){const t={role:"user",content:e};this.inputText="",this.pendingMessage=e,this.messages=[t],this.scrollToBottom();const i="text"===this.selectedMode;try{await this.handleStartConversation(i,!0)}catch{this.pendingMessage=null}}else"connected"===this.status&&(this.messages=[...this.messages,{role:"user",content:e}],this.inputText="",this.conversation&&"function"==typeof this.conversation.sendUserMessage?this.conversation.sendUserMessage(e):console.error("[Staylift] Cannot send message: no active conversation"),this.scrollToBottom())}async handleVoiceButton(){"disconnected"===this.status||null===this.status?await this.handleStartConversation(!1):"connected"===this.status&&await this.handleEndConversation()}async handleTextButton(){"disconnected"===this.status||null===this.status?await this.handleStartConversation(!0):"connected"===this.status&&await this.handleEndConversation()}startVolumeMonitoring(){this.volumeInterval=setInterval((()=>{if(this.conversation&&"connected"===this.status){const t=this.conversation.getInputVolume?.()??0,e=this.conversation.getOutputVolume?.()??0;this.inputVolume=Math.min(1,2.5*Math.pow(t,.5)),this.outputVolume=Math.min(1,2.5*Math.pow(e,.5))}}),50)}stopVolumeMonitoring(){this.volumeInterval&&(clearInterval(this.volumeInterval),this.volumeInterval=null),this.inputVolume=0,this.outputVolume=0}cleanup(){this.stopVolumeMonitoring(),this.conversation&&(this.conversation.endSession(),this.conversation=null),this.mediaStream&&(this.mediaStream.getTracks().forEach((t=>t.stop())),this.mediaStream=null)}t(t){const e={en:{microphoneError:"Please enable microphone permissions in your browser.",connectionError:"Connection failed. Please try again.",tapToStart:"Tap to start voice chat",connected:"Connected",placeholder:"Type a message...",emptyTitle:"Start a conversation",emptyDesc:"Type a message or tap the voice button",starting:"Starting conversation",connecting:"Connecting...",ready:"Ready to chat",talkOrType:"Start talking or type",poweredBy:"Powered by Staylift",termsTitle:"Terms and Conditions",termsText:'By clicking "Agree," and each time I interact with this AI agent, I consent to the recording, storage, and sharing of my communications with third-party service providers, and as described in the Privacy Policy.',termsWarning:"If you do not wish to have your conversations recorded, please refrain from using this service.",termsAgree:"Agree",termsDecline:"Decline",modeText:"Text",modeVoice:"Voice",startVoice:"Start Voice Call",endVoice:"End Call",startText:"Start Text Chat",endText:"End Chat"},pl:{microphoneError:"Proszę włączyć uprawnienia mikrofonu.",connectionError:"Połączenie nieudane. Spróbuj ponownie.",tapToStart:"Dotknij, aby rozpocząć rozmowę",connected:"Połączono",placeholder:"Napisz wiadomość...",emptyTitle:"Rozpocznij rozmowę",emptyDesc:"Napisz wiadomość lub naciśnij przycisk głosowy",starting:"Rozpoczynanie rozmowy",connecting:"Łączenie...",ready:"Gotowe do czatu",talkOrType:"Mów lub pisz",poweredBy:"Powered by Staylift",termsTitle:"Regulamin",termsText:"Klikając „Akceptuję” i za każdym razem, gdy wchodzę w interakcję z tym agentem AI, wyrażam zgodę na nagrywanie, przechowywanie i udostępnianie mojej komunikacji zewnętrznym dostawcom usług, zgodnie z opisem w Polityce Prywatności.",termsWarning:"Jeśli nie życzysz sobie nagrywania swoich rozmów, prosimy o powstrzymanie się od korzystania z tej usługi.",termsAgree:"Akceptuję",termsDecline:"Odrzucam",modeText:"Tekst",modeVoice:"Głos",startVoice:"Rozpocznij rozmowę głosową",endVoice:"Zakończ",startText:"Rozpocznij czat",endText:"Zakończ czat"},de:{microphoneError:"Bitte aktivieren Sie die Mikrofonberechtigung in Ihrem Browser.",connectionError:"Verbindung fehlgeschlagen. Bitte versuchen Sie es erneut.",tapToStart:"Tippen, um den Voice-Chat zu starten",connected:"Verbunden",placeholder:"Nachricht eingeben...",emptyTitle:"Gespräch starten",emptyDesc:"Nachricht eingeben oder Voice-Button drücken",starting:"Gespräch wird gestartet",connecting:"Verbindung wird hergestellt...",ready:"Bereit zum Chatten",talkOrType:"Sprechen oder tippen",poweredBy:"Powered by Staylift",termsTitle:"Nutzungsbedingungen",termsText:'Durch Klicken auf „Zustimmen" und bei jeder Interaktion mit diesem KI-Agenten stimme ich der Aufzeichnung, Speicherung und Weitergabe meiner Kommunikation an Drittanbieter zu, wie in der Datenschutzrichtlinie beschrieben.',termsWarning:"Wenn Sie nicht möchten, dass Ihre Gespräche aufgezeichnet werden, verwenden Sie diesen Dienst bitte nicht.",termsAgree:"Zustimmen",termsDecline:"Ablehnen",modeText:"Text",modeVoice:"Stimme",startVoice:"Sprachanruf starten",endVoice:"Beenden",startText:"Text-Chat starten",endText:"Chat beenden"}};return e[this.language]?.[t]||e.en[t]||t}getPositionClasses(){return`sl-x-${this.positionX} sl-y-${this.positionY}`}getThemeColors(){return"light"===this.mode?{bg:"#ffffff",text:"#18181b",muted:"#71717a",border:"#e4e4e7",surface:"#f4f4f5"}:{bg:"#18181b",text:"#ffffff",muted:"#a1a1aa",border:"#27272a",surface:"#27272a"}}render(){const t="connecting"===this.status||"disconnecting"===this.status,e="connected"===this.status&&!this.isTextOnlyMode,i=this.getThemeColors(),n={"--sl-primary":this.primaryColor,"--sl-bg":i.bg,"--sl-text":i.text,"--sl-muted":i.muted,"--sl-border":i.border,"--sl-surface":i.surface};return"inline"===this.variant?c("div",{class:"sl-widget sl-inline",style:n},this.renderCard(t)):c("div",{class:"sl-widget sl-floating "+this.getPositionClasses(),style:n},this.isExpanded?c("div",{class:"sl-card"},this.renderCard(t)):c("div",{class:"sl-fab-pill"},c("div",{class:"sl-fab-avatar"},this.avatarUrl?c("img",{src:this.avatarUrl,alt:"",class:"sl-fab-avatar-img"}):c("staylift-orb",{size:48,primaryColor:this.primaryColor,inputVolume:this.inputVolume,outputVolume:this.outputVolume,isActive:e})),c("div",{class:"sl-fab-content"},c("span",{class:"sl-fab-prompt"},this.fabPrompt),c("button",{class:"sl-fab-btn",onClick:this.handleToggleExpand},c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"})),this.fabButtonText))))}renderCard(t){return this.termsAccepted?[this.renderHeader(t),this.renderContent(),this.renderFooter(t)]:this.renderTerms()}renderTerms(){return c("div",{class:"sl-terms"},c("div",{class:"sl-terms-content"},c("h3",{class:"sl-terms-title"},this.t("termsTitle")),c("p",{class:"sl-terms-text"},this.t("termsText")),c("p",{class:"sl-terms-warning"},this.t("termsWarning"))),c("div",{class:"sl-terms-actions"},c("button",{class:"sl-terms-btn sl-terms-btn--decline",onClick:this.handleDeclineTerms},this.t("termsDecline")),c("button",{class:"sl-terms-btn sl-terms-btn--agree",onClick:this.handleAcceptTerms},this.t("termsAgree"))))}renderHeader(t){return c("div",{class:"sl-header"},c("div",{class:"sl-header-left"},c("div",{class:"sl-orb-ring"},this.avatarUrl?c("img",{src:this.avatarUrl,alt:"",class:"sl-header-avatar-img"}):c("staylift-orb",{size:40,primaryColor:this.primaryColor,inputVolume:this.inputVolume,outputVolume:this.outputVolume,isActive:"connected"===this.status&&!this.isTextOnlyMode})),c("div",{class:"sl-header-text"},c("span",{class:"sl-title"},this.brandName),c("span",{class:"sl-subtitle"},this.errorMessage?c("span",{class:"sl-error"},this.errorMessage):"disconnected"===this.status?this.t("tapToStart"):"connected"===this.status?c("span",{class:"sl-connected"},this.t("connected")):t?c("span",{class:"sl-shimmer"},this.status):null))),c("div",{class:"sl-header-right"},c("div",{class:`sl-dot ${"connected"===this.status?"sl-dot--active":""} ${t?"sl-dot--pulse":""}`}),"floating"===this.variant&&c("button",{class:"sl-close",onClick:this.handleToggleExpand},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M18 6L6 18M6 6l12 12"})))))}renderContent(){const t="connecting"===this.status,e="connected"===this.status;return c("div",{class:"sl-content",ref:t=>this.messagesContainer=t??null},0===this.messages.length?c("div",{class:"sl-empty"},c("staylift-orb",{size:48,primaryColor:this.primaryColor,isActive:!1}),c("h3",{class:"sl-empty-title"},this.t(t?"starting":e?"talkOrType":"emptyTitle")),c("p",{class:"sl-empty-desc"},this.t(t?"connecting":e?"ready":"emptyDesc"))):this.messages.map(((t,e)=>c("div",{class:"sl-msg sl-msg--"+t.role,key:e},c("div",{class:"sl-msg-row"},c("div",{class:"sl-msg-bubble"},t.content)),"assistant"===t.role&&c("div",{class:"sl-msg-actions"},c("button",{class:"sl-action",onClick:()=>this.copyToClipboard(t.content,e)},this.copiedIndex===e?c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("polyline",{points:"20 6 9 17 4 12"})):c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"}))))))))}renderFooter(t){const e="disconnected"===this.status,i="connected"===this.status&&!this.isTextOnlyMode,n="connected"===this.status&&this.isTextOnlyMode;return c("div",{class:"sl-footer"},e&&c("div",{class:"sl-mode-toggle"},c("button",{class:"sl-mode-btn "+("text"===this.selectedMode?"sl-mode-btn--active":""),onClick:()=>this.selectedMode="text"},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})),this.t("modeText")),c("button",{class:"sl-mode-btn "+("voice"===this.selectedMode?"sl-mode-btn--active":""),onClick:()=>this.selectedMode="voice"},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),c("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),c("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),c("line",{x1:"8",y1:"23",x2:"16",y2:"23"})),this.t("modeVoice"))),n&&c("div",{class:"sl-input-row"},c("button",{class:"sl-btn sl-btn--end",onClick:()=>this.handleTextButton(),disabled:t,title:this.t("endText")},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c("line",{x1:"6",y1:"6",x2:"18",y2:"18"}))),c("input",{type:"text",class:"sl-input",placeholder:this.t("placeholder"),value:this.inputText,onInput:this.handleInputChange,onKeyDown:this.handleInputKeyDown,disabled:t}),c("button",{class:"sl-btn",onClick:()=>this.handleSendText(),disabled:!this.inputText.trim()||t},c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),c("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})))),"text"===this.selectedMode&&e&&c("div",{class:"sl-voice-controls"},c("button",{class:"sl-voice-btn",onClick:()=>this.handleTextButton(),disabled:t},c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})),this.t(t?"connecting":"startText"))),"voice"===this.selectedMode&&e&&c("div",{class:"sl-voice-controls"},c("button",{class:"sl-voice-btn",onClick:()=>this.handleVoiceButton(),disabled:t},c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),c("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),c("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),c("line",{x1:"8",y1:"23",x2:"16",y2:"23"})),this.t(t?"connecting":"startVoice"))),i&&c("div",{class:"sl-voice-controls"},c("button",{class:"sl-voice-btn sl-voice-btn--end",onClick:()=>this.handleVoiceButton(),disabled:t},c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},c("path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91"}),c("line",{x1:"22",y1:"2",x2:"2",y2:"22"})),this.t("endVoice"))),this.showBranding&&c("div",{class:"sl-branding"},c("a",{href:"https://stayliftnow.com",target:"_blank",rel:"noopener noreferrer"},c("img",{src:"data:image/png;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8IAEQgAIAAgAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAMCBAEFAAYHCAkKC//EAMMQAAEDAwIEAwQGBAcGBAgGcwECAAMRBBIhBTETIhAGQVEyFGFxIweBIJFCFaFSM7EkYjAWwXLRQ5I0ggjhU0AlYxc18JNzolBEsoPxJlQ2ZJR0wmDShKMYcOInRTdls1V1pJXDhfLTRnaA40dWZrQJChkaKCkqODk6SElKV1hZWmdoaWp3eHl6hoeIiYqQlpeYmZqgpaanqKmqsLW2t7i5usDExcbHyMnK0NTV1tfY2drg5OXm5+jp6vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAQIAAwQFBgcICQoL/8QAwxEAAgIBAwMDAgMFAgUCBASHAQACEQMQEiEEIDFBEwUwIjJRFEAGMyNhQhVxUjSBUCSRoUOxFgdiNVPw0SVgwUThcvEXgmM2cCZFVJInotIICQoYGRooKSo3ODk6RkdISUpVVldYWVpkZWZnaGlqc3R1dnd4eXqAg4SFhoeIiYqQk5SVlpeYmZqgo6SlpqeoqaqwsrO0tba3uLm6wMLDxMXGx8jJytDT1NXW19jZ2uDi4+Tl5ufo6ery8/T19vf4+fr/2wBDAAICAgICAgMCAgMFAwMDBQYFBQUFBggGBgYGBggKCAgICAgICgoKCgoKCgoMDAwMDAwODg4ODg8PDw8PDw8PDw//2wBDAQICAgQEBAcEBAcQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/2gAMAwEAAhEDEQAAAfiPo6T9gTw/lbxH1R8xAWn0XwXsuXwv2J+cvsHnGXj/AP/aAAgBAQABBQJ2O0btujuvDXiGygZS/B6bCDwr9Yvii93+QRKL5RL8C7HvO8yb3t22f0cO3xxpg2+r22+3Pbre83K/u0XUoD//2gAIAQMRAT8BwnczyRDk/enDhl9/j+j8l+8kutyx9kUA/wD/2gAIAQIRAT8B0OVnO3//2gAIAQEABj8CajttnLc48eWgqo1XV5t08MMftLWggDvtxssUw8hKlH+VTrr9rTFZoWnZ41URJQhMyx+avw8nw7SWKbmWDaf+BASqiVfyR8S7mwljSi1jhISnyTQdNPtfB8GLe1uVxRjXFLwurhcqR5E6dv/EADMQAQADAAICAgICAwEBAAACCwERACExQVFhcYGRobHB8NEQ4fEgMEBQYHCAkKCwwNDg/9oACAEBAAE/IZsYHlgL2hFFykgNxq/8i4rZQAQHMl53M1Hu+FPRCE0H7+OCoZU37nAvVx5U656pS9EIT8wQj3YdyrMaSOzIAl5fmjVxMtl8cUFL/9oADAMBAAIRAxEAABD2kov/xAAzEQEBAQADAAECBQUBAQABAQkBABEhMRBBUWEgcfCRgaGx0cHh8TBAUGBwgJCgsMDQ4P/aAAgBAxEBPxDT3M5sJdI+Ma/bs4t0zZy8v7fT4v/aAAgBAhEBPxBPA2RcX//aAAgBAQABPxCXMUdNxPzQSDHSzRnYYmQIwJUDyoU5qBhvVIgVuSPBo61iI8V5sIdq5DxIPbJQrnR+qCA5rryHQleAAiIk2UhJuwnSp6JKa/KjgYm/NRmPignYSnymSrtfVNewxg4eEjzFnxEX/9k=",alt:"Staylift",class:"sl-branding-logo"}),this.t("poweredBy"))))}get el(){return this}static get style(){return":host{--sl-primary:#6366f1;--sl-bg:#18181b;--sl-text:#ffffff;--sl-muted:#a1a1aa;--sl-border:#27272a;--sl-surface:#27272a;--sl-success:#22c55e;--sl-danger:#ef4444;font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;font-size:14px;line-height:1.5;color:var(--sl-text)}.sl-widget *{box-sizing:border-box}.sl-floating{position:fixed;z-index:999999}.sl-x-left{left:40px;right:auto}.sl-x-center{left:50%;right:auto;transform:translateX(-50%)}.sl-x-right{right:40px;left:auto}.sl-y-top{top:40px;bottom:auto}.sl-y-bottom{bottom:40px;top:auto}.sl-fab{width:64px;height:64px;border-radius:50%;border:1px solid var(--sl-border);background:var(--sl-bg);cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 8px 32px rgba(0, 0, 0, 0.4);transition:transform 0.2s, box-shadow 0.2s;padding:8px}.sl-fab:hover{transform:scale(1.05);box-shadow:0 12px 40px rgba(0, 0, 0, 0.5)}.sl-fab-pill{display:flex;align-items:center;gap:16px;padding:12px 16px 12px 12px;background:var(--sl-bg);border:1px solid var(--sl-border);border-radius:32px;box-shadow:0 8px 32px rgba(0, 0, 0, 0.4);animation:sl-fade-in 0.2s ease}.sl-fab-avatar{width:48px;height:48px;border-radius:50%;overflow:hidden;flex-shrink:0;border:1px solid var(--sl-border)}.sl-fab-avatar-img{width:100%;height:100%;object-fit:cover}.sl-fab-content{display:flex;flex-direction:column;gap:8px}.sl-fab-prompt{font-size:14px;font-weight:500;color:var(--sl-text);white-space:nowrap}.sl-fab-btn{display:flex;align-items:center;gap:6px;padding:8px 20px;border:none;border-radius:20px;background:var(--sl-primary);color:white;font-size:13px;font-weight:500;cursor:pointer;transition:all 0.2s}.sl-fab-btn:hover{filter:brightness(1.1);transform:translateY(-1px)}.sl-card{width:440px;height:440px;max-height:calc(100vh - 100px);background:var(--sl-bg);border-radius:16px;border:1px solid var(--sl-border);box-shadow:0 20px 60px rgba(0, 0, 0, 0.5);display:flex;flex-direction:column;overflow:hidden;animation:sl-fade-in 0.2s ease}.sl-inline{width:100%;max-width:540px;height:440px;background:var(--sl-bg);border-radius:16px;border:1px solid var(--sl-border);display:flex;flex-direction:column;overflow:hidden}@keyframes sl-fade-in{from{opacity:0;transform:translateY(10px) scale(0.98)}to{opacity:1;transform:translateY(0) scale(1)}}.sl-header{display:flex;align-items:center;justify-content:space-between;padding:16px;flex-shrink:0;border-bottom:1px solid var(--sl-border)}.sl-header-left{display:flex;align-items:center;gap:16px}.sl-orb-ring{width:40px;height:40px;border-radius:50%;border:1px solid var(--sl-border);overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center}.sl-header-avatar-img{width:100%;height:100%;object-fit:cover;object-position:center center;display:block}.sl-header-text{display:flex;flex-direction:column;gap:2px}.sl-title{font-size:14px;font-weight:500;color:var(--sl-text);line-height:1.2}.sl-subtitle{font-size:12px;color:var(--sl-muted);line-height:1.2}.sl-error{color:var(--sl-danger)}.sl-connected{color:var(--sl-success)}.sl-shimmer{background:linear-gradient(90deg, var(--sl-muted) 0%, var(--sl-text) 50%, var(--sl-muted) 100%);background-size:200% 100%;-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;animation:sl-shimmer 1.5s infinite;text-transform:capitalize}@keyframes sl-shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}.sl-header-right{display:flex;align-items:center;gap:12px}.sl-dot{width:8px;height:8px;border-radius:50%;background:var(--sl-muted);opacity:0.4;transition:all 0.3s}.sl-dot--active{background:var(--sl-success);opacity:1;box-shadow:0 0 8px rgba(34, 197, 94, 0.5)}.sl-dot--pulse{background:var(--sl-text);opacity:0.4;animation:sl-pulse 1s infinite}@keyframes sl-pulse{0%,100%{opacity:0.4}50%{opacity:0.8}}.sl-close{width:32px;height:32px;border-radius:50%;border:none;background:transparent;color:var(--sl-muted);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s}.sl-close:hover{background:var(--sl-surface);color:var(--sl-text)}.sl-content{flex:1;overflow-y:auto;padding:12px 24px 24px;display:flex;flex-direction:column;gap:8px}.sl-empty{display:flex;flex-direction:column;align-items:center;text-align:center;gap:12px}.sl-empty-title{margin:0;font-size:15px;font-weight:500;color:var(--sl-text)}.sl-empty-desc{margin:0;font-size:13px;color:var(--sl-muted)}.sl-mode-toggle{display:flex;gap:8px;margin-bottom:12px;padding:4px;background:var(--sl-surface);border-radius:10px}.sl-mode-btn{display:flex;align-items:center;gap:6px;padding:8px 16px;border:none;border-radius:8px;background:transparent;color:var(--sl-muted);font-size:13px;font-weight:500;cursor:pointer;transition:all 0.2s}.sl-mode-btn:hover{color:var(--sl-text)}.sl-mode-btn--active{background:var(--sl-bg);color:var(--sl-text);box-shadow:0 1px 3px rgba(0, 0, 0, 0.2)}.sl-voice-controls{display:flex;justify-content:center}.sl-voice-btn{display:flex;align-items:center;justify-content:center;gap:10px;width:100%;padding:14px 24px;border:none;border-radius:12px;background:var(--sl-primary);color:white;font-size:14px;font-weight:500;cursor:pointer;transition:all 0.2s}.sl-voice-btn:hover:not(:disabled){filter:brightness(1.1);transform:translateY(-1px)}.sl-voice-btn:disabled{opacity:0.6;cursor:not-allowed}.sl-voice-btn--end{background:var(--sl-danger)}.sl-voice-btn--end:hover:not(:disabled){filter:brightness(1.1)}.sl-msg{display:flex;flex-direction:column;gap:4px}.sl-msg-row{display:flex;align-items:flex-end;gap:8px}.sl-msg--user .sl-msg-row{justify-content:flex-end}.sl-msg--assistant .sl-msg-row{justify-content:flex-start}.sl-msg-bubble{max-width:85%;padding:10px 14px;border-radius:12px;font-size:14px;line-height:1.5;white-space:pre-wrap;word-wrap:break-word}.sl-msg--user .sl-msg-bubble{background:var(--sl-primary);color:white;border-bottom-right-radius:4px}.sl-msg--assistant .sl-msg-bubble{background:var(--sl-surface);color:var(--sl-text);border-bottom-left-radius:4px}.sl-msg-actions{display:flex;gap:4px;padding-left:32px}.sl-action{width:28px;height:28px;border-radius:6px;border:none;background:transparent;color:var(--sl-muted);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s}.sl-action:hover{background:var(--sl-surface);color:var(--sl-text)}.sl-footer{padding:16px;border-top:1px solid var(--sl-border);flex-shrink:0}.sl-branding{text-align:center;margin-top:8px;padding-top:8px}.sl-branding a{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--sl-muted);text-decoration:none;opacity:0.6;transition:opacity 0.2s}.sl-branding a:hover{opacity:1}.sl-branding-logo{width:16px;height:16px;border-radius:3px;object-fit:cover}.sl-input-row{display:flex;align-items:center;gap:8px}.sl-input{flex:1;height:36px;padding:0 12px;border:none;border-radius:8px;background:transparent;color:var(--sl-text);font-size:14px;outline:none}.sl-input::placeholder{color:var(--sl-muted)}.sl-input:disabled{opacity:0.5;cursor:not-allowed}.sl-btn{width:36px;height:36px;border-radius:50%;border:none;background:transparent;color:var(--sl-muted);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s;flex-shrink:0}.sl-btn:hover:not(:disabled){background:var(--sl-surface);color:var(--sl-text)}.sl-btn:disabled{opacity:0.3;cursor:not-allowed}.sl-btn--end{background:var(--sl-surface);color:var(--sl-text)}.sl-btn--end:hover:not(:disabled){background:var(--sl-danger);color:white}.sl-terms{display:flex;flex-direction:column;height:100%;padding:24px}.sl-terms-content{flex:1;display:flex;flex-direction:column;justify-content:center;gap:16px}.sl-terms-title{margin:0;font-size:18px;font-weight:600;color:var(--sl-text)}.sl-terms-text{margin:0;font-size:14px;line-height:1.6;color:var(--sl-text)}.sl-terms-warning{margin:0;font-size:13px;line-height:1.5;color:var(--sl-muted);font-style:italic}.sl-terms-actions{display:flex;gap:12px;padding-top:16px;border-top:1px solid var(--sl-border)}.sl-terms-btn{flex:1;padding:12px 20px;border:none;border-radius:8px;font-size:14px;font-weight:500;cursor:pointer;transition:all 0.2s}.sl-terms-btn--decline{background:var(--sl-surface);color:var(--sl-muted)}.sl-terms-btn--decline:hover{background:var(--sl-border);color:var(--sl-text)}.sl-terms-btn--agree{background:var(--sl-primary);color:white}.sl-terms-btn--agree:hover{filter:brightness(1.1)}@media (max-width: 480px){.sl-card{width:calc(100vw - 32px);max-width:400px}.sl-floating.sl-x-left,.sl-floating.sl-x-right{left:16px;right:16px}.sl-floating.sl-x-center{left:16px;right:16px;transform:none}.sl-floating.sl-y-bottom{bottom:16px}.sl-floating.sl-y-top{top:16px}}"}},[1,"staylift-widget",{agentId:[1,"agent-id"],positionX:[1,"position-x"],positionY:[1,"position-y"],variant:[1],mode:[1],primaryColor:[1,"primary-color"],brandName:[1,"brand-name"],language:[1],autoExpand:[4,"auto-expand"],showBranding:[4,"show-branding"],avatarUrl:[1,"avatar-url"],fabPrompt:[1,"fab-prompt"],fabButtonText:[1,"fab-button-text"],status:[32],isExpanded:[32],termsAccepted:[32],errorMessage:[32],inputVolume:[32],outputVolume:[32],messages:[32],inputText:[32],copiedIndex:[32],selectedMode:[32],startConversation:[64],endConversation:[64],getStatus:[64],sendMessage:[64]}]);function Vc(){"undefined"!=typeof customElements&&["staylift-widget","staylift-orb"].forEach((i=>{switch(i){case"staylift-widget":customElements.get(t(i))||customElements.define(t(i),Fc);break;case"staylift-orb":customElements.get(t(i))||e()}}))}Vc();export{Fc as StayliftWidget,Vc as d}