@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{r as t,c as e,h as i,g as n}from"./p-DAtfDq5B.js";function s(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 r=Object.defineProperty,o=(t,e,i)=>((t,e,i)=>e in t?r(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,i);let a=class{constructor(){o(this,"_locking"),o(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 c(t,e){if(!t)throw new Error(e)}function h(t){if("number"!=typeof t)throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>2147483647||t<-2147483648)throw new Error("invalid int 32: "+t)}function d(t){if("number"!=typeof t)throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>4294967295||t<0)throw new Error("invalid uint 32: "+t)}function l(t){if("number"!=typeof t)throw new Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>34028234663852886e22||t<-34028234663852886e22))throw new Error("invalid float 32: "+t)}const u=Symbol("@bufbuild/protobuf/enum-type");function f(t,e,i){t[u]=v(e,i.map((e=>({no:e.no,name:e.name,localName:t[e.no]}))))}function v(t,e){const i=Object.create(null),n=Object.create(null),s=[];for(const t of e){const e=m(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 m(t){return"localName"in t?t:Object.assign(Object.assign({},t),{localName:t.name})}class p{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 new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(t instanceof Error?t.message:String(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 g(){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 new Error("invalid varint")}function b(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 y=4294967296;function w(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>=y&&(s+=n/y|0,n%=y)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?S(n,s):T(n,s)}function k(t,e){if(({lo:t,hi:e}=function(t,e){return{lo:t>>>0,hi:e>>>0}}(t,e)),e<=2097151)return String(y*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.toString()+E(r)+E(s)}function T(t,e){return{lo:0|t,hi:0|e}}function S(t,e){return e=~e,t?t=1+~t:e+=1,T(t,e)}const E=t=>{const e=String(t);return"0000000".slice(e.length)+e};function O(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 A(){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 new Error("invalid varint");return this.assertBounds(),e>>>0}const x=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 new Error("int64 invalid: ".concat(t));return n},uParse(t){const e="bigint"==typeof t?t:BigInt(t);if(e>s||e<n)throw new 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=>c(/^-?[0-9]+$/.test(t),"int64 invalid: ".concat(t)),i=t=>c(/^[0-9]+$/.test(t),"uint64 invalid: ".concat(t));return{zero:"0",supported:!1,parse:t=>("string"!=typeof t&&(t=t.toString()),e(t),t),uParse:t=>("string"!=typeof t&&(t=t.toString()),i(t),t),enc:t=>("string"!=typeof t&&(t=t.toString()),e(t),w(t)),uEnc:t=>("string"!=typeof t&&(t=t.toString()),i(t),w(t)),dec:(t,e)=>function(t,e){let i=T(t,e);const n=2147483648&i.hi;n&&(i=S(i.lo,i.hi));const s=k(i.lo,i.hi);return n?"-"+s:s}(t,e),uDec:(t,e)=>k(t,e)}}();var C,_,R;function I(t,e,i){if(e===i)return!0;if(t==C.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 C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return e==i}return!1}function j(t,e){switch(t){case C.BOOL:return!1;case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return 0==e?x.zero:"0";case C.DOUBLE:case C.FLOAT:return 0;case C.BYTES:return new Uint8Array(0);case C.STRING:return"";default:return 0}}function P(t,e){switch(t){case C.BOOL:return!1===e;case C.STRING:return""===e;case C.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"}(C||(C={})),function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING"}(_||(_={})),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"}(R||(R={}));class D{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 new 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(d(t);t>127;)this.buf.push(127&t|128),t>>>=7;return this.buf.push(t),this}int32(t){return h(t),O(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){l(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){d(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){h(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return h(t),O(t=(t<<1^t>>31)>>>0,this.buf),this}sfixed64(t){let e=new Uint8Array(8),i=new DataView(e.buffer),n=x.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=x.uEnc(t);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(e)}int64(t){let e=x.enc(t);return b(e.lo,e.hi,this.buf),this}sint64(t){let e=x.enc(t),i=e.hi>>31;return b(e.lo<<1^i,(e.hi<<1|e.lo>>>31)^i,this.buf),this}uint64(t){let e=x.uEnc(t);return b(e.lo,e.hi,this.buf),this}}class M{constructor(t,e){this.varint64=g,this.uint32=A,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 new Error("illegal tag: field no "+e+" wire type "+i);return[e,i]}skip(t,e){let i=this.pos;switch(t){case R.Varint:for(;128&this.buf[this.pos++];);break;case R.Bit64:this.pos+=4;case R.Bit32:this.pos+=4;break;case R.LengthDelimited:let i=this.uint32();this.pos+=i;break;case R.StartGroup:for(;;){const[t,i]=this.tag();if(i===R.EndGroup){if(void 0!==e&&t!==e)throw new Error("invalid end group tag");break}this.skip(i,t)}break;default:throw new 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 x.dec(...this.varint64())}uint64(){return x.uDec(...this.varint64())}sint64(){let[t,e]=this.varint64(),i=-(1&t);return t=(t>>>1|(1&e)<<31)^i,e=e>>>1^i,x.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 x.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return x.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let 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 N(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 j(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 U="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),L=[];for(let t=0;t<U.length;t++)L[U[t].charCodeAt(0)]=t;L["-".charCodeAt(0)]=U.indexOf("+"),L["_".charCodeAt(0)]=U.indexOf("/");const B={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=L[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+=U[e>>2],s=(3&e)<<4,n=1;break;case 1:i+=U[s|e>>4],s=(15&e)<<2,n=2;break;case 2:i+=U[s|e>>6],i+=U[63&e],n=0}return n&&(i+=U[s],i+="=",1==n&&(i+="=")),i}};function F(t,e,i){z(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]=N(e);for(const t of s)e.runtime.bin.readField(r,n.readerFactory(t.data),e.field,t.wireType,n);return o()}function q(t,e,i,n){z(e,t);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(V(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 V(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 z(t,e){c(t.extendee.typeName==e.getType().typeName,"extension ".concat(t.typeName," can only be applied to message ").concat(t.extendee.typeName))}function J(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:!P(t.T,e[i]);case"message":return void 0!==e[i];case"map":return Object.keys(e[i]).length>0}}function W(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?j(t.T,t.L):void 0;break;case"message":e[i]=void 0}}function G(t,e){if(null===t||"object"!=typeof t)return!1;if(!Object.getOwnPropertyNames(p.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 Q(t,e){return G(e)||!t.fieldWrapper?e:t.fieldWrapper.wrapField(e)}const H={ignoreUnknownFields:!1},K={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};const Y=Symbol(),$=Symbol();function Z(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 String(t)}}function X(t,e,i,n,s){let r=i.localName;if(i.repeated){if(c("map"!=i.kind),null===e)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e)));const o=t[r];for(const t of e){if(null===t)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(t)));switch(i.kind){case"message":o.push(i.T.fromJson(t,n));break;case"enum":const e=it(i.T,t,n.ignoreUnknownFields,!0);e!==$&&o.push(e);break;case"scalar":try{o.push(et(i.T,t,i.L,!0))}catch(e){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}}}}else if("map"==i.kind){if(null===e)return;if("object"!=typeof e||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e)));const o=t[r];for(const[t,r]of Object.entries(e)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let a;try{a=tt(i.K,t)}catch(t){let n="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),new Error(n)}switch(i.V.kind){case"message":o[a]=i.V.T.fromJson(r,n);break;case"enum":const t=it(i.V.T,r,n.ignoreUnknownFields,!0);t!==$&&(o[a]=t);break;case"scalar":try{o[a]=et(i.V.T,r,_.BIGINT,!0)}catch(t){let n="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),new 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];G(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=it(i.T,e,n.ignoreUnknownFields,!1);switch(c){case Y:W(i,t);break;case $:break;default:t[r]=c}break;case"scalar":try{const n=et(i.T,e,i.L,!1);n===Y?W(i,t):t[r]=n}catch(t){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),new Error(n)}}}function tt(t,e){if(t===C.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1}return et(t,e,_.BIGINT,!0).toString()}function et(t,e,i,n){if(null===e)return n?j(t,i):Y;switch(t){case C.DOUBLE:case C.FLOAT:if("NaN"===e)return Number.NaN;if("Infinity"===e)return Number.POSITIVE_INFINITY;if("-Infinity"===e)return Number.NEGATIVE_INFINITY;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==C.FLOAT&&l(n),n;case C.INT32:case C.FIXED32:case C.SFIXED32:case C.SINT32:case C.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==C.UINT32||t==C.FIXED32?d(s):h(s),s;case C.INT64:case C.SFIXED64:case C.SINT64:if("number"!=typeof e&&"string"!=typeof e)break;const r=x.parse(e);return i?r.toString():r;case C.FIXED64:case C.UINT64:if("number"!=typeof e&&"string"!=typeof e)break;const o=x.uParse(e);return i?o.toString():o;case C.BOOL:if("boolean"!=typeof e)break;return e;case C.STRING:if("string"!=typeof e)break;return e;case C.BYTES:if(""===e)return new Uint8Array(0);if("string"!=typeof e)break;return B.dec(e)}throw new Error}function it(t,e,i,n){if(null===e)return"google.protobuf.NullValue"==t.typeName?0:n?t.values[0].no:Y;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 $}throw new Error("cannot decode enum ".concat(t.typeName," from JSON: ").concat(Z(e)))}function nt(t){return!(!t.repeated&&"map"!=t.kind&&(t.oneof||"message"==t.kind||t.opt||t.req))}function st(t,e,i){if("map"==t.kind){c("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.toString()]=ot(t.V.T,i);break;case"message":for(const[t,e]of s)n[t.toString()]=e.toJson(i);break;case"enum":const e=t.V.T;for(const[t,r]of s)n[t.toString()]=rt(e,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(t.repeated){c(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let i=0;i<e.length;i++)n.push(ot(t.T,e[i]));break;case"enum":for(let s=0;s<e.length;s++)n.push(rt(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 ot(t.T,e);case"enum":return rt(t.T,e,i.enumAsInteger);case"message":return Q(t.T,e).toJson(i)}}function rt(t,e,i){var n;if(c("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 ot(t,e){switch(t){case C.INT32:case C.SFIXED32:case C.SINT32:case C.FIXED32:case C.UINT32:return c("number"==typeof e),e;case C.FLOAT:case C.DOUBLE:return c("number"==typeof e),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case C.STRING:return c("string"==typeof e),e;case C.BOOL:return c("boolean"==typeof e),e;case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return c("bigint"==typeof e||"string"==typeof e||"number"==typeof e),e.toString();case C.BYTES:return c(e instanceof Uint8Array),B.enc(e)}}const at=Symbol("@bufbuild/protobuf/unknown-fields"),ct={readUnknownFields:!0,readerFactory:t=>new M(t)},ht={writeUnknownFields:!0,writerFactory:()=>new D};function dt(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?C.INT32:i.T;let c=ft;if("scalar"==i.kind&&i.L>0&&(c=ut),r){let i=t[o];if(n==R.LengthDelimited&&a!=C.STRING&&a!=C.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 h=i.T;r?t[o].push(lt(e,new h,s,i)):G(t[o])?lt(e,t[o],s,i):(t[o]=lt(e,new h,s,i),!h.fieldWrapper||i.oneof||i.repeated||(t[o]=h.fieldWrapper.unwrapField(t[o])));break;case"map":let[d,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=ft(e,t.K);break;case 2:switch(t.V.kind){case"scalar":o=ft(e,t.V.T);break;case"enum":o=e.int32();break;case"message":o=lt(e,new t.V.T,i,void 0)}}}if(void 0===r&&(r=j(t.K,_.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=r.toString()),void 0===o)switch(t.V.kind){case"scalar":o=j(t.V.T,_.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][d]=l}}function lt(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 ut(t,e){const i=ft(t,e);return"bigint"==typeof i?i.toString():i}function ft(t,e){switch(e){case C.STRING:return t.string();case C.BOOL:return t.bool();case C.DOUBLE:return t.double();case C.FLOAT:return t.float();case C.INT32:return t.int32();case C.INT64:return t.int64();case C.UINT64:return t.uint64();case C.FIXED64:return t.fixed64();case C.BYTES:return t.bytes();case C.FIXED32:return t.fixed32();case C.SFIXED32:return t.sfixed32();case C.SFIXED64:return t.sfixed64();case C.SINT64:return t.sint64();case C.UINT32:return t.uint32();case C.SINT32:return t.sint32()}}function vt(t,e,i,n){c(void 0!==e);const s=t.repeated;switch(t.kind){case"scalar":case"enum":let r="enum"==t.kind?C.INT32:t.T;if(s)if(c(Array.isArray(e)),t.packed)!function(t,e,i,n){if(!n.length)return;t.tag(i,R.LengthDelimited).fork();let[,s]=bt(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)gt(i,r,t.no,n);else gt(i,r,t.no,e);break;case"message":if(s){c(Array.isArray(e));for(const s of e)pt(i,n,t,s)}else pt(i,n,t,e);break;case"map":c("object"==typeof e&&null!=e);for(const[s,r]of Object.entries(e))mt(i,n,t,s,r)}}function mt(t,e,i,n,s){t.tag(i.no,R.LengthDelimited),t.fork();let r=n;switch(i.K){case C.INT32:case C.FIXED32:case C.UINT32:case C.SFIXED32:case C.SINT32:r=Number.parseInt(n);break;case C.BOOL:c("true"==n||"false"==n),r="true"==n}switch(gt(t,i.K,1,r),i.V.kind){case"scalar":gt(t,i.V.T,2,s);break;case"enum":gt(t,C.INT32,2,s);break;case"message":c(void 0!==s),t.tag(2,R.LengthDelimited).bytes(s.toBinary(e))}t.join()}function pt(t,e,i,n){const s=Q(i.T,n);i.delimited?t.tag(i.no,R.StartGroup).raw(s.toBinary(e)).tag(i.no,R.EndGroup):t.tag(i.no,R.LengthDelimited).bytes(s.toBinary(e))}function gt(t,e,i,n){c(void 0!==n);let[s,r]=bt(e);t.tag(i,s)[r](n)}function bt(t){let e=R.Varint;switch(t){case C.BYTES:case C.STRING:e=R.LengthDelimited;break;case C.DOUBLE:case C.FIXED64:case C.SFIXED64:e=R.Bit64;break;case C.FIXED32:case C.SFIXED32:case C.FLOAT:e=R.Bit32}return[e,C[t].toLowerCase()]}function yt(t){if(void 0===t)return t;if(G(t))return t.clone();if(t instanceof Uint8Array){const e=new Uint8Array(t.byteLength);return e.set(t),e}return t}function wt(t){return t instanceof Uint8Array?t:new Uint8Array(t)}class kt{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 Tt(t,e){const i=Et(t);return e?i:_t(Ct(i))}const St=Et;function Et(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 Ot=new Set(["constructor","toString","toJSON","valueOf"]),At=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),xt=t=>"".concat(t,"$"),Ct=t=>At.has(t)?xt(t):t,_t=t=>Ot.has(t)?xt(t):t;class Rt{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=Tt(t,!1)}addField(t){c(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 It=(jt=t=>new kt(t,(t=>function(t){var e,i,n,s,r,o;const a=[];let c;for(const h of"function"==typeof t?t():t){const t=h;if(t.localName=Tt(h.name,void 0!==h.oneof),t.jsonName=null!==(e=h.jsonName)&&void 0!==e?e:St(h.name),t.repeated=null!==(i=h.repeated)&&void 0!==i&&i,"scalar"==h.kind&&(t.L=null!==(n=h.L)&&void 0!==n?n:_.BIGINT),t.delimited=null!==(s=h.delimited)&&void 0!==s&&s,t.req=null!==(r=h.req)&&void 0!==r&&r,t.opt=null!==(o=h.opt)&&void 0!==o&&o,void 0===h.packed&&(t.packed="enum"==h.kind||"scalar"==h.kind&&h.T!=C.BYTES&&h.T!=C.STRING),void 0!==h.oneof){const e="string"==typeof h.oneof?h.oneof:h.oneof.name;c&&c.name==e||(c=new Rt(e)),t.oneof=c,c.addField(t)}a.push(t)}return a}(t))),Pt=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]=j(e.T,e.L)}}},{syntax:"proto3",json:{makeReadOptions:function(t){return t?Object.assign(Object.assign({},H),t):H},makeWriteOptions:function(t){return t?Object.assign(Object.assign({},K),t):K},readMessage(t,e,i,n){if(null==e||Array.isArray(e)||"object"!=typeof e)throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(Z(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 new 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)}X(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]=N(s);X(t,a,s.field,i,s),q(n,s,r(),i)}}if(!e&&!i.ignoreUnknownFields)throw new 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(!J(s,t)){if(s.req)throw"required field not set";if(!e.emitDefaultValues)continue;if(!nt(s))continue}const i=st(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&&V(t,o)){const i=F(t,o,e),s=st(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:String(t);throw new Error(e+(n.length>0?": ".concat(n):""))}return n},readScalar:(t,e,i)=>et(t,e,null!=i?i:_.BIGINT,!0),writeScalar(t,e,i){if(void 0!==e)return i||P(t,e)?ot(t,e):void 0},debug:Z},bin:{makeReadOptions:function(t){return t?Object.assign(Object.assign({},ct),t):ct},makeWriteOptions:function(t){return t?Object.assign(Object.assign({},ht),t):ht},listUnknownFields(t){var e;return null!==(e=t[at])&&void 0!==e?e:[]},discardUnknownFields(t){delete t[at]},writeUnknownFields(t,e){const i=t[at];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[at])||(s[at]=[]),s[at].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!=R.EndGroup);){const i=r.fields.find(a);if(i)dt(t,e,i,c,n);else{const i=e.skip(c,a);n.readUnknownFields&&this.onUnknownField(t,a,c,i)}}if(s&&(c!=R.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:dt,writeMessage(t,e,i){const n=t.getType();for(const s of n.fields.byNumber())if(J(s,t))vt(s,s.oneof?t[s.oneof.localName].value:t[s.localName],e,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(t,e),e},writeField(t,e,i,n){void 0!==e&&vt(t,e,i,n)}},util:Object.assign(Object.assign({},{setEnumType:f,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&&!G(o,e.T)?o=new e.T(o):e&&"scalar"===e.kind&&e.T===C.BYTES&&(o=wt(o)),s[i]={case:t,value:o};break;case"scalar":case"enum":let a=r[i];n.T===C.BYTES&&(a=n.repeated?a.map(wt):wt(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===C.BYTES)for(const[t,e]of Object.entries(r[i]))s[i][t]=wt(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=>G(t,c)?t:new c(t)));else{const t=r[i];s[i]=c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?wt(t):t:G(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)=>I(t.T,e,s[i])));case"enum":return n.every(((t,e)=>I(C.INT32,t,s[e])))}throw new Error("repeated cannot contain ".concat(t.kind))}switch(t.kind){case"message":let e=n,i=s;return t.T.fieldWrapper&&(void 0===e||G(e)||(e=t.T.fieldWrapper.wrapField(e)),void 0===i||G(i)||(i=t.T.fieldWrapper.wrapField(i))),t.T.equals(e,i);case"enum":return I(C.INT32,n,s);case"scalar":return I(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 I(C.INT32,n.value,s.value);case"scalar":return I(r.T,n.value,s.value)}throw new 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=>I(C.INT32,n[t],s[t])));case"scalar":const i=t.V.T;return o.every((t=>I(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(yt);else if("map"==i.kind){s=n[i.localName];for(const[t,i]of Object.entries(e))s[t]=yt(i)}else s="oneof"==i.kind?i.findField(e.case)?{case:e.case,value:yt(e.value)}:{case:void 0}:yt(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:jt,initFields:Pt}),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 p),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:function(t,e){const i={};for(const t of e){const e=m(t);i[e.localName]=e.no,i[e.no]=e.localName}return f(i,t,e),i},makeEnumType:v,getEnumType:function(t){const e=t[u];return c(e,"missing enum type on enum object"),e},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)}});var jt,Pt;class Dt extends p{constructor(t){super(),this.seconds=x.zero,this.nanos=0,It.util.initPartial(t,this)}fromJson(t,e){if("string"!=typeof t)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(It.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 new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=x.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(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 new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const t=(this.nanos+1e9).toString().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 Dt.fromDate(new Date)}static fromDate(t){const e=t.getTime();return new Dt({seconds:x.parse(Math.floor(e/1e3)),nanos:e%1e3*1e6})}static fromBinary(t,e){return(new Dt).fromBinary(t,e)}static fromJson(t,e){return(new Dt).fromJson(t,e)}static fromJsonString(t,e){return(new Dt).fromJsonString(t,e)}static equals(t,e){return It.util.equals(Dt,t,e)}}Dt.runtime=It,Dt.typeName="google.protobuf.Timestamp",Dt.fields=It.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const Mt=It.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Dt},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Nt,repeated:!0},{no:5,name:"events",kind:"message",T:Lt,repeated:!0}])),Nt=It.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:Ut,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Ut=It.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Dt},{no:3,name:"value",kind:"scalar",T:2}])),Lt=It.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:Dt},{no:7,name:"normalized_end_timestamp",kind:"message",T:Dt,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Bt=It.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ft=It.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),qt=It.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"}]),Vt=It.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),zt=It.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Jt=It.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Wt=It.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"}]),Gt=It.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"}]),Qt=It.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ht=It.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"}]),Kt=It.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:Yt,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:Re}])),Yt=It.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),$t=It.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:It.getEnumType(qt),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}])),Zt=It.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:It.getEnumType(Xt)},{no:4,name:"tracks",kind:"message",T:se,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:$t},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:It.getEnumType(te)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:It.getEnumType(Wt)},{no:18,name:"kind_details",kind:"enum",T:It.getEnumType(ee),repeated:!0}])),Xt=It.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),te=It.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"}]),ee=It.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),ie=It.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ne=It.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:re,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:It.getEnumType(oe)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),se=It.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:It.getEnumType(Ft)},{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:It.getEnumType(qt)},{no:10,name:"layers",kind:"message",T:re,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:ne,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:It.getEnumType(ie)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Re},{no:19,name:"audio_features",kind:"enum",T:It.getEnumType(Ht),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:It.getEnumType(Bt)}])),re=It.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:It.getEnumType(Vt)},{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}])),oe=It.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"}]),ae=It.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:It.getEnumType(ce)},{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:fe,oneof:"value"},{no:3,name:"speaker",kind:"message",T:le,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:ve,oneof:"value"},{no:7,name:"transcription",kind:"message",T:me,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Mt,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:ge,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:be,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:ye,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:we,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:De,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Me,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Ne,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:he,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),ce=It.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),he=It.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:It.getEnumType(ie)},{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}])),de=It.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:fe,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:ge,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:be,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:ye,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:we,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:De,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Me,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Ne,oneof:"value"}])),le=It.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:ue,repeated:!0}])),ue=It.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}])),fe=It.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}])),ve=It.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),me=It.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:pe,repeated:!0}])),pe=It.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}])),ge=It.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}])),be=It.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}])),ye=It.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),we=It.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:ke,oneof:"value"}])),ke=It.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}])),Te=It.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Se=It.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:It.getEnumType(Ee)},{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}])),Ee=It.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Oe=It.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:It.getEnumType(Ae)},{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}])),Ae=It.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"}]),xe=It.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Ce},{no:2,name:"screen",kind:"message",T:Ce},{no:3,name:"resume_connection",kind:"enum",T:It.getEnumType(Jt)},{no:4,name:"disabled_codecs",kind:"message",T:_e},{no:5,name:"force_relay",kind:"enum",T:It.getEnumType(Jt)}])),Ce=It.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:It.getEnumType(Jt)}])),_e=It.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:Yt,repeated:!0},{no:2,name:"publish",kind:"message",T:Yt,repeated:!0}])),Re=It.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Ie=It.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),je=It.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:It.getEnumType(Ie)},{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"}),Pe=It.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),De=It.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:It.getEnumType(ie)},{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:Pe,oneof:"content_header"}]),{localName:"DataStream_Header"}),Me=It.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"}),Ne=It.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"}),Ue=It.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Le=It.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Be=It.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Fe=It.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),qe=It.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:$e,oneof:"message"},{no:2,name:"answer",kind:"message",T:$e,oneof:"message"},{no:3,name:"trickle",kind:"message",T:We,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Je,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ge,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Xe,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ti,oneof:"message"},{no:8,name:"leave",kind:"message",T:ni,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ri,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:yi,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ti,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Oi,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:oi,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ai,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ei,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ii,oneof:"message"}])),Ve=It.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Qe,oneof:"message"},{no:2,name:"answer",kind:"message",T:$e,oneof:"message"},{no:3,name:"offer",kind:"message",T:$e,oneof:"message"},{no:4,name:"trickle",kind:"message",T:We,oneof:"message"},{no:5,name:"update",kind:"message",T:Ze,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Ke,oneof:"message"},{no:8,name:"leave",kind:"message",T:ni,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ge,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ci,oneof:"message"},{no:11,name:"room_update",kind:"message",T:hi,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:li,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:fi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:pi,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:wi,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Ye,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:He,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:xi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ri,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Ii,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Pi,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:ki,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Li,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:gi,oneof:"message"}])),ze=It.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:re,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:It.getEnumType(oe)}])),Je=It.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:It.getEnumType(Ft)},{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:It.getEnumType(qt)},{no:9,name:"layers",kind:"message",T:re,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ze,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:It.getEnumType(ie)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:It.getEnumType(Bt)},{no:17,name:"audio_features",kind:"enum",T:It.getEnumType(Ht),repeated:!0}])),We=It.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:It.getEnumType(Le)},{no:3,name:"final",kind:"scalar",T:8}])),Ge=It.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Qe=It.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:Kt},{no:2,name:"participant",kind:"message",T:Zt},{no:3,name:"other_participants",kind:"message",T:Zt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ai,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:xe},{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:Se},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Yt,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),He=It.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:ai,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:xe},{no:3,name:"server_info",kind:"message",T:Se},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),Ke=It.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:se}])),Ye=It.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),$e=It.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}}])),Ze=It.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:Zt,repeated:!0}])),Xe=It.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:Te,repeated:!0}])),ti=It.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:It.getEnumType(Vt)},{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}])),ei=It.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:It.getEnumType(Ht),repeated:!0}])),ii=It.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}])),ni=It.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:It.getEnumType(Wt)},{no:3,name:"action",kind:"enum",T:It.getEnumType(si)},{no:4,name:"regions",kind:"message",T:Ci}])),si=It.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),ri=It.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:re,repeated:!0}])),oi=It.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}])),ai=It.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}])),ci=It.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:ue,repeated:!0}])),hi=It.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:Kt}])),di=It.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:It.getEnumType(zt)},{no:3,name:"score",kind:"scalar",T:2}])),li=It.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:di,repeated:!0}])),ui=It.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:It.getEnumType(Be)}])),fi=It.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:ui,repeated:!0}])),vi=It.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:It.getEnumType(Vt)},{no:2,name:"enabled",kind:"scalar",T:8}])),mi=It.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:vi,repeated:!0}])),pi=It.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:vi,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:mi,repeated:!0}])),gi=It.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Ue,repeated:!0}])),bi=It.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}])),yi=It.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:bi,repeated:!0}])),wi=It.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}])),ki=It.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:Kt},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Zt},{no:4,name:"other_participants",kind:"message",T:Zt,repeated:!0}])),Ti=It.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:$e},{no:2,name:"subscription",kind:"message",T:Xe},{no:3,name:"publish_tracks",kind:"message",T:Ke,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ei,repeated:!0},{no:5,name:"offer",kind:"message",T:$e},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Si,repeated:!0}])),Si=It.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Ei=It.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:It.getEnumType(Le)}])),Oi=It.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:It.getEnumType(Fe),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"}])),Ai=It.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),xi=It.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Ci=It.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:_i,repeated:!0}])),_i=It.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}])),Ri=It.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:It.getEnumType(Qt)}])),Ii=It.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:It.getEnumType(ji)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:We,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Je,oneof:"request"},{no:6,name:"mute",kind:"message",T:Ge,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:oi,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:ei,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:ii,oneof:"request"}])),ji=It.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"}]),Pi=It.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Di=It.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}])),Mi=It.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:Oe},{no:2,name:"connection_settings",kind:"message",T:Di},{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:Je,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:$e},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:It.getEnumType(Gt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ti}])),Ni=It.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:It.getEnumType(Ui)},{no:2,name:"join_request",kind:"scalar",T:12}])),Ui=It.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Li=It.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]));function Bi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Fi,qi,Vi,zi,Ji,Wi={exports:{}},Gi=(Fi||(Fi=1,qi=Wi.exports,Vi=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.apply(i,[t,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var 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 h(t){return function(){typeof console!==e&&(c.call(this),this[t].apply(this,arguments))}}function d(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)||h.apply(this,arguments)}function l(t,i){var o,a,h,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||d,l.getLevel=function(){return null!=h?h:null!=a?a:o},l.setLevel=function(t,i){return h=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){}}}(h),c.call(l)},l.setDefaultLevel=function(t){a=v(t),f()||l.setLevel(t,!1)},l.resetLevel=function(){h=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&&(h=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},Wi.exports?Wi.exports=Vi():qi.log=Vi()),Wi.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"}(zi||(zi={})),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"}(Ji||(Ji={}));let Qi=Gi.getLogger("livekit");function Hi(t){const e=Gi.getLogger(t);return e.setDefaultLevel(Qi.getLevel()),e}Object.values(Ji).map((t=>Gi.getLogger(t))),Qi.setDefaultLevel(zi.info);const Ki=Gi.getLogger("lk-e2ee"),Yi=7e3,$i=[0,300,1200,2700,4800,Yi,Yi,Yi,Yi,Yi];function Zi(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){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}c((n=n.apply(t,e||[])).next())}))}function Xi(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 tn,en={exports:{}},nn=function(){if(tn)return en.exports;tn=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)}en.exports=s,en.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 h=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=t,h.type=e,h.count=c.length,console&&console.warn&&console.warn(h)}return t}function h(){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 d(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},s=h.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=new 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=new 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=new 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 h=c.length,d=f(c,h);for(n=0;n<h;++n)i(d[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,d(this,t,e)),this},s.prototype.prependOnceListener=function(t,e){return o(e),this.prependListener(t,d(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):[]},en.exports}();let sn=!0,rn=!0;function on(t,e,i){const n=t.match(e);return n&&n.length>=i&&parseFloat(n[i],10)}function an(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.apply(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.apply(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 cn(t){return"boolean"!=typeof t?new Error("Argument type: "+typeof t+". Please use a boolean."):(sn=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function hn(t){return"boolean"!=typeof t?new Error("Argument type: "+typeof t+". Please use a boolean."):(rn=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function dn(){if("object"==typeof window){if(sn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function ln(t,e){rn&&console.warn(t+" is deprecated, please use "+e+" instead.")}function un(t){return"[object Object]"===Object.prototype.toString.call(t)}function fn(t){return un(t)?Object.keys(t).reduce((function(e,i){const n=un(t[i]),s=n?fn(t[i]):t[i],r=n&&!Object.keys(s).length;return void 0===s||r?e:Object.assign(e,{[i]:s})}),{}):t}function vn(t,e,i){e&&!i.has(e.id)&&(i.set(e.id,e),Object.keys(e).forEach((n=>{n.endsWith("Id")?vn(t,t.get(e[n]),i):n.endsWith("Ids")&&e[n].forEach((e=>{vn(t,t.get(e),i)}))})))}function mn(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&&vn(t,i,s)}))})),s}const pn=dn;function gn(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),pn("chrome: "+JSON.stringify(t)),s(t)}))}t.video=n(t.video)}return pn("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 bn(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function yn(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 an(t,"track",(t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t)))}function wn(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.apply(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.apply(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.apply(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 kn(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.apply(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=>mn(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.apply(this,[]);return t.forEach((t=>t._pc=this)),t}),an(t,"track",(t=>(t.receiver._pc=t.srcElement,t))),t.RTCRtpReceiver.prototype.getStats=function(){const t=this;return this._pc.getStats().then((e=>mn(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 Tn(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 Sn(t,e){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Tn(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.apply(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(new 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.apply(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.apply(this,[e=>{const i=r(this,e);t[0].apply(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(new 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 En(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 On(t,e){an(t,"negotiationneeded",(t=>{const i=t.target;if(!(e.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return t}))}var An=Object.freeze({__proto__:null,fixNegotiationNeeded:On,shimAddTrackRemoveTrack:Sn,shimAddTrackRemoveTrackWithNative:Tn,shimGetSendersWithDtmf:wn,shimGetUserMedia:gn,shimMediaStream:bn,shimOnTrack:yn,shimPeerConnection:En,shimSenderReceiverGetStats:kn});function xn(t,e){const i=t&&t.navigator,n=t&&t.MediaStreamTrack;if(i.getUserMedia=function(t,e,n){ln("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.apply(this,[i])}}}}function Cn(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 _n(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.apply(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 Rn(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.apply(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 In(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.apply(this,[]);return t.forEach((t=>t._pc=this)),t}),an(t,"track",(t=>(t.receiver._pc=t.srcElement,t))),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function jn(t){t.RTCPeerConnection&&!("removeStream"in t.RTCPeerConnection.prototype)&&(t.RTCPeerConnection.prototype.removeStream=function(t){ln("removeStream","removeTrack"),this.getSenders().forEach((e=>{e.track&&t.getTracks().includes(e.track)&&this.removeTrack(e)}))})}function Pn(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function Dn(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 Mn(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 Nn(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 Un(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 Ln=Object.freeze({__proto__:null,shimAddTransceiver:Dn,shimCreateAnswer:Un,shimCreateOffer:Nn,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:Mn,shimGetUserMedia:xn,shimOnTrack:Cn,shimPeerConnection:_n,shimRTCDataChannel:Pn,shimReceiverGetStats:In,shimRemoveStream:jn,shimSenderGetStats:Rn});function Bn(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=new 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 Fn(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 qn(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.apply(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.apply(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.apply(this,[t]);return i?(n.then(e,i),Promise.resolve()):n};e.setLocalDescription=a,a=function(t,e,i){const n=r.apply(this,[t]);return i?(n.then(e,i),Promise.resolve()):n},e.setRemoteDescription=a,a=function(t,e,i){const n=o.apply(this,[t]);return i?(n.then(e,i),Promise.resolve()):n},e.addIceCandidate=a}function Vn(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(zn(t))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(t,i,n){e.mediaDevices.getUserMedia(t).then(i,n)}.bind(e))}function zn(t){return t&&void 0!==t.video?Object.assign({},t,{video:fn(t.video)}):t}function Jn(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?(ln("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 Wn(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 Gn(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 Qn(t){"object"!=typeof t||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var Hn,Kn=Object.freeze({__proto__:null,shimAudioContext:Qn,shimCallbacksAPI:qn,shimConstraints:zn,shimCreateOfferLegacy:Gn,shimGetUserMedia:Vn,shimLocalStreamsAPI:Bn,shimRTCIceServerUrls:Jn,shimRemoteStreamsAPI:Fn,shimTrackEventTransceiver:Wn}),Yn={exports:{}},$n=(Hn||(Hn=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 h=e.matchPrefix(t,"a=ssrc-group:FID").map((t=>t.substring(17).split(" ").map((t=>parseInt(t,10)))));h.length>0&&h[0].length>1&&h[0][0]===a&&(c=h[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 d=e.matchPrefix(t,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((t=>{t.maxBitrate=d}))),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().toString().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}(Yn)),Yn.exports),Zn=Bi($n),Xn=s({__proto__:null,default:Zn},[$n]);function ts(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=Zn.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,an(t,"icecandidate",(e=>(e.candidate&&Object.defineProperty(e,"candidate",{value:new t.RTCIceCandidate(e.candidate),writable:"false"}),e)))}function es(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||an(t,"icecandidate",(t=>{if(t.candidate){const e=Zn.parseCandidate(t.candidate.candidate);"relay"===e.type&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[e.priority>>24])}return t}))}function is(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=Zn.splitSections(t.sdp);return e.shift(),e.some((t=>{const e=Zn.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=Zn.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?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function ns(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},an(t,"datachannel",(t=>(e(t.channel,t.target),t)))}function ss(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 rs(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 os(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 as(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.apply(this,[t]):("offer"===t.type?this.createOffer:this.createAnswer).apply(this).then((t=>e.apply(this,[t])))})}var cs=Object.freeze({__proto__:null,removeExtmapAllowMixed:rs,shimAddIceCandidateNullOrEmpty:os,shimConnectionState:ss,shimMaxMessageSize:is,shimParameterlessSetLocalDescription:as,shimRTCIceCandidate:ts,shimRTCIceCandidateRelayProtocol:es,shimSendThrowTypeError:ns});!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=dn,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(on(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===t.isSecureContext&&t.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(on(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(on(i.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype,e._safariVersion=on(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return e}(t),s={browserDetails:n,commonShim:cs,extractVersion:on,disableLog:cn,disableWarnings:hn,sdp:Xn};switch(n.browser){case"chrome":if(!An||!En||!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=An,os(t,n),as(t),gn(t,n),bn(t),En(t,n),yn(t),Sn(t,n),wn(t),kn(t),On(t,n),ts(t),es(t),ss(t),is(t,n),ns(t),rs(t,n);break;case"firefox":if(!Ln||!_n||!e.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Ln,os(t,n),as(t),xn(t,n),_n(t,n),Cn(t),jn(t),Rn(t),In(t),Pn(t),Dn(t),Mn(t),Nn(t),Un(t),ts(t),ss(t),is(t,n),ns(t);break;case"safari":if(!Kn||!e.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=Kn,os(t,n),as(t),Jn(t),Gn(t),qn(t),Bn(t),Fn(t),Wn(t),Vn(t),Qn(t),ts(t),es(t),is(t,n),ns(t),rs(t,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class hs 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 ds=/version\/(\d+(\.?_?\d+)+)/i;let ls;function us(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===ls||e){const t=fs.find((t=>{let{test:e}=t;return e.test(i)}));ls=null==t?void 0:t.describe(i)}return ls}const fs=[{test:/firefox|iceweasel|fxios/i,describe:t=>({name:"Firefox",version:vs(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ms(t)})},{test:/chrom|crios|crmo/i,describe:t=>({name:"Chrome",version:vs(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ms(t)})},{test:/safari|applewebkit/i,describe:t=>({name:"Safari",version:vs(ds,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:ms(t)})}];function vs(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 ms(t){return t.includes("mac os")?vs(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}class ps extends Error{constructor(t,e){super(e||"an error has occured"),this.name="LiveKitError",this.code=t}}var gs,bs,ys,ws,ks,Ts,Ss;!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"}(gs||(gs={}));class Es extends ps{constructor(t,e,i,n){super(1,t),this.name="ConnectionError",this.status=i,this.reason=e,this.context=n,this.reasonName=gs[e]}static notAllowed(t,e,i){return new Es(t,gs.NotAllowed,e,i)}static timeout(t){return new Es(t,gs.Timeout)}static leaveRequest(t,e){return new Es(t,gs.LeaveRequest,void 0,e)}static internal(t,e){return new Es(t,gs.InternalError,void 0,e)}static cancelled(t){return new Es(t,gs.Cancelled)}static serverUnreachable(t,e){return new Es(t,gs.ServerUnreachable,e)}static websocket(t,e,i){return new Es(t,gs.WebSocket,e,i)}static serviceNotFound(t,e){return new Es(t,gs.ServiceNotFound,void 0,e)}}class Os extends ps{constructor(t){super(21,null!=t?t:"device is unsupported"),this.name="DeviceUnsupportedError"}}class As extends ps{constructor(t){super(20,null!=t?t:"track is invalid"),this.name="TrackInvalidError"}}class xs extends ps{constructor(t){super(10,null!=t?t:"unsupported server"),this.name="UnsupportedServer"}}class Cs extends ps{constructor(t){super(12,null!=t?t:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class _s extends ps{constructor(t){super(13,null!=t?t:"unable to negotiate"),this.name="NegotiationError"}}class Rs extends ps{constructor(t,e){super(15,t),this.name="PublishTrackError",this.status=e}}class Is extends ps{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"}(bs||(bs={}));class js extends ps{constructor(t,e){super(16,t),this.name="DataStreamError",this.reason=e,this.reasonName=bs[e]}}class Ps extends ps{constructor(t){super(18,t),this.name="SignalReconnectError"}}!function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"}(ys||(ys={})),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}}(ys||(ys={}));class Ds{}Ds.setTimeout=function(){return setTimeout(...arguments)},Ds.setInterval=function(){return setInterval(...arguments)},Ds.clearTimeout=function(){return clearTimeout(...arguments)},Ds.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"}(ws||(ws={})),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"}(ks||(ks={})),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"}(Ts||(Ts={})),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"}(Ss||(Ss={}));class Ms{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 Ns=["vp8","h264"],Us=["vp8","h264","vp9","av1","h265"],Ls=function(t){return!!Ns.find((e=>e===t))};var Bs,Fs;!function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"}(Bs||(Bs={})),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}}(Fs||(Fs={}));const qs={h90:new Ms(160,90,9e4,20),h180:new Ms(320,180,16e4,20),h216:new Ms(384,216,18e4,20),h360:new Ms(640,360,45e4,20),h540:new Ms(960,540,8e5,25),h720:new Ms(1280,720,17e5,30),h1080:new Ms(1920,1080,3e6,30),h1440:new Ms(2560,1440,5e6,30),h2160:new Ms(3840,2160,8e6,30)},Vs={h120:new Ms(160,120,7e4,20),h180:new Ms(240,180,125e3,20),h240:new Ms(320,240,14e4,20),h360:new Ms(480,360,33e4,20),h480:new Ms(640,480,5e5,20),h540:new Ms(720,540,6e5,25),h720:new Ms(960,720,13e5,30),h1080:new Ms(1440,1080,23e5,30),h1440:new Ms(1920,1440,38e5,30)},zs={h360fps3:new Ms(640,360,2e5,3,"medium"),h360fps15:new Ms(640,360,4e5,15,"medium"),h720fps5:new Ms(1280,720,8e5,5,"medium"),h720fps15:new Ms(1280,720,15e5,15,"medium"),h720fps30:new Ms(1280,720,2e6,30,"medium"),h1080fps15:new Ms(1920,1080,25e5,15,"medium"),h1080fps30:new Ms(1920,1080,5e6,30,"medium"),original:new Ms(0,0,7e6,30,"medium")};function Js(t,e,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:h}=Xs(null!=t?t:{}),d=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&&(Ws(u.audio,e),null!==(n=(r=u.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||d)&&(u.audio.processor=null!=c?c:d)),u.video&&(Ws(u.video,i),null!==(s=(o=u.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(h||l)&&(u.video.processor=null!=h?h:l)),u}function Ws(t,e){return Object.keys(e).forEach((i=>{void 0===t[i]&&(t[i]=e[i])})),t}function Gs(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?Ws(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 Qs(){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=()=>Zi(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 Hs(t){return"audioinput"===t?nr.Source.Microphone:"videoinput"===t?nr.Source.Camera:nr.Source.Unknown}function Ks(t){return t===nr.Source.Microphone?"audioinput":t===nr.Source.Camera?"videoinput":void 0}function Ys(t){return t.split("/")[1].toLowerCase()}function $s(t){const e=[];return t.forEach((t=>{void 0!==t.track&&e.push(new Ke({cid:t.track.mediaStreamID,track:t.trackInfo}))})),e}function Zs(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?Zs(t.track):{})}}function Xs(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:(s=e,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function tr(t,e){return t.width*t.height<e.width*e.height}const er=[];var ir;!function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"}(ir||(ir={}));class nr extends nn.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=nr.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Qi,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=Hi(null!==(n=i.loggerName)&&void 0!==n?n:Ji.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=e,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=nr.Source.Unknown}get logContext(){var t;return Object.assign(Object.assign({},null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this)),Zs(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let e="audio";this.kind===nr.Kind.Video&&(e="video"),0===this.attachedElements.length&&this.kind===nr.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===e&&(er.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&er.splice(er.indexOf(t),1)),t||(t=document.createElement(e))),this.attachedElements.includes(t)||this.attachedElements.push(t),sr(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),n=i.some((t=>"audio"===t.kind));return t.play().then((()=>{this.emit(n?Ss.AudioPlaybackStarted:Ss.VideoPlaybackStarted)})).catch((e=>{"NotAllowedError"===e.name?this.emit(n?Ss.AudioPlaybackFailed:Ss.VideoPlaybackFailed,e):"AbortError"===e.name?Qi.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Qi.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(Ss.ElementAttached,t),t}detach(t){try{if(t){rr(this.mediaStreamTrack,t);const e=this.attachedElements.indexOf(t);return e>=0&&(this.attachedElements.splice(e,1),this.recycleElement(t),this.emit(Ss.ElementDetached,t)),t}const e=[];return this.attachedElements.forEach((t=>{rr(this.mediaStreamTrack,t),e.push(t),this.recycleElement(t),this.emit(Ss.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=Hi(t.loggerName)),t.loggerContextCb&&(this.loggerContextCb=t.loggerContextCb)}recycleElement(t){if(t instanceof HTMLAudioElement){let e=!0;t.pause(),er.forEach((t=>{t.parentElement||(e=!1)})),e&&er.push(t)}}handleAppVisibilityChanged(){return Zi(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==nr.Kind.Video||setTimeout((()=>this.attachedElements.forEach((t=>t.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){gr()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){gr()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function sr(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)),vr()&&e instanceof HTMLVideoElement||(e.autoplay=!0),e.muted=0===i.getAudioTracks().length,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==i&&(e.srcObject=i,(vr()||ur())&&e instanceof HTMLVideoElement&&setTimeout((()=>{e.srcObject=i,e.play().catch((()=>{}))}),0))}function rr(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 Ft.AUDIO;case e.Video:return Ft.VIDEO;default:return Ft.DATA}},t.kindFromProto=function(t){switch(t){case Ft.AUDIO:return e.Audio;case Ft.VIDEO:return e.Video;default:return e.Unknown}},t.sourceToProto=function(t){switch(t){case i.Camera:return qt.CAMERA;case i.Microphone:return qt.MICROPHONE;case i.ScreenShare:return qt.SCREEN_SHARE;case i.ScreenShareAudio:return qt.SCREEN_SHARE_AUDIO;default:return qt.UNKNOWN}},t.sourceFromProto=function(t){switch(t){case qt.CAMERA:return i.Camera;case qt.MICROPHONE:return i.Microphone;case qt.SCREEN_SHARE:return i.ScreenShare;case qt.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},t.streamStateFromProto=function(t){switch(t){case Be.ACTIVE:return n.Active;case Be.PAUSED:return n.Paused;default:return n.Unknown}}}(nr||(nr={}));const or="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ar(t){return new hs((e=>Ds.setTimeout(e,t)))}function cr(){return"addTransceiver"in RTCPeerConnection.prototype}function hr(){return"addTrack"in RTCPeerConnection.prototype}function dr(t){return"av1"===t||"vp9"===t}function lr(t){return!(!document||mr())&&(t||(t=document.createElement("audio")),"setSinkId"in t)}function ur(){var t;return"Firefox"===(null===(t=us())||void 0===t?void 0:t.name)}function fr(){const t=us();return!!t&&"Chrome"===t.name&&"iOS"!==t.os}function vr(){var t;return"Safari"===(null===(t=us())||void 0===t?void 0:t.name)}function mr(){const t=us();return"Safari"===(null==t?void 0:t.name)||"iOS"===(null==t?void 0:t.os)}function pr(){var t,e;return!!gr()&&(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 gr(){return"undefined"!=typeof document}function br(){return"ReactNative"==navigator.product}function yr(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function wr(t){return yr(t)?t.hostname.split(".")[0]:null}function kr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Tr(){if(!br())return;let t=kr();return t?t.platform:void 0}function Sr(){if(gr())return window.devicePixelRatio;if(br()){let t=kr();if(t)return t.devicePixelRatio}return 1}function Er(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 Or(t){for(const e of t)e.target.handleResize(e)}function Ar(t){for(const e of t)e.target.handleVisibilityChanged(e)}let xr=null;const Cr=()=>(xr||(xr=new ResizeObserver(Or)),xr);let _r=null;const Rr=()=>(_r||(_r=new IntersectionObserver(Ar,{root:null,rootMargin:"0px"})),_r);function Ir(){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 Pr(){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 Dr{get isResolved(){return this._isResolved}constructor(t,e){this._isResolved=!1,this.onFinally=e,this.promise=new Promise(((e,i)=>Zi(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 Mr(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 Nr(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function Ur(t){switch(t.reason){case gs.LeaveRequest:return t.context;case gs.Cancelled:return Wt.CLIENT_INITIATED;case gs.NotAllowed:return Wt.USER_REJECTED;case gs.ServerUnreachable:return Wt.JOIN_FAILURE;default:return Wt.UNKNOWN_REASON}}function Lr(t){return void 0!==t?Number(t):void 0}function Br(t){return void 0!==t?BigInt(t):void 0}function Fr(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function qr(t){return!!t&&t.kind==nr.Kind.Audio}function Vr(t){return!!t&&t.kind==nr.Kind.Video}function zr(t){return Fr(t)&&Vr(t)}function Jr(t){return Fr(t)&&qr(t)}function Wr(t){return!!t&&!t.isLocal}function Gr(t){return!!t&&!t.isLocal}function Qr(t){return Wr(t)&&Vr(t)}function Hr(t){return t.endsWith("/")?t:"".concat(t,"/")}function Kr(t,e){return t.pathname="".concat(Hr(t.pathname)).concat(e),t}function Yr(t){if("string"==typeof t)return Ve.fromJson(JSON.parse(t),{ignoreUnknownFields:!0});if(t instanceof ArrayBuffer)return Ve.fromBinary(new Uint8Array(t));throw new Error("could not decode websocket message: ".concat(typeof t))}const $r="lk_e2ee";var Zr,Xr,to,eo,io;function no(){return void 0!==window.RTCRtpScriptTransform}!function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"}(Zr||(Zr={})),function(t){t.KeyRatcheted="keyRatcheted"}(Xr||(Xr={})),function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"}(to||(to={})),function(t){t.Error="cryptorError"}(eo||(eo={})),function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"}(io||(io={}));class so extends nn.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(Qi.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(to.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(to.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(to.ParticipantEncryptionStatusChanged,s.enabled,t)}break;case"ratchetKey":this.keyProvider.emit(Zr.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=>{Qi.error("e2ee worker encountered an error:",{error:t.error}),this.emit(to.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||no()))throw new Os("tried to setup end-to-end encryption on an unsupported browser");if(Qi.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:Ki.getLevel()}};this.worker&&(Qi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(e))}}setParticipantCryptorEnabled(t,e){Qi.debug("set e2ee to ".concat(t," for participant ").concat(e)),this.postEnable(t,e)}setSifTrailer(t){t&&0!==t.length?this.postSifTrailer(t):Qi.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(Ts.RTPVideoMapUpdate,(t=>{this.postRTPMap(t)}))}setupEventListeners(t,e){t.on(ws.TrackPublished,((t,e)=>this.setParticipantCryptorEnabled(t.trackInfo.encryption!==ie.NONE,e.identity))),t.on(ws.ConnectionStateChanged,(e=>{e===Ea.Connected&&t.remoteParticipants.forEach((t=>{t.trackPublications.forEach((e=>{this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ie.NONE,t.identity)}))}))})).on(ws.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(ws.TrackSubscribed,((t,e,i)=>{this.setupE2EEReceiver(t,i.identity,e.trackInfo)})).on(ws.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(ks.LocalSenderCreated,((t,e)=>Zi(this,void 0,void 0,(function*(){this.setupE2EESender(e,t)})))),t.localParticipant.on(ks.LocalTrackPublished,(t=>{if(!Vr(t.track)||!mr())return;const e={kind:"updateCodec",data:{trackId:t.track.mediaStreamID,codec:Ys(t.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(e)})),e.on(Zr.SetKey,(t=>this.postKey(t))).on(Zr.RatchetRequest,((t,e)=>this.postRatchetRequest(t,e)))}encryptData(t){return Zi(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 Dr;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 Dr;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?Ys(i.mimeType):void 0)}}setupE2EESender(t,e){Fr(t)&&e?this.handleSender(e,t.mediaStreamID,void 0):e||Qi.warn("early return because sender is not ready")}handleReceiver(t,e,i,n){return Zi(this,void 0,void 0,(function*(){if(this.worker){if(no()&&!fr())t.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:e,codec:n});else{if($r 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:$r in t}},[r,s])}t[$r]=!0}}))}handleSender(t,e,i){var n;if(!($r 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(no()&&!fr())Qi.info("initialize script transform"),t.transform=new RTCRtpScriptTransform(this.worker,{kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:e,codec:i});else{Qi.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[$r]=!0}}}class ro{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new ro),this._instance}addFailedConnectionAttempt(t){var e;const i=wr(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,ar(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(t){const e=new URL(t),i=e&&wr(e);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(t){const e=new URL(t),i=e&&wr(e);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}ro._instance=null;const oo="default";class ao{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new ao),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return Zi(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=ao.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Qi.debug("awaiting getUserMedia promise");try{t?yield ao.userMediaPromiseMap.get(t):yield Promise.all(ao.userMediaPromiseMap.values())}catch(t){Qi.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!vr()||!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 Zi(this,void 0,void 0,(function*(){if(e!==oo)return e;const n=yield this.getDevices(t),s=n.find((t=>t.deviceId===oo));if(!s)return void Qi.warn("could not reliably determine default device");const r=n.find((t=>t.deviceId!==oo&&t.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;Qi.warn("could not reliably determine default device")}))}hasDeviceInUse(t){return t?ao.userMediaPromiseMap.has(t):ao.userMediaPromiseMap.size>0}}var co;ao.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ao.userMediaPromiseMap=new Map,function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"}(co||(co={}));class ho{constructor(){this.pendingTasks=new Map,this.taskMutex=new a,this.nextTaskIndex=0}run(t){return Zi(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:co.WAITING};this.pendingTasks.set(e.id,e);const i=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=co.RUNNING,yield t()}finally{e.status=co.COMPLETED,this.pendingTasks.delete(e.id),i()}}))}flush(){return Zi(this,void 0,void 0,(function*(){return this.run((()=>Zi(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}class lo{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 hs(((t,e)=>{const i=()=>{e(Es.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 hs(((t,e)=>{const i=()=>Zi(this,void 0,void 0,(function*(){const i=new hs((t=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",(e=>{t(e)}),{once:!0})})),n=yield hs.race([ar(250),i]);n?t(n):e(Es.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 uo=["syncState","trickle","offer","answer","simulate","leave"];var fo;!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"}(fo||(fo={}));class vo{get currentState(){return this.state}get isDisconnected(){return this.state===fo.DISCONNECTING||this.state===fo.DISCONNECTED}get isEstablishingConnection(){return this.state===fo.CONNECTING||this.state===fo.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=fo.DISCONNECTED,this.log=Qi,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=Hi(null!==(i=e.loggerName)&&void 0!==i?i:Ji.Signal),this.loggerContextCb=e.loggerContextCb,this.useJSON=t,this.requestQueue=new ho,this.queuedRequests=[],this.closingLock=new a,this.connectionLock=new a,this.state=fo.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 Zi(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=fo.CONNECTING,s.options=i,yield s.connect(t,e,i,n,r)}()}))}reconnect(t,e,i,n){return Zi(this,void 0,void 0,(function*(){if(this.options)return this.state=fo.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 Zi(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 Oe({sdk:Ae.JS,protocol:16,version:"2.17.0"});return br()&&(e.os=null!==(t=Tr())&&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",br()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),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.toString()),(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 Mi({clientInfo:e,connectionSettings:new Di({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 Ni({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}(e,a,i),h=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)})),Kr(i,"rtc")}(t,e);return i?n:Kr(n,"v1")}(t,c,r).toString(),d=(l=h,Kr(new URL(Nr(l)),"validate")).toString();var l;return new Promise(((t,e)=>Zi(s,void 0,void 0,(function*(){var s,r;try{let o=!1;const a=t=>Zi(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.toString():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(Es.cancelled(i))}));null==n||n.addEventListener("abort",a);const c=()=>{clearTimeout(l),null==n||n.removeEventListener("abort",a)},l=setTimeout((()=>{a(Es.timeout("room connection has timed out (signal)"))}),i.websocketTimeout),u=(t,e)=>{this.handleSignalConnected(t,l,e)},f=new URL(h);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 lo(h);try{this.ws.closed.then((t=>{var i;this.isEstablishingConnection&&e(Es.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===fo.CONNECTED&&this.handleOnClose(null!==(i=t.reason)&&void 0!==i?i:"Unexpected WS error"))})).catch((t=>{this.isEstablishingConnection&&e(Es.internal("Websocket error during a (re)connection attempt: ".concat(t)))}));const n=yield this.ws.opened.catch((t=>Zi(this,void 0,void 0,(function*(){if(this.state===fo.CONNECTED)this.handleWSError(t),e(t);else{this.state=fo.DISCONNECTED,clearTimeout(l);const i=yield this.handleConnectionError(t,d);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 Es.internal("no message received as first message");const c=Yr(a.value),h=this.validateFirstMessage(c,null!==(s=i.reconnect)&&void 0!==s&&s);if(!h.isValid)return void e(h.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,h.shouldProcessFirstMessage?c:void 0),t(h.response)}catch(t){e(t)}finally{c()}}finally{o()}}))))}()}))}startReadingLoop(t,e){return Zi(this,void 0,void 0,(function*(){for(e&&this.handleSignalResponse(e);;){this.signalLatency&&(yield ar(this.signalLatency));const{done:e,value:i}=yield t.read();if(e)break;const n=Yr(i);this.handleSignalResponse(n)}}))}close(){return Zi(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([fo.DISCONNECTING||fo.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=fo.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,ar(250)])}}catch(e){t.log.debug("websocket error while closing",Object.assign(Object.assign({},t.logContext),{error:e}))}finally{e&&(t.state=fo.DISCONNECTED),n()}}()}))}sendOffer(t,e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:t.sdp})),this.sendRequest({case:"offer",value:po(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:po(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 We({candidateInit:JSON.stringify(t),target:e})})}sendMuteTrack(t,e){return this.sendRequest({case:"mute",value:new Ge({sid:t,muted:e})})}sendAddTrack(t){return this.sendRequest({case:"addTrack",value:t})}sendUpdateLocalMetadata(t,e){return Zi(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 oi({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 ri({trackSid:t,layers:e})})}sendUpdateSubscriptionPermissions(t,e){return this.sendRequest({case:"subscriptionPermission",value:new yi({allParticipants:t,trackPermissions:e})})}sendSimulateScenario(t){return this.sendRequest({case:"simulate",value:t})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:x.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ai({timestamp:x.parse(Date.now()),rtt:x.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(t,e){return this.sendRequest({case:"updateAudioTrack",value:new ei({trackSid:t,features:e})})}sendLeave(){return this.sendRequest({case:"leave",value:new ni({reason:Wt.CLIENT_INITIATED,action:si.DISCONNECT})})}sendRequest(t){return Zi(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=uo.indexOf(t.case)>=0;return Qi.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}(t);if(n&&e.state===fo.RECONNECTING)return void e.queuedRequests.push((()=>Zi(e,void 0,void 0,(function*(){yield this.sendRequest(t,!0)}))));if(i||(yield e.requestQueue.flush()),e.signalLatency&&(yield ar(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 qe({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=mo(n.value);this.onAnswer&&this.onAnswer(t,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const t=mo(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.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"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 Zi(this,void 0,void 0,(function*(){if(this.state===fo.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=Ds.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&&Ds.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Ds.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&&Ds.clearInterval(this.pingInterval)}handleSignalConnected(t,e,i){this.state=fo.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===fo.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:Es.leaveRequest("Received leave request while trying to (re)connect",t.message.value.reason)}:e?{isValid:!1,error:Es.internal("Unexpected first message")}:{isValid:!1,error:Es.internal("did not receive join response, got ".concat(null===(o=t.message)||void 0===o?void 0:o.case," instead"))}}handleConnectionError(t,e){return Zi(this,void 0,void 0,(function*(){try{const i=yield fetch(e);switch(i.status){case 404:return Es.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield i.text();return Es.notAllowed(t,i.status)}return t instanceof Es?t:Es.internal("Encountered unknown websocket error during connection: ".concat(t),{status:i.status,statusText:i.statusText})}catch(t){return t instanceof Es?t:Es.serverUnreachable(t instanceof Error?t.message:"server was not reachable")}}))}}function mo(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 po(t,e){return new $e({sdp:t.sdp,type:t.type,id:e})}class go{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 bo{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 yo,wo,ko,To,So,Eo={},Oo={},Ao={exports:{}};function xo(){if(yo)return Ao.exports;yo=1;var t=Ao.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:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(t){return"imageattr:%s %s %s"+(t.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(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")}))})),Ao.exports}function Co(){return wo||(wo=1,function(t){var e=function(t){return String(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=xo(),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.toString().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}}))}))}}(Oo)),Oo}function _o(){if(To)return ko;To=1;var t=xo(),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 String(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 ko=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"},ko}var Ro=function(){if(So)return Eo;So=1;var t=Co(),e=_o(),i=xo();return Eo.grammar=i,Eo.write=e,Eo.parse=t.parse,Eo.parseParams=t.parseParams,Eo.parseFmtpConfig=t.parseFmtpConfig,Eo.parsePayloads=t.parsePayloads,Eo.parseRemoteCandidates=t.parseRemoteCandidates,Eo.parseImageAttributes=t.parseImageAttributes,Eo.parseSimulcastStreamList=t.parseSimulcastStreamList,Eo}();function Io(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,h=Date.now(),d=[];function l(){if(void 0!==c){var t=Date.now()-h;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,h=Date.now(),!o){var n=t.apply(i,e);a&&a(n),d.forEach((function(t){return(0,t.resolve)(n)})),d=[]}}),l()),c){var u=t.apply(i,e);return a&&a(u),n(u)}d.push({resolve:n,reject:s})}))};return u.cancel=function(t){void 0!==r&&clearTimeout(r),d.forEach((function(e){return(0,e.reject)(t)})),d=[]},u}const jo="negotiationStarted",Po="negotiationComplete",Do="rtpVideoPayloadTypes";class Mo extends nn.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=Qi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Io((t=>Zi(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=Hi(null!==(i=e.loggerName)&&void 0!==i?i:Ji.PCTransport),this.loggerOptions=e,this.config=t,this._pc=this.createPC(),this.offerLock=new a}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 Zi(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 Zi(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=Ro.parse(null!==(e=t.sdp)&&void 0!==e?e:"");let r=0;return s.media.forEach((t=>{var e;const s=Lo(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=Ro.parse(null!==(i=t.sdp)&&void 0!==i?i:"");e.media.forEach((t=>{const e=Lo(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=Ro.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(Po),t.sdp)&&Ro.parse(t.sdp).media.forEach((t=>{"video"===t.type&&this.emit(Do,t.rtp)})),!0}))}createAndSendOffer(t){return Zi(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=Ro.parse(null!==(e=n.sdp)&&void 0!==e?e:"");if(s.media.forEach((t=>{Uo(t),"audio"===t.type?No(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(dr(e.codec)&&!vr()&&this.ensureVideoDDExtensionForSVC(t,s),!dr(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,Ro.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}}))}createAndSetAnswer(){return Zi(this,void 0,void 0,(function*(){var t;const e=yield this.pc.createAnswer(),i=Ro.parse(null!==(t=e.sdp)&&void 0!==t?t:"");return i.media.forEach((t=>{Uo(t),"audio"===t.type&&No(t,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(e,Ro.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 Cs("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 Cs("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 Zi(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 Zi(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 _s(n)}}))}ensureVideoDDExtensionForSVC(t,e){var i,n;if(!(null===(i=t.ext)||void 0===i?void 0:i.some((t=>t.uri===or)))){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:or})}}}function No(t,e,i){const n=Lo(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 Uo(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 Lo(t){return"number"==typeof t?t.toFixed(0):t}const Bo="vp8",Fo={audioPreset:Fs.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:zs.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Bo,backupCodec:!0,preConnectBuffer:!1},qo={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Vo={deviceId:{ideal:"default"},resolution:qs.h720.resolution},zo={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(t){this._retryDelays=void 0!==t?[...t]:$i}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},Jo={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Wo;!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"}(Wo||(Wo={}));class Go{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=Jo.peerConnectionTimeout,this.log=Qi,this.updateState=()=>{var t,e;const i=this.state,n=this.requiredTransports.map((t=>t.getConnectionState()));n.every((t=>"connected"===t))?this.state=Wo.CONNECTED:n.some((t=>"failed"===t))?this.state=Wo.FAILED:n.some((t=>"connecting"===t))?this.state=Wo.CONNECTING:n.every((t=>"closed"===t))?this.state=Wo.CLOSED:n.some((t=>"closed"===t))?this.state=Wo.CLOSING:n.every((t=>"new"===t))&&(this.state=Wo.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(Wo[i]," to ").concat(Wo[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=Hi(null!==(n=i.loggerName)&&void 0!==n?n:Ji.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==e,this.isSubscriberConnectionRequired="subscriber-primary"===e,this.publisher=new Mo(t,i),this._mode=e,"publisher-only"!==e&&(this.subscriber=new Mo(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,Le.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,Le.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=Wo.NEW,this.connectionLock=new a,this.remoteOfferLock=new a}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 Zi(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 Zi(this,void 0,void 0,(function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(t,e){return Zi(this,void 0,void 0,(function*(){var i;e===Le.PUBLISHER?yield this.publisher.addIceCandidate(t):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(t)}))}createSubscriberAnswerFromOffer(t,e){return Zi(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().toString()}));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 Zi(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 Zi(this,void 0,void 0,(function*(){return new hs(((e,i)=>Zi(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i(new _s("negotiation timed out"))}),this.peerConnectionTimeout);t.signal.addEventListener("abort",(()=>{clearTimeout(n),i(new _s("negotiation aborted"))})),this.publisher.once(jo,(()=>{t.signal.aborted||this.publisher.once(Po,(()=>{clearTimeout(n),e()}))})),yield this.publisher.negotiate((t=>{clearTimeout(n),t instanceof Error?i(t):i(new Error(String(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===Le.PUBLISHER||t===Le.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 Zi(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)=>Zi(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Ds.clearTimeout(r),s(Es.cancelled("room connection has been cancelled"))};(null==e?void 0:e.signal.aborted)&&i(),null==e||e.signal.addEventListener("abort",i);const r=Ds.setTimeout((()=>{null==e||e.signal.removeEventListener("abort",i),s(Es.internal("could not establish pc connection"))}),n);for(;this.state!==Wo.CONNECTED;)if(yield ar(50),null==e?void 0:e.signal.aborted)return void s(Es.cancelled("room connection has been cancelled"));Ds.clearTimeout(r),null==e||e.signal.removeEventListener("abort",i),t()}))))}()}))}}class Qo{static fetchRegionSettings(t,e,i){return Zi(this,void 0,void 0,(function*(){const n=yield Qo.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?Es.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):Es.internal("Could not fetch region settings: ".concat(n.statusText))}catch(t){throw t instanceof Es?t:(null==i?void 0:i.aborted)?Es.cancelled("Region fetching was aborted"):Es.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 Zi(this,void 0,void 0,(function*(){const n=Qo.settingsTimeouts.get(t.hostname);clearTimeout(n),Qo.settingsTimeouts.set(t.hostname,setTimeout((()=>Zi(this,void 0,void 0,(function*(){try{const i=yield Qo.fetchRegionSettings(t,e);Qo.updateCachedRegionSettings(t,e,i)}catch(n){if(n instanceof Es&&n.reason===gs.NotAllowed)return void Qi.debug("token is not valid, cancelling auto region refresh");Qi.debug("auto refetching of region settings failed",{error:n}),Qo.scheduleRefetch(t,e,i)}}))),i))}))}static updateCachedRegionSettings(t,e,i){Qo.cache.set(t.hostname,i),Qo.scheduleRefetch(t,e,i.maxAgeInMs)}static stopRefetch(t){const e=Qo.settingsTimeouts.get(t);e&&(clearTimeout(e),Qo.settingsTimeouts.delete(t))}static scheduleCleanup(t){let e=Qo.connectionTrackers.get(t);e&&(e.cleanupTimeout&&clearTimeout(e.cleanupTimeout),e.cleanupTimeout=setTimeout((()=>{const e=Qo.connectionTrackers.get(t);e&&0===e.connectionCount&&(Qi.debug("stopping region refetch after disconnect delay",{hostname:t}),Qo.stopRefetch(t)),e&&(e.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(t){const e=Qo.connectionTrackers.get(t);(null==e?void 0:e.cleanupTimeout)&&(clearTimeout(e.cleanupTimeout),e.cleanupTimeout=void 0)}notifyConnected(){const t=this.serverUrl.hostname;let e=Qo.connectionTrackers.get(t);e||(e={connectionCount:0},Qo.connectionTrackers.set(t,e)),e.connectionCount++,Qo.cancelCleanup(t)}notifyDisconnected(){const t=this.serverUrl.hostname,e=Qo.connectionTrackers.get(t);e&&(e.connectionCount=Math.max(0,e.connectionCount-1),0===e.connectionCount&&Qo.scheduleCleanup(t))}constructor(t,e){this.attemptedRegions=[],this.serverUrl=new URL(t),this.token=e}updateToken(t){this.token=t}isCloud(){return yr(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return Zi(this,void 0,void 0,(function*(){return Qo.fetchRegionSettings(this.serverUrl,this.token,t)}))}getNextBestRegionUrl(t){return Zi(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let e=Qo.cache.get(this.serverUrl.hostname);(!e||Date.now()-e.updatedAtInMs>e.maxAgeInMs)&&(e=yield this.fetchRegionSettings(t),Qo.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),Qi.debug("next region: ".concat(t.region)),t.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){Qo.updateCachedRegionSettings(this.serverUrl,this.token,t)}}Qo.cache=new Map,Qo.settingsTimeouts=new Map,Qo.connectionTrackers=new Map,Qo.fetchLock=new a;class Ho extends Error{constructor(t,e,i){super(e),this.code=t,this.message=Yo(e,Ho.MAX_MESSAGE_BYTES),this.data=i?Yo(i,Ho.MAX_DATA_BYTES):void 0}static fromProto(t){return new Ho(t.code,t.message,t.data)}toProto(){return new ke({code:this.code,message:this.message,data:this.data})}static builtIn(t,e){return new Ho(Ho.ErrorCode[t],Ho.ErrorMessage[t],e)}}function Ko(t){return(new TextEncoder).encode(t).length}function Yo(t,e){if(Ko(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)}Ho.MAX_MESSAGE_BYTES=256,Ho.MAX_DATA_BYTES=15360,Ho.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},Ho.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 $o=2e3;function Zo(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 Xo="undefined"!=typeof MediaRecorder,ta=Xo?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class ea extends ta{constructor(t,e){if(!Xo)throw new 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=>Zi(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 new 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 ia extends nr{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=Io((()=>Zi(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Zi(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(Ss.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new a,this.pauseUpstreamLock=new a,this.trackChangeLock=new a,this.trackChangeLock.lock().then((e=>Zi(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!==nr.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 Zi(this,void 0,void 0,(function*(){var i;if(t===this._mediaStreamTrack&&!e)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((t=>{rr(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&&(sr(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=>{sr(null!=n?n:t,e)})))}))}waitForDimensions(){return Zi(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===nr.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=us())||void 0===i?void 0:i.os)&&(yield ar(10));const n=Date.now();for(;Date.now()-n<e;){const e=t.dimensions;if(e)return e;yield ar(50)}throw new As("unable to get track dimensions after timeout")}()}))}setDeviceId(t){return Zi(this,void 0,void 0,(function*(){return this._constraints.deviceId===t&&this._mediaStreamTrack.getSettings().deviceId===Mr(t)||(this._constraints.deviceId=t,!!this.isMuted||(yield this.restartTrack(),Mr(t)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Zi(this,arguments,void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(t.source===nr.Source.ScreenShare)return;const{deviceId:i,groupId:n}=t._mediaStreamTrack.getSettings(),s=t.kind===nr.Kind.Audio?"audioinput":"videoinput";return e?ao.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return Zi(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Zi(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(t,e){return Zi(this,void 0,void 0,(function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new As("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 Zi(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===nr.Kind.Video?s.video=!e&&!i||{deviceId:e,facingMode:i}:s.audio=!e||Object.assign({deviceId:e},n),this.attachedElements.forEach((t=>{rr(this.mediaStreamTrack,t)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===nr.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(Ss.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?Ss.Muted:Ss.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 Zi(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),pr()&&(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 Zi(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(Ss.UpstreamPaused,this);const e=us();if("Safari"===(null==e?void 0:e.name)&&Er(e.version,"12.0")<0)throw new Os("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 Zi(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(Ss.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 Zi(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 Zi(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(sr(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&&(rr(e._mediaStreamTrack,t),sr(e.processor.processedTrack,t));yield null===(n=e.sender)||void 0===n?void 0:n.replaceTrack(e.processor.processedTrack)}e.emit(Ss.TrackProcessorUpdate,e.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Zi(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 Zi(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(Ss.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(Xo)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 ea(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 na extends ia{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,e){let i=arguments.length>3?arguments[3]:void 0;super(t,nr.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=()=>Zi(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=Zo(t,this.prevStats)),this.prevStats=t})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Ss.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Ss.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return Zi(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===nr.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 Zi(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!==Mr(this._constraints.deviceId);return this.source!==nr.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 Zi(this,void 0,void 0,(function*(){let e;if(t){const i=Gs({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 Zi(this,void 0,void 0,(function*(){const i=yield e.restart.call(this,t);return this.checkForSilence(),i}))}startMonitor(){gr()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),$o)))}setProcessor(t){return Zi(this,void 0,void 0,(function*(){var e;const i=yield this.trackChangeLock.lock();try{if(!br()&&!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(Ss.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(t){this.audioContext=t}getSenderStats(){return Zi(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 Zi(this,void 0,void 0,(function*(){const t=yield function(t){return Zi(this,arguments,void 0,(function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Qs();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([t.mediaStreamTrack])).connect(n),yield ar(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(Ss.AudioSilenceDetected)),t}))}}const sa=Object.values(qs),ra=Object.values(Vs),oa=Object.values(zs),aa=[qs.h180,qs.h360],ca=[Vs.h180,Vs.h360],ha=["q","h","f"];function da(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,h=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 oa;const n=e>i?e/i:i/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?sa:ra}(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,h),Qi.debug("using video encoding",o));const d=o.maxFramerate,l=new Ms(e,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&dr(h)){const t=new va(c),e=[];if(t.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=us();if(mr()||br()||"Chrome"===(null==i?void 0:i.name)&&Er(null==i?void 0:i.version,"113")<0){const n="h"==t.suffix?2:3,s=function(t){return t||(t=us()),"Safari"===(null==t?void 0:t.name)&&Er(t.version,"18.3")>0||"iOS"===(null==t?void 0:t.os)&&!!(null==t?void 0:t.osVersion)&&Er(t.osVersion,"18.3")>0}(i);for(let i=0;i<t.spatial;i+=1)e.push({rid:ha[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),Qi.debug("using svc encoding",{encodings:e}),e}if(!a)return[o];let u,f=[];if(f=t?null!==(s=fa(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:la(t,l):null!==(r=fa(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:la(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 ua(e,i,[t,u,l],d);if(n>=480)return ua(e,i,[t,l],d)}return ua(e,i,[l])}function la(t,e){if(t)return[{scaleResolutionDownBy:2,fps:(i=e).encoding.maxFramerate}].map((t=>{var e,n;return new Ms(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(e=i.encoding.maxFramerate)&&void 0!==e?e:30)/(null!==(n=t.fps)&&void 0!==n?n:30))))),t.fps,i.encoding.priority)}));var i;const{width:n,height:s}=e,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?aa:ca}function ua(t,e,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=ha.length)return;const o=Math.min(t,e),a={rid:ha[r],scaleResolutionDownBy:Math.max(1,o/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const h=ur()||0===r;i.encoding.priority&&h&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)})),br()&&"ios"===Tr()){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,Qi.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Qi.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(t)),i.maxFramerate=t)}))}return s}function fa(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 va{constructor(t){const e=t.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!e)throw new 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 ma extends ia{get sender(){return this._sender}set sender(t){this._sender=t,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,e){super(t,nr.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=()=>Zi(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(Ss.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+=Zo(e,s)})),this._currentBitrate=t}this.prevStats=e})),this.senderLock=new a}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(t){var e;if(this.signalClient=t,!gr())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()}),$o))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((t=>{t.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const t=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Zi(this,void 0,void 0,(function*(){var e,i,n,s;yield t.pauseUpstream.call(this);try{for(var r,o=!0,a=Xi(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 Zi(this,void 0,void 0,(function*(){var e,i,n,s;yield t.resumeUpstream.call(this);try{for(var r,o=!0,a=Xi(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 Zi(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!==nr.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 Zi(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.source!==nr.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 Zi(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=ir.LOW;i<=ir.HIGH;i+=1)e.push(new vi({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(dr(this.codec),e)}restartTrack(t){return Zi(this,void 0,void 0,(function*(){var e,i,n,s;let r;if(t){const e=Gs({video:t});"boolean"!=typeof e.video&&(r=e.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var o,a=!0,c=Xi(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 Zi(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 h,d=!0,l=Xi(i.simulcastCodecs.values());!(s=(h=yield l.next()).done);d=!0){d=!1;const t=h.value;yield null===(c=t.sender)||void 0===c?void 0:c.replaceTrack(i.processor.processedTrack)}}catch(t){r={error:t}}finally{try{d||s||!(o=l.return)||(yield o.call(l))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(t){return Zi(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 Zi(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(dr(t[0].codec),t[0].qualities),[];this.subscribedCodecs=t;const a=[];try{for(e=!0,i=Xi(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 pa(e.sender,e.encodings,t.qualities,this.senderLock,dr(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(dr(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 Zi(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 pa(this.sender,this.encodings,e,this.senderLock,t,this.log,this.logContext)))}))}prioritizePerformance(){return Zi(this,void 0,void 0,(function*(){if(!this.sender)throw new 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&&dr(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 Zi(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),pr()&&this.isInBackground&&this.source===nr.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function pa(t,e,i,n,s,r,o){return Zi(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 h=ga(a),d=i.find((t=>t.quality===h));d&&t.active!==d.enabled&&(c=!0,t.active=d.enabled,r.debug("setting layer ".concat(d.quality," to ").concat(t.active?"enabled":"disabled"),o),ur()&&(d.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 ga(t){switch(t){case"f":default:return ir.HIGH;case"h":return ir.MEDIUM;case"q":return ir.LOW}}function ba(t,e,i,n){if(!i)return[new re({quality:ir.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(n){const n=new va(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 re({quality:Math.min(ir.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=ga(null!==(s=i.rid)&&void 0!==s?s:"");return new re({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 ya="_lossy",wa="_reliable",ka="leave-reconnect";var Ta,Sa,Ea,Oa;!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"}(Ta||(Ta={}));class Aa extends nn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var e;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Jo.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ta.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=Qi,this.reliableDataSequence=1,this.reliableMessageBuffer=new go,this.reliableReceivedState=new bo(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=t=>Zi(this,[t],void 0,(function(t){var e=this;let{channel:i}=t;return function*(){if(i){if(i.label===wa)e.reliableDCSub=i;else{if(i.label!==ya)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=>Zi(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=ae.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(Ts.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=de.fromBinary(t.payload),i=new ae({value:e.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&xa(i,i.value.value),this.emit(Ts.DataPacketReceived,i,a.value.value.encryptionType)}else"user"===(null===(r=a.value)||void 0===r?void 0:r.case)&&xa(a,a.value.value),this.emit(Ts.DataPacketReceived,a,ie.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?ce.LOSSY:ce.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===ka&&(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=Ds.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(Ts.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((t,e)=>{this.pcState===Ta.Connected&&t();const i=()=>{this.off(Ts.Disconnected,n),t()},n=()=>{this.off(Ts.Restarted,i),e()};this.once(Ts.Restarted,i),this.once(Ts.Disconnected,n)})),this.updateAndEmitDCBufferStatus=t=>{if(t===ce.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(Ts.DCBufferStatusChanged,e,t))},this.isBufferStatusLow=t=>{const e=this.dataChannelForKind(t);if(e)return e.bufferedAmount<=e.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>Zi(this,void 0,void 0,(function*(){this.url&&(yield fetch(Nr(this.url),{method:"HEAD"}).then((t=>t.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===fo.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===fo.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Gt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>Zi(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(Nr(this.url),{method:"HEAD"}),ar(4e3).then((()=>Promise.reject()))])}catch(t){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=Hi(null!==(e=t.loggerName)&&void 0!==e?e:Ji.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new vo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new a,this.dataProcessLock=new a,this.dcBufferStatus=new Map([[ce.LOSSY,!0],[ce.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(Ts.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(Ts.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(Ts.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(Ts.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(Ts.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(Ts.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(Ts.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(Ts.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 Zi(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=>{Qi.error(t,s.logContext)})),s.registerOnLineListener(),s.clientConfiguration=o.clientConfiguration,s.emit(Ts.SignalConnected,o),o}catch(o){if(o instanceof Es)if(o.reason===gs.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===gs.ServiceNotFound)return s.log.warn("Initial connection failed: ".concat(o.message," – Retrying")),s.join(t,e,i,n,!0);throw o}}()}))}close(){return Zi(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(Ts.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return Zi(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 go,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 Zi(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(t){if(this.pendingTrackResolvers[t.cid])throw new As("a track with the same ID has already been published");return new Promise(((e,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[t.cid],i(Es.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(new 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 Zi(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 Zi(this,void 0,void 0,(function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==Wo.NEW)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const s=this.makeRTCConfiguration(t);var r;this.pcManager=new Go(s,e?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(Ts.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)=>Zi(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===Wo.CONNECTED){const e=this.pcState===Ta.New;this.pcState=Ta.Connected,e&&this.emit(Ts.Connected,t)}else e===Wo.FAILED&&(this.pcState!==Ta.Connected&&this.pcState!==Ta.Reconnecting||(this.pcState=Ta.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?Gt.RR_SUBSCRIBER_FAILED:Gt.RR_PUBLISHER_FAILED)));const s=this.client.isDisconnected||this.client.currentState===fo.RECONNECTING,r=[Wo.FAILED,Wo.CLOSING,Wo.CLOSED].includes(e);s&&r&&!this._isClosed&&this.emit(Ts.Offline)})),this.pcManager.onTrack=t=>{0!==t.streams.length&&this.emit(Ts.MediaTrackAdded,t.track,t.streams[0],t.receiver)},void 0!==(r=null===(n=t.serverInfo)||void 0===n?void 0:n.protocol)&&r>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=(t,e,i)=>Zi(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)=>Zi(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(Ts.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(Ts.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(Ts.RemoteMute,t,e)},this.client.onSubscribedQualityUpdate=t=>{this.emit(Ts.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(Ts.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",Gt.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 si.DISCONNECT:this.emit(Ts.Disconnected,null==t?void 0:t.reason),this.close();break;case si.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ka);break;case si.RESUME:this.handleDisconnect(ka)}}}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===Jt.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(ya,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(wa,{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(ce.LOSSY);t&&(t.bufferedAmountLowThreshold=Math.min(Math.max(this.lossyDataStatByterate/10,8192),262144))}),1e3))}createSender(t,e,i){return Zi(this,void 0,void 0,(function*(){if(cr())return yield this.createTransceiverRTCRtpSender(t,e,i);if(hr())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(t.mediaStreamTrack);throw new Cs("Required webRTC APIs not supported on this device")}))}createSimulcastSender(t,e,i,n){return Zi(this,void 0,void 0,(function*(){if(cr())return this.createSimulcastTransceiverSender(t,e,i,n);if(hr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(t.mediaStreamTrack);throw new Cs("Cannot stream on this device")}))}createTransceiverRTCRtpSender(t,e,i){return Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Cs("publisher is closed");const n=[];t.mediaStream&&n.push(t.mediaStream),Vr(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 Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Cs("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 Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Cs("publisher is closed");return this.pcManager.addPublisherTrack(t)}))}attemptReconnect(t){return Zi(this,void 0,void 0,(function*(){var e,i,n;if(!this._isClosed)if(this.attemptingReconnect)Qi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(e=this.clientConfiguration)||void 0===e?void 0:e.resumeConnection)!==Jt.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:Wo.NEW)!==Wo.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 Cs?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof Ps||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",Gt.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(Ts.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 Zi(this,void 0,void 0,(function*(){var e,i,n;try{if(!this.url||!this.token)throw new Cs("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Ts.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 Ps;i=yield this.join(null!=t?t:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(t){if(t instanceof Es&&t.reason===gs.NotAllowed)throw new Cs("could not reconnect, token might be expired");throw new Ps}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Ts.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==fo.CONNECTED)throw new Ps("Signal connection got severed during reconnect");null===(e=this.regionUrlProvider)||void 0===e||e.resetAttempts(),this.emit(Ts.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 Zi(this,void 0,void 0,(function*(){var e;if(!this.url||!this.token)throw new Cs("could not reconnect, url or token not saved");if(!this.pcManager)throw new Cs("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Ts.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 Es&&t.reason===gs.NotAllowed)throw new Cs("could not reconnect, token might be expired");if(t instanceof Es&&t.reason===gs.LeaveRequest)throw t;throw new Ps(e)}if(this.emit(Ts.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,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==fo.CONNECTED)throw new Ps("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(Ts.Resumed)}))}waitForPCInitialConnection(t,e){return Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Cs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(e,t)}))}waitForPCReconnected(){return Zi(this,void 0,void 0,(function*(){this.pcState=Ta.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ar(2e3),!this.pcManager)throw new Cs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ta.Connected}catch(t){throw this.pcState=Ta.Disconnected,Es.internal("could not establish PC connection, ".concat(t.message))}}))}publishRpcResponse(t,e,i,n){return Zi(this,void 0,void 0,(function*(){const s=new ae({destinationIdentities:[t],kind:ce.RELIABLE,value:{case:"rpcResponse",value:new we({requestId:e,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,ce.RELIABLE)}))}publishRpcAck(t,e){return Zi(this,void 0,void 0,(function*(){const i=new ae({destinationIdentities:[t],kind:ce.RELIABLE,value:{case:"rpcAck",value:new ye({requestId:e})}});yield this.sendDataPacket(i,ce.RELIABLE)}))}sendDataPacket(t,e){return Zi(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 de({value:t.value})}(t);if(e){const i=yield this.e2eeManager.encryptData(e.toBinary());t.value={case:"encryptedPacket",value:new he({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}e===ce.RELIABLE&&(t.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=t.toBinary(),n=this.dataChannelForKind(e);if(n){if(e===ce.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 Zi(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(ce.RELIABLE);const e=this.dataChannelForKind(ce.RELIABLE);e&&(this.reliableMessageBuffer.popToSequence(t),this.reliableMessageBuffer.getAll().forEach((t=>{e.send(t.data)}))),this.updateAndEmitDCBufferStatus(ce.RELIABLE)}))}waitForBufferStatusLow(t){return new hs(((e,i)=>Zi(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(t))e();else{const n=()=>i(new Cs("engine closed"));for(this.once(Ts.Closing,n);!this.dcBufferStatus.get(t);)yield ar(10);this.off(Ts.Closing,n),e()}}))))}ensureDataTransportConnected(t){return Zi(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 Cs("PC manager is closed");const s=i?e.pcManager.subscriber:e.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw Es.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=>{Qi.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 ar(50)}throw Es.internal("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))}()}))}ensurePublisherConnected(t){return Zi(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(t,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===Wo.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Zi(this,void 0,void 0,(function*(){return new hs(((t,e)=>Zi(this,void 0,void 0,(function*(){if(!this.pcManager)return void e(new _s("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 _s("cannot negotiate on closed engine")),this.on(Ts.Closing,n),this.pcManager.publisher.once(Do,(t=>{const e=new Map;t.forEach((t=>{const i=t.codec.toLowerCase();Us.includes(i)&&e.set(t.payload,i)})),this.emit(Ts.RTPVideoMapUpdate,e)}));try{yield this.pcManager.negotiate(i),t()}catch(t){t instanceof _s&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Gt.RR_UNKNOWN),t instanceof Error?e(t):e(new Error(String(t)))}finally{this.off(Ts.Closing,n)}}))))}))}dataChannelForKind(t,e){if(e){if(t===ce.LOSSY)return this.lossyDCSub;if(t===ce.RELIABLE)return this.reliableDCSub}else{if(t===ce.LOSSY)return this.lossyDC;if(t===ce.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(),h=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getLocalDescription(),d=null===(r=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===r||r,l=new Array,u=new Array;t.forEach((t=>{t.isDesired!==d&&l.push(t.trackSid),t.isEnabled||u.push(t.trackSid)})),this.client.sendSyncState(new Ti({answer:"publisher-only"===this.pcManager.mode?a?po({sdp:a.sdp,type:a.type}):void 0:h?po({sdp:h.sdp,type:h.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?po({sdp:o.sdp,type:o.type}):void 0:c?po({sdp:c.sdp,type:c.type}):void 0,subscription:new Xe({trackSids:l,subscribe:!d,participantTracks:[]}),publishTracks:$s(e),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:u,datachannelReceiveStates:this.reliableReceivedState.map(((t,e)=>new Si({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 Ei({label:e.label,id:e.id,target:i}))};return e(this.dataChannelForKind(ce.LOSSY),Le.PUBLISHER),e(this.dataChannelForKind(ce.RELIABLE),Le.PUBLISHER),e(this.dataChannelForKind(ce.LOSSY,!0),Le.SUBSCRIBER),e(this.dataChannelForKind(ce.RELIABLE,!0),Le.SUBSCRIBER),t}clearReconnectTimeout(){this.reconnectTimeout&&Ds.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){gr()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){gr()&&(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 xa(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 Ca{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 js("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),bs.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new js("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),bs.LengthExceeded)}}constructor(t,e,i,n){this.reader=e,this.totalByteSize=i,this._info=t,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class _a extends Ca{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 Dr,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:()=>Zi(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 Zi(this,void 0,void 0,(function*(){return s(),{done:!0,value:void 0}}))}}}withAbortSignal(t){return this.signal=t,this}readAll(){return Zi(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,h=Xi(o);!(i=(a=yield h.next()).done);c=!0)c=!1,r.add(a.value)}catch(t){n={error:t}}finally{try{c||i||!(s=h.return)||(yield s.call(h))}finally{if(n)throw n.error}}return Array.from(r)}()}))}}class Ra extends Ca{constructor(t,e,i,n){super(t,e,i,n),this.receivedChunks=new Map}handleChunkReceived(t){var e;const i=Lr(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 Dr,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:()=>Zi(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 js("Cannot decode datastream chunk ".concat(o.chunkIndex," as text: ").concat(t),bs.DecodeFailed)}return{done:!1,value:t}}}catch(t){throw r(),t}})),return(){return Zi(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(t){return this.signal=t,this}readAll(){return Zi(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,h=Xi(o);!(i=(a=yield h.next()).done);c=!0)c=!1,r+=a.value}catch(t){n={error:t}}finally{try{c||i||!(s=h.return)||(yield s.call(h))}finally{if(n)throw n.error}}return r}()}))}}class Ia{constructor(){this.log=Qi,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 js('A text stream handler for topic "'.concat(t,'" has already been set.'),bs.HandlerAlreadyRegistered);this.textStreamHandlers.set(t,e)}unregisterTextStreamHandler(t){this.textStreamHandlers.delete(t)}registerByteStreamHandler(t,e){if(this.byteStreamHandlers.has(t))throw new js('A byte stream handler for topic "'.concat(t,'" has already been set.'),bs.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 js("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),bs.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 Zi(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 new Error('DataPacket of value "'.concat(t.value.case,'" is not data stream related!'))}}))}handleStreamHeader(t,e,i){return Zi(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 Dr;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:Lr(t.timestamp),attributes:t.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(t.streamId))throw new js("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),bs.AlreadyOpened);this.byteStreamControllers.set(t.streamId,{info:a,controller:r,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:o})}});s(new _a(a,c,Lr(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 Dr;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 js("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),bs.AlreadyOpened);this.textStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:r})}});n(new Ra(o,a,Lr(t.totalLength),r),{identity:e})}}))}handleStreamChunk(t,e){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==e?(i.controller.error(new js("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(i.info.encryptionType),bs.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 js("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(n.info.encryptionType),bs.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 js("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(i.info.encryptionType),bs.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 js("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(n.info.encryptionType),bs.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 Zi(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 Pa extends ja{}class Da extends ja{}class Ma{constructor(t,e){this.engine=t,this.log=e}setupEngine(t){this.engine=t}sendText(t,e){return Zi(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=new 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)=>Zi(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 Zi(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)?ie.GCM:ie.NONE},o=new De({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:Br(r.timestamp),totalLength:Br(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)?Ie.UPDATE:Ie.CREATE})}}),a=null==t?void 0:t.destinationIdentities,c=new ae({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,ce.RELIABLE);let h=0;const d=this.engine,l=new WritableStream({write(t){return Zi(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 Me({content:e,streamId:s,chunkIndex:Br(h)}),i=new ae({destinationIdentities:a,value:{case:"streamChunk",value:t}});yield d.sendDataPacket(i,ce.RELIABLE),h+=1}}))},close(){return Zi(this,void 0,void 0,(function*(){const t=new Ne({streamId:s}),e=new ae({destinationIdentities:a,value:{case:"streamTrailer",value:t}});yield d.sendDataPacket(e,ce.RELIABLE)}))},abort(t){console.log("Sink error:",t)}});let u=()=>Zi(this,void 0,void 0,(function*(){yield f.close()}));d.once(Ts.Closing,u);const f=new Pa(l,r,(()=>this.engine.off(Ts.Closing,u)));return f}))}sendFile(t,e){return Zi(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,t,e),{id:i}}))}_sendFile(t,e,i){return Zi(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 Zi(this,void 0,void 0,(function*(){var e,i,n,s,r,o;const c=null!==(e=null==t?void 0:t.streamId)&&void 0!==e?e:crypto.randomUUID(),h=null==t?void 0:t.destinationIdentities,d={id:c,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)?ie.GCM:ie.NONE},l=new De({totalLength:Br(null!==(o=d.size)&&void 0!==o?o:0),mimeType:d.mimeType,streamId:c,topic:d.topic,timestamp:Br(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Pe({name:d.name})}}),u=new ae({destinationIdentities:h,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,ce.RELIABLE);let f=0;const v=new a,m=this.engine,p=this.log,g=new WritableStream({write(t){return Zi(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 ae({destinationIdentities:h,value:{case:"streamChunk",value:new Me({content:e,streamId:c,chunkIndex:Br(f)})}});yield m.sendDataPacket(n,ce.RELIABLE),f+=1,i+=e.byteLength}}finally{e()}}))},close(){return Zi(this,void 0,void 0,(function*(){const t=new Ne({streamId:c}),e=new ae({destinationIdentities:h,value:{case:"streamTrailer",value:t}});yield m.sendDataPacket(e,ce.RELIABLE)}))},abort(t){p.error("Sink error:",t)}});return new Da(g,d)}))}}class Na extends nr{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?Ss.Muted:Ss.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(Ss.Ended,this))};t.addEventListener("removetrack",e)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Zi(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()),$o)),"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(Ss.TimeSyncUpdate,{timestamp:t,rtpTimestamp:e}),this.rtpTimestamp=e)}};t()}}class Ua extends Na{constructor(t,e,i,n,s,r){super(t,e,nr.Kind.Audio,i,r),this.monitorReceiver=()=>Zi(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=Zo(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;br()&&this._mediaStreamTrack._setVolume(t),this.elementVolume=t}getVolume(){if(this.elementVolume)return this.elementVolume;if(br())return 1;let t=0;return this.attachedElements.forEach((e=>{e.volume>t&&(t=e.volume)})),t}setSinkId(t){return Zi(this,void 0,void 0,(function*(){this.sinkId=t,yield Promise.all(this.attachedElements.map((e=>{if(lr(e))return e.setSinkId(t)})))}))}attach(t){const e=0===this.attachedElements.length;return t?super.attach(t):t=super.attach(),this.sinkId&&lr(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(Ss.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(Ss.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 Zi(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 La extends Na{constructor(t,e,i,n,s){super(t,e,nr.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Zi(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=Zo(t,this.prevStats)),this.prevStats=t})),this.debouncedHandleResize=Io((()=>{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===nr.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(t){super.setMuted(t),this.attachedElements.forEach((e=>{t?rr(this._mediaStreamTrack,e):sr(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 Ba(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 Zi(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 Zi(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?Ds.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(Ss.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(Ss.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var t;const e=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pixelDensity;return"screen"===e?Sr():e||(Sr()>2?2:1)}}class Ba{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=Fa(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=Fa(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var t;this.isPiP=Fa(this.element),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this)},this.element=t,this.isIntersecting=null!=e?e:qa(t),this.isPiP=gr()&&Fa(t),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var t,e,i;this.isIntersecting=qa(this.element),this.isPiP=Fa(this.element),this.element.handleResize=()=>{var t;null===(t=this.handleResize)||void 0===t||t.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Rr().observe(this.element),Cr().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=Rr())||void 0===t||t.unobserve(this.element),null===(e=Cr())||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 Fa(t){var e,i;return document.pictureInPictureElement===t||!!(null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)&&qa(t,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function qa(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 Va extends nn.EventEmitter{constructor(t,e,i,n){var s;super(),this.metadataMuted=!1,this.encryption=ie.NONE,this.log=Qi,this.handleMuted=()=>{this.emit(Ss.Muted)},this.handleUnmuted=()=>{this.emit(Ss.Unmuted)},this.log=Hi(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:Ji.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=e,this.trackName=i,this.source=nr.Source.Unknown}setTrack(t){this.track&&(this.track.off(Ss.Muted,this.handleMuted),this.track.off(Ss.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(Ss.Muted,this.handleMuted),t.on(Ss.Unmuted,this.handleUnmuted))}get logContext(){var t;return Object.assign(Object.assign({},null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this)),Zs(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ie.NONE}get audioTrack(){if(qr(this.track))return this.track}get videoTrack(){if(Vr(this.track))return this.track}updateInfo(t){this.trackSid=t.sid,this.trackName=t.name,this.source=nr.sourceFromProto(t.source),this.mimeType=t.mimeType,this.kind===nr.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){var e,i;(e=t.SubscriptionStatus||(t.SubscriptionStatus={})).Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",(i=t.PermissionStatus||(t.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(Va||(Va={}));class za extends Va{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(Ss.Ended)},this.handleCpuConstrained=()=>{this.track&&Vr(this.track)&&this.emit(Ss.CpuConstrained,this.track)},this.updateInfo(e),this.setTrack(i)}setTrack(t){this.track&&(this.track.off(Ss.Ended,this.handleTrackEnded),this.track.off(Ss.CpuConstrained,this.handleCpuConstrained)),super.setTrack(t),t&&(t.on(Ss.Ended,this.handleTrackEnded),t.on(Ss.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 Zi(this,void 0,void 0,(function*(){var t;return null===(t=this.track)||void 0===t?void 0:t.mute()}))}unmute(){return Zi(this,void 0,void 0,(function*(){var t;return null===(t=this.track)||void 0===t?void 0:t.unmute()}))}pauseUpstream(){return Zi(this,void 0,void 0,(function*(){var t;yield null===(t=this.track)||void 0===t?void 0:t.pauseUpstream()}))}resumeUpstream(){return Zi(this,void 0,void 0,(function*(){var t;yield null===(t=this.track)||void 0===t?void 0:t.resumeUpstream()}))}getTrackFeatures(){var t;if(qr(this.track)){const e=this.track.getSourceTrackSettings(),i=new Set;return e.autoGainControl&&i.add(Ht.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&i.add(Ht.TF_ECHO_CANCELLATION),e.noiseSuppression&&i.add(Ht.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&i.add(Ht.TF_STEREO),(null===(t=this.options)||void 0===t?void 0:t.dtx)||i.add(Ht.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Ht.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function Ja(t,e){return Zi(this,void 0,void 0,(function*(){null!=t||(t={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Xs(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=Gs(Js(r,qo,Vo)),h=navigator.mediaDevices.getUserMedia(c);r.audio&&(ao.userMediaPromiseMap.set("audioinput",h),h.catch((()=>ao.userMediaPromiseMap.delete("audioinput")))),r.video&&(ao.userMediaPromiseMap.set("videoinput",h),h.catch((()=>ao.userMediaPromiseMap.delete("videoinput"))));try{const t=yield h;return yield Promise.all(t.getTracks().map((i=>Zi(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)&&Mr(r.deviceId)!==a?r.deviceId=a:r||(r={deviceId:a});const h=function(t,e,i){switch(t.kind){case"audio":return new na(t,e,!1,void 0,i);case"video":return new ma(t,e,!1,i);default:throw new As("unsupported track type: ".concat(t.kind))}}(i,r,e);return h.kind===nr.Kind.Video?h.source=nr.Source.Camera:h.kind===nr.Kind.Audio&&(h.source=nr.Source.Microphone),h.mediaStream=t,qr(h)&&n?yield h.setProcessor(n):Vr(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(n){if(!i)throw n;return Ja(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"}(Sa||(Sa={}));class Wa extends nn.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===te.AGENT}get isActive(){var t;return(null===(t=this.participantInfo)||void 0===t?void 0:t.state)===Xt.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]:te.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Sa.Unknown,this.log=Qi,this.log=Hi(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:Ji.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 Dr,this.once(ks.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(nr.Source.Camera);return!(null===(t=null==e?void 0:e.isMuted)||void 0===t||t)}get isMicrophoneEnabled(){var t;const e=this.getTrackPublication(nr.Source.Microphone);return!(null===(t=null==e?void 0:e.isMuted)||void 0===t||t)}get isScreenShareEnabled(){return!!this.getTrackPublication(nr.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):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===Xt.ACTIVE&&(null===(e=this.participantInfo)||void 0===e?void 0:e.state)!==Xt.ACTIVE&&this.emit(ks.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(ks.ParticipantMetadataChanged,i)}_setName(t){const e=this.name!==t;this.name=t,e&&this.emit(ks.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(ks.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(ks.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(ks.IsSpeakingChanged,t))}setConnectionQuality(t){const e=this._connectionQuality;this._connectionQuality=function(t){switch(t){case zt.EXCELLENT:return Sa.Excellent;case zt.GOOD:return Sa.Good;case zt.POOR:return Sa.Poor;case zt.LOST:return Sa.Lost;default:return Sa.Unknown}}(t),e!==this._connectionQuality&&this.emit(ks.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var t,e;this.activeFuture&&(null===(e=(t=this.activeFuture).reject)||void 0===e||e.call(t,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(t){this.audioContext=t,this.audioTrackPublications.forEach((e=>qr(e.track)&&e.track.setAudioContext(t)))}addTrackPublication(t){switch(t.on(Ss.Muted,(()=>{this.emit(ks.TrackMuted,t)})),t.on(Ss.Unmuted,(()=>{this.emit(ks.TrackUnmuted,t)})),t.track&&(t.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case nr.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case nr.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class Ga extends Wa{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=ie.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Dr)},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,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(r=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,new 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 Dr),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 Is(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=Ho.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 new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new bi({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),Zs(t)))},this.onTrackUpstreamPaused=t=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Zs(t))),this.onTrackMuted(t,!0)},this.onTrackUpstreamResumed=t=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Zs(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),Zs(e))),this.emit(ks.LocalTrackCpuConstrained,t,e)},this.handleSubscribedQualityUpdate=t=>Zi(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,h=Xi(o);!(e=(a=yield h.next()).done);c=!0){c=!1;const t=a.value;Ls(t)&&(this.log.debug("publish ".concat(t," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Zs(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,t,r.options))}}catch(t){i={error:t}}finally{try{c||e||!(n=h.return)||(yield n.call(h))}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=>Zi(this,void 0,void 0,(function*(){if(t.source===nr.Source.ScreenShare||t.source===nr.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Zs(t))),this.unpublishTrack(t);else if(t.isUserProvided)yield t.mute();else if(Jr(t)||zr(t))try{if(gr())try{const e=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:t.source===nr.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),Zs(t))),e.onchange=()=>{"denied"!==e.state&&(t.isMuted||t.restartTrack(),e.onchange=null)},new 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),Zs(t))),Jr(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),Zs(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!==ie.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(Ts.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(Ts.Connected,this.handleReconnected).on(Ts.SignalConnected,this.handleSignalConnected).on(Ts.SignalRestarted,this.handleReconnected).on(Ts.SignalResumed,this.handleReconnected).on(Ts.Restarting,this.handleReconnecting).on(Ts.Resuming,this.handleReconnecting).on(Ts.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Ts.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Ts.Closing,this.handleClosing).on(Ts.SignalRequestResponse,this.handleSignalRequestResponse).on(Ts.DataPacketReceived,this.handleDataPacket)}setMetadata(t){return Zi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:t})}))}setName(t){return Zi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:t})}))}setAttributes(t){return Zi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:t})}))}requestMetadataUpdate(t){return Zi(this,arguments,void 0,(function(t){var e=this;let{metadata:i,name:n,attributes:s}=t;return function*(){return new hs(((t,r)=>Zi(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),h=performance.now();for(this.pendingSignalRequests.set(c,{resolve:t,reject:t=>{r(t),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-h<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 ar(50)}r(new Is("Request to update local metadata timed out","TimeoutError"))}catch(t){t instanceof Error?r(t):r(new Error(String(t)))}}))))}()}))}setCameraEnabled(t,e,i){return this.setTrackEnabled(nr.Source.Camera,t,e,i)}setMicrophoneEnabled(t,e,i){return this.setTrackEnabled(nr.Source.Microphone,t,e,i)}setScreenShareEnabled(t,e,i){return this.setTrackEnabled(nr.Source.ScreenShare,t,e,i)}setE2EEEnabled(t){return Zi(this,void 0,void 0,(function*(){this.encryptionType=t?ie.GCM:ie.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,e,i,n){return Zi(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 nr.Source.Camera:e=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case nr.Source.Microphone:e=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case nr.Source.ScreenShare:e=yield this.createScreenTracks(Object.assign({},i));break;default:throw new As(t)}}catch(i){throw null==e||e.forEach((t=>{t.stop()})),i instanceof Error&&this.emit(ks.MediaDevicesError,i,Ks(t)),this.pendingPublishing.delete(t),i}for(const n of e){const e=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);t===nr.Source.Microphone&&qr(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),Zs(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===nr.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const t=this.getTrackPublication(nr.Source.ScreenShareAudio);t&&t.track&&this.unpublishTrack(t.track)}else yield o.mute();return o}))}enableCameraAndMicrophone(){return Zi(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(nr.Source.Camera)&&!this.pendingPublishing.has(nr.Source.Microphone)){this.pendingPublishing.add(nr.Source.Camera),this.pendingPublishing.add(nr.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(nr.Source.Camera),this.pendingPublishing.delete(nr.Source.Microphone)}}}))}createTracks(t){return Zi(this,void 0,void 0,(function*(){var e,i;null!=t||(t={});const n=Js(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 Ja(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((t=>(qr(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=nr.Source.Microphone,this.emit(ks.AudioStreamAcquired)),Vr(t)&&(this.cameraError=void 0,t.source=nr.Source.Camera),t)))}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}}))}createScreenTracks(t){return Zi(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Os("getDisplayMedia not supported");void 0!==t.resolution||function(){const t=us();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)&&Er(t.osVersion,"17")>=0}()||(t.resolution=zs.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=vr()?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 As("no video track found");const s=new ma(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=nr.Source.ScreenShare,t.contentHint&&(s.mediaStreamTrack.contentHint=t.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(ks.AudioStreamAcquired);const t=new na(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=nr.Source.ScreenShareAudio,r.push(t)}return r}))}publishTrack(t,e){return Zi(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(t,e)}))}publishOrRepublishTrack(t,e){return Zi(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,h;if(Jr(t)&&t.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),Fr(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 nr.Source.Microphone:e="audioinput";break;case nr.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 na(t,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":t=new ma(t,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new As("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&&(h=e)})),h)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),Zs(h))),h;const d=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=d.forceStereo)&&void 0!==r?r:l;u&&(void 0===d.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),Zs(t))),void 0===d.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=d.dtx)&&void 0!==o||(d.dtx=!1),null!==(a=d.red)&&void 0!==a||(d.red=!1)),!function(){const t=us(),e="17.2";if(t)return"Safari"!==t.name&&"iOS"!==t.os||!!("iOS"===t.os&&t.osVersion&&Er(t.osVersion,e)>=0)||"Safari"===t.name&&Er(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)),d.simulcast=!1),d.source&&(t.source=d.source);const f=new Promise(((e,n)=>Zi(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==fo.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Zs(t)}));let i=!1;const s=setTimeout((()=>{i=!0,t.stop(),n(new Rs("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(s),i)return;const r=yield this.publish(t,d,u);e(r)}else try{const i=yield this.publish(t,d,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 Dr),this.signalConnectedFuture.promise}hasPermissionsToPublish(t){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Zs(t))),!1;const{canPublish:e,canPublishSources:i}=this.permissions;return!(!e||0!==i.length&&!i.map((t=>function(t){switch(t){case qt.CAMERA:return nr.Source.Camera;case qt.MICROPHONE:return nr.Source.Microphone;case qt.SCREEN_SHARE:return nr.Source.ScreenShare;case qt.SCREEN_SHARE_AUDIO:return nr.Source.ScreenShareAudio;default:return nr.Source.Unknown}}(t))).includes(t.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Zs(t))),!1)}publish(t,e,i){return Zi(this,void 0,void 0,(function*(){var n,s,r,o,a,c,h,d,l,u;if(!this.hasPermissionsToPublish(t))throw new Rs("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>Fr(t)&&e.source===t.source))&&t.source!==nr.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),Zs(t))),e.stopMicTrackOnMute&&qr(t)&&(t.stopOnMute=!0),t.source===nr.Source.ScreenShare&&ur()&&(e.simulcast=!1),"av1"!==e.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(vr()||ur())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(ur())return!1;if(vr()){const t=us();if((null==t?void 0:t.version)&&Er(t.version,"16")<0)return!1;if("iOS"===(null==t?void 0:t.os)&&(null==t?void 0:t.osVersion)&&Er(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=Bo),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((t=>e.videoCodec===Ys(t.mime)))||(e.videoCodec=Ys(this.enabledPublishVideoCodecs[0].mime)));const f=e.videoCodec;t.on(Ss.Muted,this.onTrackMuted),t.on(Ss.Unmuted,this.onTrackUnmuted),t.on(Ss.Ended,this.handleTrackEnded),t.on(Ss.UpstreamPaused,this.onTrackUpstreamPaused),t.on(Ss.UpstreamResumed,this.onTrackUpstreamResumed),t.on(Ss.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],m=!(null===(n=e.dtx)||void 0===n||n),p=t.getSourceTrackSettings();p.autoGainControl&&v.push(Ht.TF_AUTO_GAIN_CONTROL),p.echoCancellation&&v.push(Ht.TF_ECHO_CANCELLATION),p.noiseSuppression&&v.push(Ht.TF_NOISE_SUPPRESSION),p.channelCount&&p.channelCount>1&&v.push(Ht.TF_STEREO),m&&v.push(Ht.TF_NO_DTX),Jr(t)&&t.hasPreConnectBuffer&&v.push(Ht.TF_PRECONNECT_BUFFER);const g=new Je({cid:t.mediaStreamTrack.id,name:e.name,type:nr.kindToProto(t.kind),muted:t.isMuted,source:nr.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===nr.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:qs.h720.resolution;i={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Zs(t)),{dims:i}))}g.width=i.width,g.height=i.height,zr(t)&&(dr(f)&&(t.source===nr.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),Zs(t))))),e.scalabilityMode=null!==(a=e.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),g.simulcastCodecs=[new ze({codec:f,cid:t.mediaStreamTrack.id})],!0===e.backupCodec&&(e.backupCodec={codec:Bo}),e.backupCodec&&f!==e.backupCodec.codec&&g.encryption===ie.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new ze({codec:e.backupCodec.codec,cid:""})))),b=da(t.source===nr.Source.ScreenShare,g.width,g.height,e),g.layers=ba(g.width,g.height,b,dr(e.videoCodec))}else t.kind===nr.Kind.Audio&&(b=[{maxBitrate:null===(c=e.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(d=null===(h=e.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==d?d:"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 Cs("cannot publish track when not connected");const y=()=>Zi(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new Cs("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,e,b),this.emit(ks.LocalSenderCreated,t.sender,t),zr(t)&&(null!==(i=e.degradationPreference)&&void 0!==i||(e.degradationPreference=function(t){return t.source===nr.Source.ScreenShare||t.constraints.height&&Mr(t.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(e.degradationPreference)),b)if(ur()&&t.kind===nr.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&&dr(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)=>Zi(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),Zs(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===nr.Kind.Video){const n=Ys(i);n!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Zs(t)),{codec:n})),e.videoCodec=n,b=da(t.source===nr.Source.ScreenShare,g.width,g.height,e))}yield y()}const T=new za(t.kind,w,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(T.on(Ss.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})),zr(t)?t.startMonitor(this.engine.client):Jr(t)&&t.startMonitor(),this.addTrackPublication(T),this.emit(ks.LocalTrackPublished,T),Jr(t)&&w.audioFeatures.includes(Ht.TF_PRECONNECT_BUFFER)){const e=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(ks.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),Zs(t))),t.stopPreConnectBuffer()}})),e){const n=new Promise(((n,s)=>Zi(this,void 0,void 0,(function*(){var r,o,a,c,h;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Zs(t)));const f=setTimeout((()=>{s(new 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),Zs(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:String(null!==(c=p.sampleRate)&&void 0!==c?c:"48000"),channels:String(null!==(h=p.channelCount)&&void 0!==h?h:"1")}});try{for(var d,l=!0,u=Xi(e);!(r=(d=yield u.next()).done);l=!0){l=!1;const t=d.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),Zs(t)))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Zs(t)),{error:e}))}))}}return T}))}get isLocal(){return!0}publishAdditionalCodecForTrack(t,e,i){return Zi(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==ie.NONE)return;let s;if(this.trackPublications.forEach((e=>{e.track&&e.track===t&&(s=e)})),!s)throw new As("track is not published");if(!zr(t))throw new As("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&&Qi.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,h=null!==(r=a.height)&&void 0!==r?r:null===(o=t.dimensions)||void 0===o?void 0:o.height;return t.source===nr.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),da(t.source===nr.Source.ScreenShare,c,h,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),Zs(t)));const a=t.addSimulcastTrack(e,o);if(!a)return;const c=new Je({cid:a.mediaStreamTrack.id,type:nr.kindToProto(t.kind),muted:t.isMuted,source:nr.sourceToProto(t.source),sid:t.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=ba(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Cs("cannot publish track when not connected");const h=(yield Promise.all([this.engine.addTrack(c),(()=>Zi(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:h}))}))}unpublishTrack(t,e){return Zi(this,void 0,void 0,(function*(){var i,n;if(Fr(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Zs(t))),yield e)}const s=this.getPublicationForTrack(t),r=s?Zs(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(Ss.Muted,this.onTrackMuted),t.off(Ss.Unmuted,this.onTrackUnmuted),t.off(Ss.Ended,this.handleTrackEnded),t.off(Ss.UpstreamPaused,this.onTrackUpstreamPaused),t.off(Ss.UpstreamResumed,this.onTrackUpstreamResumed),t.off(Ss.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<Wo.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),zr(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 nr.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case nr.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(ks.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(t){return Zi(this,void 0,void 0,(function*(){return(yield Promise.all(t.map((t=>this.unpublishTrack(t))))).filter((t=>!!t))}))}republishAllTracks(t){return Zi(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 hs(((n,s)=>Zi(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=>Zi(this,void 0,void 0,(function*(){const e=t.track;yield this.unpublishTrack(e,!1),!i||e.isMuted||e.source===nr.Source.ScreenShare||e.source===nr.Source.ScreenShareAudio||!Jr(e)&&!zr(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){t instanceof Error?s(t):s(new Error(String(t)))}finally{this.republishPromise=void 0}})))),yield e.republishPromise}()}))}publishData(t){return Zi(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?ce.RELIABLE:ce.LOSSY;let s=new fe({participantIdentity:e.identity,payload:t,destinationIdentities:i.destinationIdentities,topic:i.topic});const r=new ae({kind:n,value:{case:"user",value:s}});yield e.engine.sendDataPacket(r,n)}()}))}publishDtmf(t,e){return Zi(this,void 0,void 0,(function*(){const i=new ae({kind:ce.RELIABLE,value:{case:"sipDtmf",value:new ve({code:t,digit:e})}});yield this.engine.sendDataPacket(i,ce.RELIABLE)}))}sendChatMessage(t,e){return Zi(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 ae({value:{case:"chatMessage",value:new ge(Object.assign(Object.assign({},i),{timestamp:x.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,ce.RELIABLE),this.emit(ks.ChatMessage,i),i}))}editChatMessage(t,e){return Zi(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},e),{message:t,editTimestamp:Date.now()}),n=new ae({value:{case:"chatMessage",value:new ge(Object.assign(Object.assign({},i),{timestamp:x.parse(i.timestamp),editTimestamp:x.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,ce.RELIABLE),this.emit(ks.ChatMessage,i),i}))}sendText(t,e){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(t,e)}))}streamText(t){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(t)}))}sendFile(t,e){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(t,e)}))}streamBytes(t){return Zi(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 hs(((t,r)=>Zi(this,void 0,void 0,(function*(){var o,a,c,h;if(Ko(n)>15360)return void r(Ho.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)&&Er(null===(h=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===h?void 0:h.version,"1.8.0")<0)return void r(Ho.builtIn("UNSUPPORTED_SERVER"));const d=Math.max(s,8e3),l=crypto.randomUUID();yield this.publishRpcRequest(e,l,i,n,d);const u=setTimeout((()=>{this.pendingAcks.delete(l),r(Ho.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(Ho.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 Zi(this,void 0,void 0,(function*(){const r=new ae({destinationIdentities:[t],kind:ce.RELIABLE,value:{case:"rpcRequest",value:new be({id:e,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,ce.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,Ho.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),Zs(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,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Dr),this.activeAgentFuture.promise)}getPublicationForTrack(t){let e;return this.trackPublications.forEach((i=>{const n=i.track;n&&(t instanceof MediaStreamTrack?(Jr(n)||zr(n))&&n.mediaStreamTrack===t&&(e=i):t===n&&(e=i))})),e}waitForPendingPublicationOfSource(t){return Zi(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 ar(20)}}))}}class Qa extends Va{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(Ss.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 Xe({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Te({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Ss.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(e),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Va.SubscriptionStatus.Unsubscribed:super.isSubscribed?Va.SubscriptionStatus.Subscribed:Va.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Va.PermissionStatus.Allowed:Va.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||(Qr(this.track)&&(this.requestedVideoDimensions=t),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(t){this.isManualOperationAllowed()&&Qr(this.track)&&this.fps!==t&&(this.fps=t,this.emitTrackUpdate())}get videoQuality(){var t;return null!==(t=this.requestedMaxQuality)&&void 0!==t?t:ir.HIGH}setTrack(t){const e=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==t&&(n&&(n.off(Ss.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Ss.VisibilityChanged,this.handleVisibilityChange),n.off(Ss.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Ss.Unsubscribed,n)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(Ss.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(Ss.VisibilityChanged,this.handleVisibilityChange),t.on(Ss.Ended,this.handleEnded),this.emit(Ss.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(Ss.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?Ss.Muted:Ss.Unmuted)}emitSubscriptionUpdateIfChanged(t){const e=this.subscriptionStatus;t!==e&&this.emit(Ss.SubscriptionStatusChanged,e,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(Ss.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Qr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new ti({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===nr.Kind.Video){let n=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(n)tr(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const t=(e=this.requestedMaxQuality,null===(i=this.trackInfo.layers)||void 0===i?void 0:i.find((t=>t.quality===e)));t&&tr(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(t.width=Math.ceil(n.width),t.height=Math.ceil(n.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:ir.HIGH})),t.quality=ir.HIGH)}var e,i;this.emit(Ss.UpdateSettings,t)}}class Ha extends Wa{static fromParticipantInfo(t,e,i){return new Ha(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]:te.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(Ss.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Zs(t)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)})),t.on(Ss.UpdateSubscription,(t=>{t.participantTracks.forEach((t=>{t.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(t)})),t.on(Ss.SubscriptionPermissionChanged,(e=>{this.emit(ks.TrackSubscriptionPermissionChanged,t,e)})),t.on(Ss.SubscriptionStatusChanged,(e=>{this.emit(ks.TrackSubscriptionStatusChanged,t,e)})),t.on(Ss.Subscribed,(e=>{this.emit(ks.TrackSubscribed,e,t)})),t.on(Ss.Unsubscribed,(e=>{this.emit(ks.TrackUnsubscribed,e,t)})),t.on(Ss.SubscriptionFailed,(e=>{this.emit(ks.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]:nr.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]:nr.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.toString()||(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),Zs(a))),void this.emit(ks.TrackSubscriptionFailed,e)):(o="video"===t.kind?new La(t,e,n,s):new Ua(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)&&Wr(o)&&qr(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(ks.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=nr.kindFromProto(t.type);if(!e)return;r=new Qa(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!==nr.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:Zs(o),newTrack:Zs(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),Zs(t))),this.unpublishTrack(t.trackSid,!0))})),i.forEach((t=>{this.emit(ks.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 nr.Kind.Audio:this.audioTrackPublications.delete(t);break;case nr.Kind.Video:this.videoTrackPublications.delete(t)}e&&this.emit(ks.TrackUnpublished,i)}setAudioOutput(t){return Zi(this,void 0,void 0,(function*(){this.audioOutput=t;const e=[];this.audioTrackPublications.forEach((i=>{var n;qr(i.track)&&Wr(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=new 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"}(Ea||(Ea={}));class Ka extends nn.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(t){var e,i,n,s,r;if(super(),e=this,this.state=Ea.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Qi,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(t,e,i)=>Zi(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!cr()&&!hr())throw br()?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===Ea.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(Ea.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==Hr(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),yr(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Qo(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)=>Zi(this,void 0,void 0,(function*(){var c,h;this.abortController&&this.abortController.abort();const d=new AbortController;this.abortController=d,null==s||s();try{if(yield ro.getInstance().getBackOffPromise(t),d.signal.aborted)throw Es.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=a?a:t,e,i,d),this.abortController=void 0,n()}catch(e){if(this.regionUrlProvider&&e instanceof Es&&e.reason!==gs.Cancelled&&e.reason!==gs.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 Es&&(401===t.status||t.reason===gs.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(t)}[gs.InternalError,gs.ServerUnreachable,gs.Timeout].includes(e.reason)&&(this.log.debug("Adding failed connection attempt to back off"),ro.getInstance().addFailedConnectionAttempt(t)),i&&!(null===(h=this.abortController)||void 0===h?void 0:h.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,Ur(e)),o(e))}else{let t=Wt.UNKNOWN_REASON;e instanceof Es&&(t=Ur(e)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),o(e)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Dr(((t,e)=>{r(t,e,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(t,e,i,n,s,r)=>Zi(this,void 0,void 0,(function*(){var o,a,c;const h=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 d=h.serverInfo;if(d||(d={version:h.serverVersion,region:h.serverRegion}),this.serverInfo=d,this.log.debug("connected to Livekit Server ".concat(Object.entries(d).map((t=>{let[e,i]=t;return"".concat(e,": ").concat(i)})).join(", ")),{room:null===(o=h.room)||void 0===o?void 0:o.name,roomSid:null===(a=h.room)||void 0===a?void 0:a.sid,identity:null===(c=h.participant)||void 0===c?void 0:c.identity}),!d.version)throw new xs("unknown server version");return"0.15.1"===d.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),h})),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)=>Zi(this,void 0,void 0,(function*(){var s,r;this.state===Ea.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({},Jo),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(ws.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();const e=n.signal.aborted?Es.cancelled("Signal connection aborted"):Es.serverUnreachable("could not establish signal connection");throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof Es&&(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(),Es.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(t){throw yield this.engine.close(),this.recreateEngine(),t}gr()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),gr()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Ea.Connected),this.emit(ws.Connected),ro.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return Zi(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===Ea.Disconnected)return void t.log.debug("already disconnected",t.logContext);if(t.log.info("disconnect from room",Object.assign({},t.logContext)),t.state===Ea.Connecting||t.state===Ea.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,Es.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,Wt.CLIENT_INITIATED),t.engine=void 0}finally{r()}}()}))},this.onPageLeave=()=>Zi(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Zi(this,void 0,void 0,(function*(){const t=[],e=us();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=Pr();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(ws.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=()=>Zi(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(Ea.Reconnecting)&&this.emit(ws.Reconnecting)},this.handleSignalRestarted=t=>Zi(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(Ea.Connected),this.emit(ws.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===Xt.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(ws.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(ws.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=nr.streamStateFromProto(t.state);i.track.setStreamState(n),n!==i.track.streamState&&(e.emit(ks.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(ws.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(ws.DataReceived,e.payload,t,i,e.topic,n),null==t||t.emit(ks.DataReceived,e.payload,i,n)},this.handleSipDtmf=(t,e)=>{this.emit(ws.SipDTMFReceived,e,t),null==t||t.emit(ks.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 h=null!==(c=e.get(i))&&void 0!==c?c:Date.now(),d=Date.now();return a?e.delete(i):e.set(i,h),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:h,lastReceivedTime:d}}))}(e,this.transcriptionReceivedTimes);null==n||n.emit(Ss.TranscriptionReceived,s),null==i||i.emit(ks.TranscriptionReceived,s,n),this.emit(ws.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.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(e);this.emit(ws.ChatMessage,i,t)},this.handleMetrics=(t,e)=>{this.emit(ws.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(ws.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(ws.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ws.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ws.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Zi(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=us())||void 0===t?void 0:t.os)&&(yield this.selectDefaultDevices()),this.emit(ws.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const e=this.roomInfo;this.roomInfo=t,e&&e.metadata!==t.metadata&&this.emitWhenConnected(ws.RoomMetadataChanged,t.metadata),(null==e?void 0:e.activeRecording)!==t.activeRecording&&this.emitWhenConnected(ws.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(ws.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(ws.ParticipantNameChanged,t,this.localParticipant)},this.onLocalAttributesChanged=t=>{this.emit(ws.ParticipantAttributesChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(ws.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(ws.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=>Zi(this,void 0,void 0,(function*(){var e,i,n,s,r,o;null===(e=t.track)||void 0===e||e.on(Ss.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.on(Ss.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(ws.LocalTrackPublished,t,this.localParticipant),Jr(t.track)&&(yield t.track.checkForSilence())&&this.emit(ws.LocalAudioSilenceDetected,t);const a=yield null===(o=t.track)||void 0===o?void 0:o.getDeviceId(!1),c=Ks(t.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(ws.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=t=>{var e,i;null===(e=t.track)||void 0===e||e.off(Ss.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.off(Ss.Restarted,this.onLocalTrackRestarted),this.emit(ws.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>Zi(this,void 0,void 0,(function*(){const e=yield t.getDeviceId(!1),i=Ks(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(ws.ActiveDeviceChanged,i,e))})),this.onLocalConnectionQualityChanged=t=>{this.emit(ws.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=(t,e)=>{this.emit(ws.MediaDevicesError,t,e)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(ws.ParticipantPermissionsChanged,t,this.localParticipant)},this.onLocalChatMessageSent=t=>{this.emit(ws.ChatMessage,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},zo),t),this.log=Hi(null!==(i=this.options.loggerName)&&void 0!==i?i:Ji.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},qo),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Vo),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Fo),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Ia,this.outgoingDataStreamManager=new Ma(this.engine,this.log),this.disconnectLock=new a,this.localParticipant=new Ga("","",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",Mr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Mr(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Mr(this.options.audioOutput.deviceId)).catch((t=>this.log.warn("Could not set audio output: ".concat(t.message),this.logContext))),gr()){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}),Ka.cleanupRegistry&&Ka.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 Zi(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 so(i,e),this.e2eeManager.on(to.ParticipantEncryptionStatusChanged,((t,e)=>{(function(t){return t.isLocal})(e)&&(this.isE2EEEnabled=t),this.emit(ws.ParticipantEncryptionStatusChanged,t,e)})),this.e2eeManager.on(to.EncryptionError,((t,e)=>{const i=e?this.getParticipantByIdentity(e):void 0;this.emit(ws.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===Ea.Disconnected?hs.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?hs.resolve(this.roomInfo.sid):new hs(((t,e)=>{const i=e=>{""!==e.sid&&(this.engine.off(Ts.RoomUpdate,i),t(e.sid))};this.engine.on(Ts.RoomUpdate,i),this.once(ws.Disconnected,(()=>{this.engine.off(Ts.RoomUpdate,i),e(new Cs("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 Aa(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Ts.ParticipantUpdate,this.handleParticipantUpdates).on(Ts.RoomUpdate,this.handleRoomUpdate).on(Ts.SpeakersChanged,this.handleSpeakersChanged).on(Ts.StreamStateChanged,this.handleStreamStateUpdate).on(Ts.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Ts.SubscriptionError,this.handleSubscriptionError).on(Ts.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Ts.MediaTrackAdded,((t,e,i)=>{this.onTrackAdded(t,e,i)})).on(Ts.Disconnected,(t=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t)})).on(Ts.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Ts.DataPacketReceived,this.handleDataPacket).on(Ts.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Ea.SignalReconnecting)&&this.emit(ws.SignalReconnecting)})).on(Ts.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Ea.Connected)&&this.emit(ws.Reconnected)})).on(Ts.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Ea.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Ts.Restarting,this.handleRestarting).on(Ts.SignalRestarted,this.handleSignalRestarted).on(Ts.Offline,(()=>{this.setAndEmitConnectionState(Ea.Reconnecting)&&this.emit(ws.Reconnecting)})).on(Ts.DCBufferStatusChanged,((t,e)=>{this.emit(ws.DCBufferStatusChanged,t,e)})).on(Ts.LocalTrackSubscribed,(t=>{const e=this.localParticipant.getTrackPublications().find((e=>{let{trackSid:i}=e;return i===t}));e?(this.localParticipant.emit(ks.LocalTrackSubscribed,e),this.emitWhenConnected(ws.LocalTrackSubscribed,e,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})).on(Ts.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(ws.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 ao.getInstance().getDevices(t,e)}prepareConnection(t,e){return Zi(this,void 0,void 0,(function*(){if(this.state===Ea.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(yr(new URL(t))&&e){this.regionUrlProvider=new Qo(t,e);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Ea.Disconnected&&(this.regionUrl=i,yield fetch(Nr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Nr(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 Zi(this,void 0,void 0,(function*(){let i,n=()=>Zi(this,void 0,void 0,(function*(){}));switch(t){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Oi({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Oi({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Oi({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Oi({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=()=>Zi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Oi({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Zi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Oi({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 Oi({scenario:{case:"switchCandidateProtocol",value:"force-tls"===t?2:1}}),n=()=>Zi(this,void 0,void 0,(function*(){const t=this.engine.client.onLeave;t&&t(new ni({reason:Wt.CLIENT_INITIATED,action:si.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===e||"number"!=typeof e)throw new Error("subscriber-bandwidth requires a number as argument");i=new Oi({scenario:{case:"subscriberBandwidth",value:Br(e)}});break;case"leave-full-reconnect":i=new Oi({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 Zi(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,h,d;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===nr.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===nr.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,!lr()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(e=null!==(o=yield ao.getInstance().normalizeDeviceId("audiooutput",e))&&void 0!==o?o:""),null!==(a=(d=i.options).audioOutput)&&void 0!==a||(d.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===(h=i.audioContext)||void 0===h||h.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(ws.ActiveDeviceChanged,t,e)),l}()}))}setupLocalParticipantEvents(){this.localParticipant.on(ks.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ks.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ks.AttributesChanged,this.onLocalAttributesChanged).on(ks.TrackMuted,this.onLocalTrackMuted).on(ks.TrackUnmuted,this.onLocalTrackUnmuted).on(ks.LocalTrackPublished,this.onLocalTrackPublished).on(ks.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ks.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ks.MediaDevicesError,this.onMediaDevicesError).on(ks.AudioStreamAcquired,this.startAudio).on(ks.ChatMessage,this.onLocalChatMessageSent).on(ks.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===Ea.Connecting||this.state===Ea.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(ws.Reconnected,n),this.off(ws.Connected,n),this.off(ws.Disconnected,s)};return this.once(ws.Reconnected,n),this.once(ws.Connected,n),void this.once(ws.Disconnected,s)}if(this.state===Ea.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 h=a.addSubscribedMediaTrack(t,o,e,i,c);(null==h?void 0:h.isEncrypted)&&!this.e2eeManager&&this.emit(ws.EncryptionError,new Error("Encrypted ".concat(h.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!==Ea.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(ks.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ks.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ks.AttributesChanged,this.onLocalAttributesChanged).off(ks.TrackMuted,this.onLocalTrackMuted).off(ks.TrackUnmuted,this.onLocalTrackUnmuted).off(ks.LocalTrackPublished,this.onLocalTrackPublished).off(ks.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ks.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ks.MediaDevicesError,this.onMediaDevicesError).off(ks.AudioStreamAcquired,this.startAudio).off(ks.ChatMessage,this.onLocalChatMessageSent).off(ks.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),gr()&&(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(Ea.Disconnected),this.emit(ws.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(ws.ParticipantDisconnected,e),e.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(e.identity))}handleIncomingRpcRequest(t,e,i,n,s,r){return Zi(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(t,e),1!==r)return void(yield this.engine.publishRpcResponse(t,e,null,Ho.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(t,e,null,Ho.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:e,callerIdentity:t,payload:n,responseTimeout:s});Ko(r)>15360?(a=Ho.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=r}catch(t){t instanceof Ho?a=t:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),t),a=Ho.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(t,e,c,a)}))}selectDefaultDevices(){return Zi(this,void 0,void 0,(function*(){var t,e,i;const n=ao.getInstance().previousDevices,s=yield ao.getInstance().getDevices(void 0,!1),r=us();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(ws.ActiveDeviceChanged,t.kind,t.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let r of o){const o=Hs(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)),h=this.getActiveDevice(r);h===(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)!==h?yield this.switchActiveDevice(r,c[0].deviceId):"audioinput"===r&&!mr()||"videoinput"===r||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(r)))||"audiooutput"===r&&mr()||(yield this.switchActiveDevice(r,c[0].deviceId))}}))}acquireAudioContext(){return Zi(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=Qs())&&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(),ar(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(ws.AudioPlaybackStatusChanged,i))}))}createParticipant(t,e){var i;let n;return n=e?Ha.fromParticipantInfo(this.engine.client,e,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new Ha(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(ws.ParticipantConnected,i),i.on(ks.TrackPublished,(t=>{this.emitWhenConnected(ws.TrackPublished,t,i)})).on(ks.TrackSubscribed,((t,e)=>{t.kind===nr.Kind.Audio?(t.on(Ss.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(Ss.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===nr.Kind.Video&&(t.on(Ss.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(Ss.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ws.TrackSubscribed,t,e,i)})).on(ks.TrackUnpublished,(t=>{this.emit(ws.TrackUnpublished,t,i)})).on(ks.TrackUnsubscribed,((t,e)=>{this.emit(ws.TrackUnsubscribed,t,e,i)})).on(ks.TrackMuted,(t=>{this.emitWhenConnected(ws.TrackMuted,t,i)})).on(ks.TrackUnmuted,(t=>{this.emitWhenConnected(ws.TrackUnmuted,t,i)})).on(ks.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(ws.ParticipantMetadataChanged,t,i)})).on(ks.ParticipantNameChanged,(t=>{this.emitWhenConnected(ws.ParticipantNameChanged,t,i)})).on(ks.AttributesChanged,(t=>{this.emitWhenConnected(ws.ParticipantAttributesChanged,t,i)})).on(ks.ConnectionQualityChanged,(t=>{this.emitWhenConnected(ws.ConnectionQualityChanged,t,i)})).on(ks.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(ws.ParticipantPermissionsChanged,t,i)})).on(ks.TrackSubscriptionStatusChanged,((t,e)=>{this.emitWhenConnected(ws.TrackSubscriptionStatusChanged,t,e,i)})).on(ks.TrackSubscriptionFailed,((t,e)=>{this.emit(ws.TrackSubscriptionFailed,t,i,e)})).on(ks.TrackSubscriptionPermissionChanged,((t,e)=>{this.emitWhenConnected(ws.TrackSubscriptionPermissionChanged,t,e,i)})).on(ks.Active,(()=>{this.emitWhenConnected(ws.ParticipantActive,i),i.kind===te.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&&Gr(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=Ds.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,Wt.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ds.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(ws.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=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];if(this.state===Ea.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===Ea.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){return Zi(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 Kt({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:x.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Zt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ws.SignalConnected),this.emit(ws.Connected),this.setAndEmitConnectionState(Ea.Connected),r.video){const t=new za(nr.Kind.Video,new se({source:qt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ft.AUDIO,name:"video-dummy"}),new ma(r.useRealTracks&&(null===(e=window.navigator.mediaDevices)||void 0===e?void 0:e.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Ir(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(ks.LocalTrackPublished,t)}if(r.audio){const t=new za(nr.Kind.Audio,new se({source:qt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ft.AUDIO}),new na(r.useRealTracks&&(null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Pr(),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(ks.LocalTrackPublished,t)}for(let t=0;t<o.count-1;t+=1){let e=new Zt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(t),state:Xt.ACTIVE,tracks:[],joinedAt:x.parse(Date.now())});const i=this.getOrCreateParticipant(e.identity,e);if(o.video){const n=Ir(160*(null!==(s=o.aspectRatios[t%o.aspectRatios.length])&&void 0!==s?s:1),160,!1,!0),r=new se({source:qt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ft.AUDIO});i.addSubscribedMediaTrack(n,r.sid,new MediaStream([n]),new RTCRtpReceiver),e.tracks=[...e.tracks,r]}if(o.audio){const t=Pr(),n=new se({source:qt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ft.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=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];if(t!==ws.ActiveSpeakersChanged&&t!==ws.TranscriptionReceived){const e=Ya(i).filter((t=>void 0!==t));t!==ws.TrackSubscribed&&t!==ws.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 Ya(t){return t.map((t=>{if(t)return Array.isArray(t)?Ya(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t}))}function $a(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 String(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}Ka.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"}(Oa||(Oa={})),new TextEncoder,new TextDecoder;class Za extends Error{constructor(t,e){var i;super(t,e),$a(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}function Xa(){return Xa=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},Xa.apply(null,arguments)}$a(Za,"code","ERR_JOSE_GENERIC"),$a(class extends Za{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}}),$a(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),$a(this,"claim",void 0),$a(this,"reason",void 0),$a(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=e}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),$a(class extends Za{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}}),$a(this,"code","ERR_JWT_EXPIRED"),$a(this,"claim",void 0),$a(this,"reason",void 0),$a(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=e}},"code","ERR_JWT_EXPIRED"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED"),$a(class extends Za{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),$a(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID"),$a(class extends Za{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),$a(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY"),$a(class extends Za{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),$a(this,Symbol.asyncIterator,void 0),$a(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS"),$a(class extends Za{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),$a(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT"),$a(class extends Za{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),$a(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const tc=new Uint8Array(0);class ec{static getFullOptions(t){return Xa({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:String(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):String(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 tc}getOutputByteFrequencyData(){return tc}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 ic{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 nc(t){const[e,i]=t.split("_");if(!["pcm","ulaw"].includes(e))throw new Error(`Invalid format: ${t}`);const n=Number.parseInt(i);if(Number.isNaN(n))throw new Error(`Invalid sample rate: ${i}`);return{format:e,sampleRate:n}}const sc="0.13.0";function rc(t){return!!t.type}const oc="conversation_initiation_client_data";function ac(t){var e;const i={type:oc};var n,s,r,o,a,c,h,d;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==(h=t.overrides.tts)?void 0:h.similarityBoost},conversation:{text_only:null==(d=t.overrides.conversation)?void 0:d.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 cc 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 hc extends ic{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(!rc(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:String(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)||sc,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 h=["convai"];t.authorization&&h.push(`bearer.${t.authorization}`),e=new WebSocket(o,h);const d=await new Promise(((i,n)=>{e.addEventListener("open",(()=>{var i;const n=ac(t);null==(i=e)||i.send(JSON.stringify(n))}),{once:!0}),e.addEventListener("error",(()=>{setTimeout((()=>n(new cc("The connection was closed due to a socket error."))),0)})),e.addEventListener("close",(t=>{n(new cc(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);rc(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}=d,v=nc(null!=f?f:"pcm_16000"),m=nc(u);return new hc(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 dc(t){const e=new Uint8Array(t);return window.btoa(String.fromCharCode(...e))}function lc(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 uc=new Map;function fc(t,e){return async(i,n)=>{const s=uc.get(t);if(s)return i.addModule(s);if(n)try{return await i.addModule(n),void uc.set(t,n)}catch(e){throw new 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 uc.set(t,o)}catch(t){URL.revokeObjectURL(o)}try{const n=`data:application/javascript;base64,${btoa(e)}`;await i.addModule(n),uc.set(t,n)}catch(e){throw new 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 vc=fc("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 mc extends ic{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 new 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)||sc,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}`,h=await fetch(c);if(!h.ok)throw new Error(`ElevenLabs API returned ${h.status} ${h.statusText}`);if(e=(await h.json()).token,!e)throw new Error("No conversation token received from API")}catch(e){let i=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes("401")&&(i="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error(`Failed to fetch conversation token for agent ${t.agentId}: ${i}`)}}var r;const o=new Ka;try{const i=`room_${Date.now()}`,n=nc("pcm_48000"),s=nc("pcm_48000"),r=new mc(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(ws.Connected,e),t()};o.on(ws.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 h=ac(t);return r.debug({type:oc,message:h}),await r.sendMessage(h),r}catch(t){throw await o.disconnect(),t}}setupRoomEventListeners(){var t=this;this.room.on(ws.Connected,(async function(){t.isConnected=!0,console.info("WebRTC room connected")})),this.room.on(ws.Disconnected,(t=>{this.isConnected=!1,this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:null==t?void 0:t.toString()})})})),this.room.on(ws.ConnectionStateChanged,(t=>{t===Ea.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:`LiveKit connection state changed to ${t}`,context:new Event("connection_state_changed")}))})),this.room.on(ws.DataReceived,((t,e)=>{try{const e=JSON.parse((new TextDecoder).decode(t));if("audio"===e.type)return;rc(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(ws.TrackSubscribed,(async function(e,i,n){if(e.kind===nr.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(ws.ActiveSpeakersChanged,(async function(e){t.updateMode(e.length>0&&e[0].identity.startsWith("agent")?"speaking":"listening")})),this.room.on(ws.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(nr.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 vc(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=dc(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 new 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 new Error("Cannot change input device: room not connected or no local participant");try{const e=this.room.localParticipant.getTrackPublication(nr.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 Zi(this,void 0,void 0,(function*(){return(yield Ja({audio:null==t||t,video:!1}))[0]}))}(i);await this.room.localParticipant.publishTrack(n,{name:"microphone",source:nr.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 pc(t){const e=function(t){return t.connectionType?t.connectionType:"conversationToken"in t&&t.conversationToken?"webrtc":"websocket"}(t);switch(e){case"websocket":return hc.create(t);case"webrtc":return mc.create(t);default:throw new Error(`Unknown connection type: ${e}`)}}function gc(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}async function bc(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(gc()){var n;e=null!=(n=t.ios)?n:e}e>0&&await new Promise((t=>setTimeout(t,e)))}class yc extends ec{static async startSession(t){const e=ec.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 bc(e.connectionDelay),i=await pc(t),new yc(e,i)}catch(t){var n;throw e.onStatusChange&&e.onStatusChange({status:"disconnected"}),null==(n=i)||n.close(),t}}}const wc={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}};class kc{static async create({sampleRate:t,format:e,preferHeadphonesForIosDevices:i,inputDeviceId:n,workletPaths:s,libsampleratePath:r}){let o=null,a=null;try{const c=Xa({sampleRate:{ideal:t}},wc);if(gc()&&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=kc.getDeviceIdConstraint(n));const h=navigator.mediaDevices.getSupportedConstraints().sampleRate;o=new window.AudioContext(h?{sampleRate:t}:{});const d=o.createAnalyser();if(!h){const t=r||"https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js";await o.audioWorklet.addModule(t)}await vc(o.audioWorklet,null==s?void 0:s.rawAudioProcessor);const l=Xa({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(d),d.connect(f),await o.resume(),new kc(o,d,f,a,u)}catch(t){var c,h;throw null==(c=a)||c.getTracks().forEach((t=>{t.stop()})),null==(h=o)||h.close(),t}}static getDeviceIdConstraint(t){if(t)return gc()?{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=Xa({},wc);t&&(e.deviceId=kc.getDeviceIdConstraint(t));const i=Xa({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 Tc=fc("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 Sc{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 Tc(s.audioWorklet,null==n?void 0:n.audioConcatProcessor);const h=new AudioWorkletNode(s,"audioConcatProcessor");return h.port.postMessage({type:"setFormat",format:e}),h.connect(a),await s.resume(),i&&r.setSinkId&&await r.setSinkId(i),new Sc(s,o,a,h,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 new 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 Ec extends ec{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=ec.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 Ec.requestWakeLock());try{var c;return o=await navigator.mediaDevices.getUserMedia({audio:!0}),await bc(i.connectionDelay),s=await pc(t),[n,r]=await Promise.all([kc.create(Xa({},s.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),Sc.create(Xa({},s.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),null==(c=o)||c.getTracks().forEach((t=>{t.stop()})),o=null,new Ec(i,s,n,r,a)}catch(t){var h,d,l,u;i.onStatusChange&&i.onStatusChange({status:"disconnected"}),null==(h=o)||h.getTracks().forEach((t=>{t.stop()})),null==(d=s)||d.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:dc(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:lc(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 mc?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&&Ec.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 mc||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 mc?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 mc?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 hc)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 mc&&await this.connection.setAudioInputDevice(n||""),await this.input.close();const s=await kc.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 hc)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 mc&&await this.connection.setAudioOutputDevice(i||""),await this.output.close();const n=await Sc.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 Oc,Ac,xc;!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"}(Oc||(Oc={})),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"}(Ac||(Ac={})),function(t){t.MANUAL="manual",t.VAD="vad"}(xc||(xc={}));const Cc=class{constructor(i){t(this,i),this.conversationStarted=e(this,"conversationStarted"),this.conversationEnded=e(this,"conversationEnded"),this.widgetError=e(this,"widgetError"),this.statusChanged=e(this,"statusChanged"),this.messageReceived=e(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(new Error("Connection timeout"))}),15e3),a=t?yc:Ec;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(new 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:String(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,n=this.getThemeColors(),s={"--sl-primary":this.primaryColor,"--sl-bg":n.bg,"--sl-text":n.text,"--sl-muted":n.muted,"--sl-border":n.border,"--sl-surface":n.surface};return"inline"===this.variant?i("div",{class:"sl-widget sl-inline",style:s},this.renderCard(t)):i("div",{class:`sl-widget sl-floating ${this.getPositionClasses()}`,style:s},this.isExpanded?i("div",{class:"sl-card"},this.renderCard(t)):i("div",{class:"sl-fab-pill"},i("div",{class:"sl-fab-avatar"},this.avatarUrl?i("img",{src:this.avatarUrl,alt:"",class:"sl-fab-avatar-img"}):i("staylift-orb",{size:48,primaryColor:this.primaryColor,inputVolume:this.inputVolume,outputVolume:this.outputVolume,isActive:e})),i("div",{class:"sl-fab-content"},i("span",{class:"sl-fab-prompt"},this.fabPrompt),i("button",{class:"sl-fab-btn",onClick:this.handleToggleExpand},i("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("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 i("div",{class:"sl-terms"},i("div",{class:"sl-terms-content"},i("h3",{class:"sl-terms-title"},this.t("termsTitle")),i("p",{class:"sl-terms-text"},this.t("termsText")),i("p",{class:"sl-terms-warning"},this.t("termsWarning"))),i("div",{class:"sl-terms-actions"},i("button",{class:"sl-terms-btn sl-terms-btn--decline",onClick:this.handleDeclineTerms},this.t("termsDecline")),i("button",{class:"sl-terms-btn sl-terms-btn--agree",onClick:this.handleAcceptTerms},this.t("termsAgree"))))}renderHeader(t){return i("div",{class:"sl-header"},i("div",{class:"sl-header-left"},i("div",{class:"sl-orb-ring"},this.avatarUrl?i("img",{src:this.avatarUrl,alt:"",class:"sl-header-avatar-img"}):i("staylift-orb",{size:40,primaryColor:this.primaryColor,inputVolume:this.inputVolume,outputVolume:this.outputVolume,isActive:"connected"===this.status&&!this.isTextOnlyMode})),i("div",{class:"sl-header-text"},i("span",{class:"sl-title"},this.brandName),i("span",{class:"sl-subtitle"},this.errorMessage?i("span",{class:"sl-error"},this.errorMessage):"disconnected"===this.status?this.t("tapToStart"):"connected"===this.status?i("span",{class:"sl-connected"},this.t("connected")):t?i("span",{class:"sl-shimmer"},this.status):null))),i("div",{class:"sl-header-right"},i("div",{class:`sl-dot ${"connected"===this.status?"sl-dot--active":""} ${t?"sl-dot--pulse":""}`}),"floating"===this.variant&&i("button",{class:"sl-close",onClick:this.handleToggleExpand},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("path",{d:"M18 6L6 18M6 6l12 12"})))))}renderContent(){const t="connecting"===this.status,e="connected"===this.status;return i("div",{class:"sl-content",ref:t=>this.messagesContainer=t??null},0===this.messages.length?i("div",{class:"sl-empty"},i("staylift-orb",{size:48,primaryColor:this.primaryColor,isActive:!1}),i("h3",{class:"sl-empty-title"},this.t(t?"starting":e?"talkOrType":"emptyTitle")),i("p",{class:"sl-empty-desc"},this.t(t?"connecting":e?"ready":"emptyDesc"))):this.messages.map(((t,e)=>i("div",{class:`sl-msg sl-msg--${t.role}`,key:e},i("div",{class:"sl-msg-row"},i("div",{class:"sl-msg-bubble"},t.content)),"assistant"===t.role&&i("div",{class:"sl-msg-actions"},i("button",{class:"sl-action",onClick:()=>this.copyToClipboard(t.content,e)},this.copiedIndex===e?i("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("polyline",{points:"20 6 9 17 4 12"})):i("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),i("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,n="connected"===this.status&&!this.isTextOnlyMode,s="connected"===this.status&&this.isTextOnlyMode;return i("div",{class:"sl-footer"},e&&i("div",{class:"sl-mode-toggle"},i("button",{class:"sl-mode-btn "+("text"===this.selectedMode?"sl-mode-btn--active":""),onClick:()=>this.selectedMode="text"},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("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")),i("button",{class:"sl-mode-btn "+("voice"===this.selectedMode?"sl-mode-btn--active":""),onClick:()=>this.selectedMode="voice"},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),i("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),i("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),i("line",{x1:"8",y1:"23",x2:"16",y2:"23"})),this.t("modeVoice"))),s&&i("div",{class:"sl-input-row"},i("button",{class:"sl-btn sl-btn--end",onClick:()=>this.handleTextButton(),disabled:t,title:this.t("endText")},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),i("line",{x1:"6",y1:"6",x2:"18",y2:"18"}))),i("input",{type:"text",class:"sl-input",placeholder:this.t("placeholder"),value:this.inputText,onInput:this.handleInputChange,onKeyDown:this.handleInputKeyDown,disabled:t}),i("button",{class:"sl-btn",onClick:()=>this.handleSendText(),disabled:!this.inputText.trim()||t},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),i("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})))),"text"===this.selectedMode&&e&&i("div",{class:"sl-voice-controls"},i("button",{class:"sl-voice-btn",onClick:()=>this.handleTextButton(),disabled:t},i("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("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&&i("div",{class:"sl-voice-controls"},i("button",{class:"sl-voice-btn",onClick:()=>this.handleVoiceButton(),disabled:t},i("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),i("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),i("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),i("line",{x1:"8",y1:"23",x2:"16",y2:"23"})),this.t(t?"connecting":"startVoice"))),n&&i("div",{class:"sl-voice-controls"},i("button",{class:"sl-voice-btn sl-voice-btn--end",onClick:()=>this.handleVoiceButton(),disabled:t},i("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("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"}),i("line",{x1:"22",y1:"2",x2:"2",y2:"22"})),this.t("endVoice"))),this.showBranding&&i("div",{class:"sl-branding"},i("a",{href:"https://staylift.com",target:"_blank",rel:"noopener noreferrer"},i("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 n(this)}};Cc.style=":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}}";export{Cc as staylift_widget}
1
+ import{r as t,c as e,h as i,g as n}from"./p-DAtfDq5B.js";function s(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 r=Object.defineProperty,o=(t,e,i)=>((t,e,i)=>e in t?r(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,i);let a=class{constructor(){o(this,"_locking"),o(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 c(t,e){if(!t)throw new Error(e)}function h(t){if("number"!=typeof t)throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>2147483647||t<-2147483648)throw new Error("invalid int 32: "+t)}function d(t){if("number"!=typeof t)throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>4294967295||t<0)throw new Error("invalid uint 32: "+t)}function l(t){if("number"!=typeof t)throw new Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>34028234663852886e22||t<-34028234663852886e22))throw new Error("invalid float 32: "+t)}const u=Symbol("@bufbuild/protobuf/enum-type");function f(t,e,i){t[u]=v(e,i.map((e=>({no:e.no,name:e.name,localName:t[e.no]}))))}function v(t,e){const i=Object.create(null),n=Object.create(null),s=[];for(const t of e){const e=m(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 m(t){return"localName"in t?t:Object.assign(Object.assign({},t),{localName:t.name})}class p{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 new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(t instanceof Error?t.message:String(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 g(){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 new Error("invalid varint")}function b(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 y=4294967296;function w(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>=y&&(s+=n/y|0,n%=y)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?S(n,s):T(n,s)}function k(t,e){if(({lo:t,hi:e}=function(t,e){return{lo:t>>>0,hi:e>>>0}}(t,e)),e<=2097151)return String(y*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.toString()+E(r)+E(s)}function T(t,e){return{lo:0|t,hi:0|e}}function S(t,e){return e=~e,t?t=1+~t:e+=1,T(t,e)}const E=t=>{const e=String(t);return"0000000".slice(e.length)+e};function O(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 A(){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 new Error("invalid varint");return this.assertBounds(),e>>>0}const x=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 new Error("int64 invalid: ".concat(t));return n},uParse(t){const e="bigint"==typeof t?t:BigInt(t);if(e>s||e<n)throw new 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=>c(/^-?[0-9]+$/.test(t),"int64 invalid: ".concat(t)),i=t=>c(/^[0-9]+$/.test(t),"uint64 invalid: ".concat(t));return{zero:"0",supported:!1,parse:t=>("string"!=typeof t&&(t=t.toString()),e(t),t),uParse:t=>("string"!=typeof t&&(t=t.toString()),i(t),t),enc:t=>("string"!=typeof t&&(t=t.toString()),e(t),w(t)),uEnc:t=>("string"!=typeof t&&(t=t.toString()),i(t),w(t)),dec:(t,e)=>function(t,e){let i=T(t,e);const n=2147483648&i.hi;n&&(i=S(i.lo,i.hi));const s=k(i.lo,i.hi);return n?"-"+s:s}(t,e),uDec:(t,e)=>k(t,e)}}();var C,_,R;function I(t,e,i){if(e===i)return!0;if(t==C.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 C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return e==i}return!1}function j(t,e){switch(t){case C.BOOL:return!1;case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return 0==e?x.zero:"0";case C.DOUBLE:case C.FLOAT:return 0;case C.BYTES:return new Uint8Array(0);case C.STRING:return"";default:return 0}}function P(t,e){switch(t){case C.BOOL:return!1===e;case C.STRING:return""===e;case C.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"}(C||(C={})),function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING"}(_||(_={})),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"}(R||(R={}));class D{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 new 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(d(t);t>127;)this.buf.push(127&t|128),t>>>=7;return this.buf.push(t),this}int32(t){return h(t),O(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){l(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){d(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){h(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return h(t),O(t=(t<<1^t>>31)>>>0,this.buf),this}sfixed64(t){let e=new Uint8Array(8),i=new DataView(e.buffer),n=x.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=x.uEnc(t);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(e)}int64(t){let e=x.enc(t);return b(e.lo,e.hi,this.buf),this}sint64(t){let e=x.enc(t),i=e.hi>>31;return b(e.lo<<1^i,(e.hi<<1|e.lo>>>31)^i,this.buf),this}uint64(t){let e=x.uEnc(t);return b(e.lo,e.hi,this.buf),this}}class M{constructor(t,e){this.varint64=g,this.uint32=A,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 new Error("illegal tag: field no "+e+" wire type "+i);return[e,i]}skip(t,e){let i=this.pos;switch(t){case R.Varint:for(;128&this.buf[this.pos++];);break;case R.Bit64:this.pos+=4;case R.Bit32:this.pos+=4;break;case R.LengthDelimited:let i=this.uint32();this.pos+=i;break;case R.StartGroup:for(;;){const[t,i]=this.tag();if(i===R.EndGroup){if(void 0!==e&&t!==e)throw new Error("invalid end group tag");break}this.skip(i,t)}break;default:throw new 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 x.dec(...this.varint64())}uint64(){return x.uDec(...this.varint64())}sint64(){let[t,e]=this.varint64(),i=-(1&t);return t=(t>>>1|(1&e)<<31)^i,e=e>>>1^i,x.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 x.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return x.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let 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 N(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 j(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 U="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),L=[];for(let t=0;t<U.length;t++)L[U[t].charCodeAt(0)]=t;L["-".charCodeAt(0)]=U.indexOf("+"),L["_".charCodeAt(0)]=U.indexOf("/");const B={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=L[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+=U[e>>2],s=(3&e)<<4,n=1;break;case 1:i+=U[s|e>>4],s=(15&e)<<2,n=2;break;case 2:i+=U[s|e>>6],i+=U[63&e],n=0}return n&&(i+=U[s],i+="=",1==n&&(i+="=")),i}};function F(t,e,i){z(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]=N(e);for(const t of s)e.runtime.bin.readField(r,n.readerFactory(t.data),e.field,t.wireType,n);return o()}function q(t,e,i,n){z(e,t);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(V(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 V(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 z(t,e){c(t.extendee.typeName==e.getType().typeName,"extension ".concat(t.typeName," can only be applied to message ").concat(t.extendee.typeName))}function J(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:!P(t.T,e[i]);case"message":return void 0!==e[i];case"map":return Object.keys(e[i]).length>0}}function W(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?j(t.T,t.L):void 0;break;case"message":e[i]=void 0}}function G(t,e){if(null===t||"object"!=typeof t)return!1;if(!Object.getOwnPropertyNames(p.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 Q(t,e){return G(e)||!t.fieldWrapper?e:t.fieldWrapper.wrapField(e)}const H={ignoreUnknownFields:!1},K={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};const Y=Symbol(),$=Symbol();function Z(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 String(t)}}function X(t,e,i,n,s){let r=i.localName;if(i.repeated){if(c("map"!=i.kind),null===e)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e)));const o=t[r];for(const t of e){if(null===t)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(t)));switch(i.kind){case"message":o.push(i.T.fromJson(t,n));break;case"enum":const e=it(i.T,t,n.ignoreUnknownFields,!0);e!==$&&o.push(e);break;case"scalar":try{o.push(et(i.T,t,i.L,!0))}catch(e){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}}}}else if("map"==i.kind){if(null===e)return;if("object"!=typeof e||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e)));const o=t[r];for(const[t,r]of Object.entries(e)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let a;try{a=tt(i.K,t)}catch(t){let n="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),new Error(n)}switch(i.V.kind){case"message":o[a]=i.V.T.fromJson(r,n);break;case"enum":const t=it(i.V.T,r,n.ignoreUnknownFields,!0);t!==$&&(o[a]=t);break;case"scalar":try{o[a]=et(i.V.T,r,_.BIGINT,!0)}catch(t){let n="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),new 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];G(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=it(i.T,e,n.ignoreUnknownFields,!1);switch(c){case Y:W(i,t);break;case $:break;default:t[r]=c}break;case"scalar":try{const n=et(i.T,e,i.L,!1);n===Y?W(i,t):t[r]=n}catch(t){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),new Error(n)}}}function tt(t,e){if(t===C.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1}return et(t,e,_.BIGINT,!0).toString()}function et(t,e,i,n){if(null===e)return n?j(t,i):Y;switch(t){case C.DOUBLE:case C.FLOAT:if("NaN"===e)return Number.NaN;if("Infinity"===e)return Number.POSITIVE_INFINITY;if("-Infinity"===e)return Number.NEGATIVE_INFINITY;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==C.FLOAT&&l(n),n;case C.INT32:case C.FIXED32:case C.SFIXED32:case C.SINT32:case C.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==C.UINT32||t==C.FIXED32?d(s):h(s),s;case C.INT64:case C.SFIXED64:case C.SINT64:if("number"!=typeof e&&"string"!=typeof e)break;const r=x.parse(e);return i?r.toString():r;case C.FIXED64:case C.UINT64:if("number"!=typeof e&&"string"!=typeof e)break;const o=x.uParse(e);return i?o.toString():o;case C.BOOL:if("boolean"!=typeof e)break;return e;case C.STRING:if("string"!=typeof e)break;return e;case C.BYTES:if(""===e)return new Uint8Array(0);if("string"!=typeof e)break;return B.dec(e)}throw new Error}function it(t,e,i,n){if(null===e)return"google.protobuf.NullValue"==t.typeName?0:n?t.values[0].no:Y;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 $}throw new Error("cannot decode enum ".concat(t.typeName," from JSON: ").concat(Z(e)))}function nt(t){return!(!t.repeated&&"map"!=t.kind&&(t.oneof||"message"==t.kind||t.opt||t.req))}function st(t,e,i){if("map"==t.kind){c("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.toString()]=ot(t.V.T,i);break;case"message":for(const[t,e]of s)n[t.toString()]=e.toJson(i);break;case"enum":const e=t.V.T;for(const[t,r]of s)n[t.toString()]=rt(e,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(t.repeated){c(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let i=0;i<e.length;i++)n.push(ot(t.T,e[i]));break;case"enum":for(let s=0;s<e.length;s++)n.push(rt(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 ot(t.T,e);case"enum":return rt(t.T,e,i.enumAsInteger);case"message":return Q(t.T,e).toJson(i)}}function rt(t,e,i){var n;if(c("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 ot(t,e){switch(t){case C.INT32:case C.SFIXED32:case C.SINT32:case C.FIXED32:case C.UINT32:return c("number"==typeof e),e;case C.FLOAT:case C.DOUBLE:return c("number"==typeof e),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case C.STRING:return c("string"==typeof e),e;case C.BOOL:return c("boolean"==typeof e),e;case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return c("bigint"==typeof e||"string"==typeof e||"number"==typeof e),e.toString();case C.BYTES:return c(e instanceof Uint8Array),B.enc(e)}}const at=Symbol("@bufbuild/protobuf/unknown-fields"),ct={readUnknownFields:!0,readerFactory:t=>new M(t)},ht={writeUnknownFields:!0,writerFactory:()=>new D};function dt(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?C.INT32:i.T;let c=ft;if("scalar"==i.kind&&i.L>0&&(c=ut),r){let i=t[o];if(n==R.LengthDelimited&&a!=C.STRING&&a!=C.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 h=i.T;r?t[o].push(lt(e,new h,s,i)):G(t[o])?lt(e,t[o],s,i):(t[o]=lt(e,new h,s,i),!h.fieldWrapper||i.oneof||i.repeated||(t[o]=h.fieldWrapper.unwrapField(t[o])));break;case"map":let[d,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=ft(e,t.K);break;case 2:switch(t.V.kind){case"scalar":o=ft(e,t.V.T);break;case"enum":o=e.int32();break;case"message":o=lt(e,new t.V.T,i,void 0)}}}if(void 0===r&&(r=j(t.K,_.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=r.toString()),void 0===o)switch(t.V.kind){case"scalar":o=j(t.V.T,_.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][d]=l}}function lt(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 ut(t,e){const i=ft(t,e);return"bigint"==typeof i?i.toString():i}function ft(t,e){switch(e){case C.STRING:return t.string();case C.BOOL:return t.bool();case C.DOUBLE:return t.double();case C.FLOAT:return t.float();case C.INT32:return t.int32();case C.INT64:return t.int64();case C.UINT64:return t.uint64();case C.FIXED64:return t.fixed64();case C.BYTES:return t.bytes();case C.FIXED32:return t.fixed32();case C.SFIXED32:return t.sfixed32();case C.SFIXED64:return t.sfixed64();case C.SINT64:return t.sint64();case C.UINT32:return t.uint32();case C.SINT32:return t.sint32()}}function vt(t,e,i,n){c(void 0!==e);const s=t.repeated;switch(t.kind){case"scalar":case"enum":let r="enum"==t.kind?C.INT32:t.T;if(s)if(c(Array.isArray(e)),t.packed)!function(t,e,i,n){if(!n.length)return;t.tag(i,R.LengthDelimited).fork();let[,s]=bt(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)gt(i,r,t.no,n);else gt(i,r,t.no,e);break;case"message":if(s){c(Array.isArray(e));for(const s of e)pt(i,n,t,s)}else pt(i,n,t,e);break;case"map":c("object"==typeof e&&null!=e);for(const[s,r]of Object.entries(e))mt(i,n,t,s,r)}}function mt(t,e,i,n,s){t.tag(i.no,R.LengthDelimited),t.fork();let r=n;switch(i.K){case C.INT32:case C.FIXED32:case C.UINT32:case C.SFIXED32:case C.SINT32:r=Number.parseInt(n);break;case C.BOOL:c("true"==n||"false"==n),r="true"==n}switch(gt(t,i.K,1,r),i.V.kind){case"scalar":gt(t,i.V.T,2,s);break;case"enum":gt(t,C.INT32,2,s);break;case"message":c(void 0!==s),t.tag(2,R.LengthDelimited).bytes(s.toBinary(e))}t.join()}function pt(t,e,i,n){const s=Q(i.T,n);i.delimited?t.tag(i.no,R.StartGroup).raw(s.toBinary(e)).tag(i.no,R.EndGroup):t.tag(i.no,R.LengthDelimited).bytes(s.toBinary(e))}function gt(t,e,i,n){c(void 0!==n);let[s,r]=bt(e);t.tag(i,s)[r](n)}function bt(t){let e=R.Varint;switch(t){case C.BYTES:case C.STRING:e=R.LengthDelimited;break;case C.DOUBLE:case C.FIXED64:case C.SFIXED64:e=R.Bit64;break;case C.FIXED32:case C.SFIXED32:case C.FLOAT:e=R.Bit32}return[e,C[t].toLowerCase()]}function yt(t){if(void 0===t)return t;if(G(t))return t.clone();if(t instanceof Uint8Array){const e=new Uint8Array(t.byteLength);return e.set(t),e}return t}function wt(t){return t instanceof Uint8Array?t:new Uint8Array(t)}class kt{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 Tt(t,e){const i=Et(t);return e?i:_t(Ct(i))}const St=Et;function Et(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 Ot=new Set(["constructor","toString","toJSON","valueOf"]),At=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),xt=t=>"".concat(t,"$"),Ct=t=>At.has(t)?xt(t):t,_t=t=>Ot.has(t)?xt(t):t;class Rt{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=Tt(t,!1)}addField(t){c(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 It=(jt=t=>new kt(t,(t=>function(t){var e,i,n,s,r,o;const a=[];let c;for(const h of"function"==typeof t?t():t){const t=h;if(t.localName=Tt(h.name,void 0!==h.oneof),t.jsonName=null!==(e=h.jsonName)&&void 0!==e?e:St(h.name),t.repeated=null!==(i=h.repeated)&&void 0!==i&&i,"scalar"==h.kind&&(t.L=null!==(n=h.L)&&void 0!==n?n:_.BIGINT),t.delimited=null!==(s=h.delimited)&&void 0!==s&&s,t.req=null!==(r=h.req)&&void 0!==r&&r,t.opt=null!==(o=h.opt)&&void 0!==o&&o,void 0===h.packed&&(t.packed="enum"==h.kind||"scalar"==h.kind&&h.T!=C.BYTES&&h.T!=C.STRING),void 0!==h.oneof){const e="string"==typeof h.oneof?h.oneof:h.oneof.name;c&&c.name==e||(c=new Rt(e)),t.oneof=c,c.addField(t)}a.push(t)}return a}(t))),Pt=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]=j(e.T,e.L)}}},{syntax:"proto3",json:{makeReadOptions:function(t){return t?Object.assign(Object.assign({},H),t):H},makeWriteOptions:function(t){return t?Object.assign(Object.assign({},K),t):K},readMessage(t,e,i,n){if(null==e||Array.isArray(e)||"object"!=typeof e)throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(Z(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 new 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)}X(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]=N(s);X(t,a,s.field,i,s),q(n,s,r(),i)}}if(!e&&!i.ignoreUnknownFields)throw new 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(!J(s,t)){if(s.req)throw"required field not set";if(!e.emitDefaultValues)continue;if(!nt(s))continue}const i=st(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&&V(t,o)){const i=F(t,o,e),s=st(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:String(t);throw new Error(e+(n.length>0?": ".concat(n):""))}return n},readScalar:(t,e,i)=>et(t,e,null!=i?i:_.BIGINT,!0),writeScalar(t,e,i){if(void 0!==e)return i||P(t,e)?ot(t,e):void 0},debug:Z},bin:{makeReadOptions:function(t){return t?Object.assign(Object.assign({},ct),t):ct},makeWriteOptions:function(t){return t?Object.assign(Object.assign({},ht),t):ht},listUnknownFields(t){var e;return null!==(e=t[at])&&void 0!==e?e:[]},discardUnknownFields(t){delete t[at]},writeUnknownFields(t,e){const i=t[at];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[at])||(s[at]=[]),s[at].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!=R.EndGroup);){const i=r.fields.find(a);if(i)dt(t,e,i,c,n);else{const i=e.skip(c,a);n.readUnknownFields&&this.onUnknownField(t,a,c,i)}}if(s&&(c!=R.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:dt,writeMessage(t,e,i){const n=t.getType();for(const s of n.fields.byNumber())if(J(s,t))vt(s,s.oneof?t[s.oneof.localName].value:t[s.localName],e,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(t,e),e},writeField(t,e,i,n){void 0!==e&&vt(t,e,i,n)}},util:Object.assign(Object.assign({},{setEnumType:f,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&&!G(o,e.T)?o=new e.T(o):e&&"scalar"===e.kind&&e.T===C.BYTES&&(o=wt(o)),s[i]={case:t,value:o};break;case"scalar":case"enum":let a=r[i];n.T===C.BYTES&&(a=n.repeated?a.map(wt):wt(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===C.BYTES)for(const[t,e]of Object.entries(r[i]))s[i][t]=wt(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=>G(t,c)?t:new c(t)));else{const t=r[i];s[i]=c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?wt(t):t:G(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)=>I(t.T,e,s[i])));case"enum":return n.every(((t,e)=>I(C.INT32,t,s[e])))}throw new Error("repeated cannot contain ".concat(t.kind))}switch(t.kind){case"message":let e=n,i=s;return t.T.fieldWrapper&&(void 0===e||G(e)||(e=t.T.fieldWrapper.wrapField(e)),void 0===i||G(i)||(i=t.T.fieldWrapper.wrapField(i))),t.T.equals(e,i);case"enum":return I(C.INT32,n,s);case"scalar":return I(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 I(C.INT32,n.value,s.value);case"scalar":return I(r.T,n.value,s.value)}throw new 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=>I(C.INT32,n[t],s[t])));case"scalar":const i=t.V.T;return o.every((t=>I(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(yt);else if("map"==i.kind){s=n[i.localName];for(const[t,i]of Object.entries(e))s[t]=yt(i)}else s="oneof"==i.kind?i.findField(e.case)?{case:e.case,value:yt(e.value)}:{case:void 0}:yt(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:jt,initFields:Pt}),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 p),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:function(t,e){const i={};for(const t of e){const e=m(t);i[e.localName]=e.no,i[e.no]=e.localName}return f(i,t,e),i},makeEnumType:v,getEnumType:function(t){const e=t[u];return c(e,"missing enum type on enum object"),e},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)}});var jt,Pt;class Dt extends p{constructor(t){super(),this.seconds=x.zero,this.nanos=0,It.util.initPartial(t,this)}fromJson(t,e){if("string"!=typeof t)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(It.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 new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=x.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(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 new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const t=(this.nanos+1e9).toString().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 Dt.fromDate(new Date)}static fromDate(t){const e=t.getTime();return new Dt({seconds:x.parse(Math.floor(e/1e3)),nanos:e%1e3*1e6})}static fromBinary(t,e){return(new Dt).fromBinary(t,e)}static fromJson(t,e){return(new Dt).fromJson(t,e)}static fromJsonString(t,e){return(new Dt).fromJsonString(t,e)}static equals(t,e){return It.util.equals(Dt,t,e)}}Dt.runtime=It,Dt.typeName="google.protobuf.Timestamp",Dt.fields=It.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const Mt=It.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Dt},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Nt,repeated:!0},{no:5,name:"events",kind:"message",T:Lt,repeated:!0}])),Nt=It.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:Ut,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Ut=It.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Dt},{no:3,name:"value",kind:"scalar",T:2}])),Lt=It.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:Dt},{no:7,name:"normalized_end_timestamp",kind:"message",T:Dt,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Bt=It.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ft=It.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),qt=It.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"}]),Vt=It.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),zt=It.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Jt=It.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Wt=It.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"}]),Gt=It.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"}]),Qt=It.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ht=It.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"}]),Kt=It.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:Yt,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:Re}])),Yt=It.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),$t=It.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:It.getEnumType(qt),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}])),Zt=It.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:It.getEnumType(Xt)},{no:4,name:"tracks",kind:"message",T:se,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:$t},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:It.getEnumType(te)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:It.getEnumType(Wt)},{no:18,name:"kind_details",kind:"enum",T:It.getEnumType(ee),repeated:!0}])),Xt=It.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),te=It.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"}]),ee=It.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),ie=It.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ne=It.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:re,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:It.getEnumType(oe)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),se=It.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:It.getEnumType(Ft)},{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:It.getEnumType(qt)},{no:10,name:"layers",kind:"message",T:re,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:ne,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:It.getEnumType(ie)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Re},{no:19,name:"audio_features",kind:"enum",T:It.getEnumType(Ht),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:It.getEnumType(Bt)}])),re=It.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:It.getEnumType(Vt)},{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}])),oe=It.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"}]),ae=It.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:It.getEnumType(ce)},{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:fe,oneof:"value"},{no:3,name:"speaker",kind:"message",T:le,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:ve,oneof:"value"},{no:7,name:"transcription",kind:"message",T:me,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Mt,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:ge,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:be,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:ye,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:we,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:De,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Me,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Ne,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:he,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),ce=It.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),he=It.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:It.getEnumType(ie)},{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}])),de=It.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:fe,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:ge,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:be,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:ye,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:we,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:De,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Me,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Ne,oneof:"value"}])),le=It.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:ue,repeated:!0}])),ue=It.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}])),fe=It.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}])),ve=It.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),me=It.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:pe,repeated:!0}])),pe=It.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}])),ge=It.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}])),be=It.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}])),ye=It.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),we=It.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:ke,oneof:"value"}])),ke=It.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}])),Te=It.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Se=It.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:It.getEnumType(Ee)},{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}])),Ee=It.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Oe=It.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:It.getEnumType(Ae)},{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}])),Ae=It.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"}]),xe=It.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Ce},{no:2,name:"screen",kind:"message",T:Ce},{no:3,name:"resume_connection",kind:"enum",T:It.getEnumType(Jt)},{no:4,name:"disabled_codecs",kind:"message",T:_e},{no:5,name:"force_relay",kind:"enum",T:It.getEnumType(Jt)}])),Ce=It.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:It.getEnumType(Jt)}])),_e=It.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:Yt,repeated:!0},{no:2,name:"publish",kind:"message",T:Yt,repeated:!0}])),Re=It.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Ie=It.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),je=It.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:It.getEnumType(Ie)},{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"}),Pe=It.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),De=It.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:It.getEnumType(ie)},{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:Pe,oneof:"content_header"}]),{localName:"DataStream_Header"}),Me=It.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"}),Ne=It.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"}),Ue=It.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Le=It.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Be=It.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Fe=It.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),qe=It.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:$e,oneof:"message"},{no:2,name:"answer",kind:"message",T:$e,oneof:"message"},{no:3,name:"trickle",kind:"message",T:We,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Je,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ge,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Xe,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ti,oneof:"message"},{no:8,name:"leave",kind:"message",T:ni,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ri,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:yi,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ti,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Oi,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:oi,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ai,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ei,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ii,oneof:"message"}])),Ve=It.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Qe,oneof:"message"},{no:2,name:"answer",kind:"message",T:$e,oneof:"message"},{no:3,name:"offer",kind:"message",T:$e,oneof:"message"},{no:4,name:"trickle",kind:"message",T:We,oneof:"message"},{no:5,name:"update",kind:"message",T:Ze,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Ke,oneof:"message"},{no:8,name:"leave",kind:"message",T:ni,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ge,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ci,oneof:"message"},{no:11,name:"room_update",kind:"message",T:hi,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:li,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:fi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:pi,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:wi,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Ye,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:He,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:xi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ri,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Ii,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Pi,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:ki,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Li,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:gi,oneof:"message"}])),ze=It.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:re,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:It.getEnumType(oe)}])),Je=It.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:It.getEnumType(Ft)},{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:It.getEnumType(qt)},{no:9,name:"layers",kind:"message",T:re,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ze,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:It.getEnumType(ie)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:It.getEnumType(Bt)},{no:17,name:"audio_features",kind:"enum",T:It.getEnumType(Ht),repeated:!0}])),We=It.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:It.getEnumType(Le)},{no:3,name:"final",kind:"scalar",T:8}])),Ge=It.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Qe=It.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:Kt},{no:2,name:"participant",kind:"message",T:Zt},{no:3,name:"other_participants",kind:"message",T:Zt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ai,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:xe},{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:Se},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Yt,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),He=It.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:ai,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:xe},{no:3,name:"server_info",kind:"message",T:Se},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),Ke=It.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:se}])),Ye=It.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),$e=It.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}}])),Ze=It.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:Zt,repeated:!0}])),Xe=It.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:Te,repeated:!0}])),ti=It.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:It.getEnumType(Vt)},{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}])),ei=It.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:It.getEnumType(Ht),repeated:!0}])),ii=It.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}])),ni=It.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:It.getEnumType(Wt)},{no:3,name:"action",kind:"enum",T:It.getEnumType(si)},{no:4,name:"regions",kind:"message",T:Ci}])),si=It.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),ri=It.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:re,repeated:!0}])),oi=It.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}])),ai=It.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}])),ci=It.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:ue,repeated:!0}])),hi=It.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:Kt}])),di=It.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:It.getEnumType(zt)},{no:3,name:"score",kind:"scalar",T:2}])),li=It.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:di,repeated:!0}])),ui=It.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:It.getEnumType(Be)}])),fi=It.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:ui,repeated:!0}])),vi=It.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:It.getEnumType(Vt)},{no:2,name:"enabled",kind:"scalar",T:8}])),mi=It.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:vi,repeated:!0}])),pi=It.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:vi,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:mi,repeated:!0}])),gi=It.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Ue,repeated:!0}])),bi=It.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}])),yi=It.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:bi,repeated:!0}])),wi=It.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}])),ki=It.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:Kt},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Zt},{no:4,name:"other_participants",kind:"message",T:Zt,repeated:!0}])),Ti=It.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:$e},{no:2,name:"subscription",kind:"message",T:Xe},{no:3,name:"publish_tracks",kind:"message",T:Ke,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ei,repeated:!0},{no:5,name:"offer",kind:"message",T:$e},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Si,repeated:!0}])),Si=It.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Ei=It.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:It.getEnumType(Le)}])),Oi=It.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:It.getEnumType(Fe),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"}])),Ai=It.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),xi=It.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Ci=It.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:_i,repeated:!0}])),_i=It.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}])),Ri=It.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:It.getEnumType(Qt)}])),Ii=It.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:It.getEnumType(ji)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:We,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Je,oneof:"request"},{no:6,name:"mute",kind:"message",T:Ge,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:oi,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:ei,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:ii,oneof:"request"}])),ji=It.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"}]),Pi=It.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Di=It.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}])),Mi=It.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:Oe},{no:2,name:"connection_settings",kind:"message",T:Di},{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:Je,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:$e},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:It.getEnumType(Gt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ti}])),Ni=It.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:It.getEnumType(Ui)},{no:2,name:"join_request",kind:"scalar",T:12}])),Ui=It.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Li=It.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]));function Bi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Fi,qi,Vi,zi,Ji,Wi={exports:{}},Gi=(Fi||(Fi=1,qi=Wi.exports,Vi=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.apply(i,[t,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var 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 h(t){return function(){typeof console!==e&&(c.call(this),this[t].apply(this,arguments))}}function d(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)||h.apply(this,arguments)}function l(t,i){var o,a,h,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||d,l.getLevel=function(){return null!=h?h:null!=a?a:o},l.setLevel=function(t,i){return h=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){}}}(h),c.call(l)},l.setDefaultLevel=function(t){a=v(t),f()||l.setLevel(t,!1)},l.resetLevel=function(){h=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&&(h=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},Wi.exports?Wi.exports=Vi():qi.log=Vi()),Wi.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"}(zi||(zi={})),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"}(Ji||(Ji={}));let Qi=Gi.getLogger("livekit");function Hi(t){const e=Gi.getLogger(t);return e.setDefaultLevel(Qi.getLevel()),e}Object.values(Ji).map((t=>Gi.getLogger(t))),Qi.setDefaultLevel(zi.info);const Ki=Gi.getLogger("lk-e2ee"),Yi=7e3,$i=[0,300,1200,2700,4800,Yi,Yi,Yi,Yi,Yi];function Zi(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){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}c((n=n.apply(t,e||[])).next())}))}function Xi(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 tn,en={exports:{}},nn=function(){if(tn)return en.exports;tn=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)}en.exports=s,en.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 h=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=t,h.type=e,h.count=c.length,console&&console.warn&&console.warn(h)}return t}function h(){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 d(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},s=h.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=new 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=new 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=new 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 h=c.length,d=f(c,h);for(n=0;n<h;++n)i(d[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,d(this,t,e)),this},s.prototype.prependOnceListener=function(t,e){return o(e),this.prependListener(t,d(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):[]},en.exports}();let sn=!0,rn=!0;function on(t,e,i){const n=t.match(e);return n&&n.length>=i&&parseFloat(n[i],10)}function an(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.apply(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.apply(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 cn(t){return"boolean"!=typeof t?new Error("Argument type: "+typeof t+". Please use a boolean."):(sn=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function hn(t){return"boolean"!=typeof t?new Error("Argument type: "+typeof t+". Please use a boolean."):(rn=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function dn(){if("object"==typeof window){if(sn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function ln(t,e){rn&&console.warn(t+" is deprecated, please use "+e+" instead.")}function un(t){return"[object Object]"===Object.prototype.toString.call(t)}function fn(t){return un(t)?Object.keys(t).reduce((function(e,i){const n=un(t[i]),s=n?fn(t[i]):t[i],r=n&&!Object.keys(s).length;return void 0===s||r?e:Object.assign(e,{[i]:s})}),{}):t}function vn(t,e,i){e&&!i.has(e.id)&&(i.set(e.id,e),Object.keys(e).forEach((n=>{n.endsWith("Id")?vn(t,t.get(e[n]),i):n.endsWith("Ids")&&e[n].forEach((e=>{vn(t,t.get(e),i)}))})))}function mn(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&&vn(t,i,s)}))})),s}const pn=dn;function gn(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),pn("chrome: "+JSON.stringify(t)),s(t)}))}t.video=n(t.video)}return pn("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 bn(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function yn(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 an(t,"track",(t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t)))}function wn(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.apply(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.apply(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.apply(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 kn(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.apply(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=>mn(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.apply(this,[]);return t.forEach((t=>t._pc=this)),t}),an(t,"track",(t=>(t.receiver._pc=t.srcElement,t))),t.RTCRtpReceiver.prototype.getStats=function(){const t=this;return this._pc.getStats().then((e=>mn(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 Tn(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 Sn(t,e){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Tn(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.apply(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(new 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.apply(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.apply(this,[e=>{const i=r(this,e);t[0].apply(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(new 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 En(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 On(t,e){an(t,"negotiationneeded",(t=>{const i=t.target;if(!(e.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return t}))}var An=Object.freeze({__proto__:null,fixNegotiationNeeded:On,shimAddTrackRemoveTrack:Sn,shimAddTrackRemoveTrackWithNative:Tn,shimGetSendersWithDtmf:wn,shimGetUserMedia:gn,shimMediaStream:bn,shimOnTrack:yn,shimPeerConnection:En,shimSenderReceiverGetStats:kn});function xn(t,e){const i=t&&t.navigator,n=t&&t.MediaStreamTrack;if(i.getUserMedia=function(t,e,n){ln("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.apply(this,[i])}}}}function Cn(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 _n(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.apply(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 Rn(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.apply(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 In(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.apply(this,[]);return t.forEach((t=>t._pc=this)),t}),an(t,"track",(t=>(t.receiver._pc=t.srcElement,t))),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function jn(t){t.RTCPeerConnection&&!("removeStream"in t.RTCPeerConnection.prototype)&&(t.RTCPeerConnection.prototype.removeStream=function(t){ln("removeStream","removeTrack"),this.getSenders().forEach((e=>{e.track&&t.getTracks().includes(e.track)&&this.removeTrack(e)}))})}function Pn(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function Dn(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 Mn(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 Nn(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 Un(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 Ln=Object.freeze({__proto__:null,shimAddTransceiver:Dn,shimCreateAnswer:Un,shimCreateOffer:Nn,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:Mn,shimGetUserMedia:xn,shimOnTrack:Cn,shimPeerConnection:_n,shimRTCDataChannel:Pn,shimReceiverGetStats:In,shimRemoveStream:jn,shimSenderGetStats:Rn});function Bn(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=new 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 Fn(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 qn(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.apply(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.apply(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.apply(this,[t]);return i?(n.then(e,i),Promise.resolve()):n};e.setLocalDescription=a,a=function(t,e,i){const n=r.apply(this,[t]);return i?(n.then(e,i),Promise.resolve()):n},e.setRemoteDescription=a,a=function(t,e,i){const n=o.apply(this,[t]);return i?(n.then(e,i),Promise.resolve()):n},e.addIceCandidate=a}function Vn(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(zn(t))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(t,i,n){e.mediaDevices.getUserMedia(t).then(i,n)}.bind(e))}function zn(t){return t&&void 0!==t.video?Object.assign({},t,{video:fn(t.video)}):t}function Jn(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?(ln("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 Wn(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 Gn(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 Qn(t){"object"!=typeof t||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var Hn,Kn=Object.freeze({__proto__:null,shimAudioContext:Qn,shimCallbacksAPI:qn,shimConstraints:zn,shimCreateOfferLegacy:Gn,shimGetUserMedia:Vn,shimLocalStreamsAPI:Bn,shimRTCIceServerUrls:Jn,shimRemoteStreamsAPI:Fn,shimTrackEventTransceiver:Wn}),Yn={exports:{}},$n=(Hn||(Hn=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 h=e.matchPrefix(t,"a=ssrc-group:FID").map((t=>t.substring(17).split(" ").map((t=>parseInt(t,10)))));h.length>0&&h[0].length>1&&h[0][0]===a&&(c=h[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 d=e.matchPrefix(t,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((t=>{t.maxBitrate=d}))),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().toString().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}(Yn)),Yn.exports),Zn=Bi($n),Xn=s({__proto__:null,default:Zn},[$n]);function ts(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=Zn.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,an(t,"icecandidate",(e=>(e.candidate&&Object.defineProperty(e,"candidate",{value:new t.RTCIceCandidate(e.candidate),writable:"false"}),e)))}function es(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||an(t,"icecandidate",(t=>{if(t.candidate){const e=Zn.parseCandidate(t.candidate.candidate);"relay"===e.type&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[e.priority>>24])}return t}))}function is(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=Zn.splitSections(t.sdp);return e.shift(),e.some((t=>{const e=Zn.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=Zn.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?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function ns(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},an(t,"datachannel",(t=>(e(t.channel,t.target),t)))}function ss(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 rs(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 os(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 as(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.apply(this,[t]):("offer"===t.type?this.createOffer:this.createAnswer).apply(this).then((t=>e.apply(this,[t])))})}var cs=Object.freeze({__proto__:null,removeExtmapAllowMixed:rs,shimAddIceCandidateNullOrEmpty:os,shimConnectionState:ss,shimMaxMessageSize:is,shimParameterlessSetLocalDescription:as,shimRTCIceCandidate:ts,shimRTCIceCandidateRelayProtocol:es,shimSendThrowTypeError:ns});!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=dn,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(on(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===t.isSecureContext&&t.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(on(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(on(i.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype,e._safariVersion=on(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return e}(t),s={browserDetails:n,commonShim:cs,extractVersion:on,disableLog:cn,disableWarnings:hn,sdp:Xn};switch(n.browser){case"chrome":if(!An||!En||!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=An,os(t,n),as(t),gn(t,n),bn(t),En(t,n),yn(t),Sn(t,n),wn(t),kn(t),On(t,n),ts(t),es(t),ss(t),is(t,n),ns(t),rs(t,n);break;case"firefox":if(!Ln||!_n||!e.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Ln,os(t,n),as(t),xn(t,n),_n(t,n),Cn(t),jn(t),Rn(t),In(t),Pn(t),Dn(t),Mn(t),Nn(t),Un(t),ts(t),ss(t),is(t,n),ns(t);break;case"safari":if(!Kn||!e.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=Kn,os(t,n),as(t),Jn(t),Gn(t),qn(t),Bn(t),Fn(t),Wn(t),Vn(t),Qn(t),ts(t),es(t),is(t,n),ns(t),rs(t,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class hs 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 ds=/version\/(\d+(\.?_?\d+)+)/i;let ls;function us(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===ls||e){const t=fs.find((t=>{let{test:e}=t;return e.test(i)}));ls=null==t?void 0:t.describe(i)}return ls}const fs=[{test:/firefox|iceweasel|fxios/i,describe:t=>({name:"Firefox",version:vs(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ms(t)})},{test:/chrom|crios|crmo/i,describe:t=>({name:"Chrome",version:vs(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ms(t)})},{test:/safari|applewebkit/i,describe:t=>({name:"Safari",version:vs(ds,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:ms(t)})}];function vs(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 ms(t){return t.includes("mac os")?vs(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}class ps extends Error{constructor(t,e){super(e||"an error has occured"),this.name="LiveKitError",this.code=t}}var gs,bs,ys,ws,ks,Ts,Ss;!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"}(gs||(gs={}));class Es extends ps{constructor(t,e,i,n){super(1,t),this.name="ConnectionError",this.status=i,this.reason=e,this.context=n,this.reasonName=gs[e]}static notAllowed(t,e,i){return new Es(t,gs.NotAllowed,e,i)}static timeout(t){return new Es(t,gs.Timeout)}static leaveRequest(t,e){return new Es(t,gs.LeaveRequest,void 0,e)}static internal(t,e){return new Es(t,gs.InternalError,void 0,e)}static cancelled(t){return new Es(t,gs.Cancelled)}static serverUnreachable(t,e){return new Es(t,gs.ServerUnreachable,e)}static websocket(t,e,i){return new Es(t,gs.WebSocket,e,i)}static serviceNotFound(t,e){return new Es(t,gs.ServiceNotFound,void 0,e)}}class Os extends ps{constructor(t){super(21,null!=t?t:"device is unsupported"),this.name="DeviceUnsupportedError"}}class As extends ps{constructor(t){super(20,null!=t?t:"track is invalid"),this.name="TrackInvalidError"}}class xs extends ps{constructor(t){super(10,null!=t?t:"unsupported server"),this.name="UnsupportedServer"}}class Cs extends ps{constructor(t){super(12,null!=t?t:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class _s extends ps{constructor(t){super(13,null!=t?t:"unable to negotiate"),this.name="NegotiationError"}}class Rs extends ps{constructor(t,e){super(15,t),this.name="PublishTrackError",this.status=e}}class Is extends ps{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"}(bs||(bs={}));class js extends ps{constructor(t,e){super(16,t),this.name="DataStreamError",this.reason=e,this.reasonName=bs[e]}}class Ps extends ps{constructor(t){super(18,t),this.name="SignalReconnectError"}}!function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"}(ys||(ys={})),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}}(ys||(ys={}));class Ds{}Ds.setTimeout=function(){return setTimeout(...arguments)},Ds.setInterval=function(){return setInterval(...arguments)},Ds.clearTimeout=function(){return clearTimeout(...arguments)},Ds.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"}(ws||(ws={})),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"}(ks||(ks={})),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"}(Ts||(Ts={})),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"}(Ss||(Ss={}));class Ms{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 Ns=["vp8","h264"],Us=["vp8","h264","vp9","av1","h265"],Ls=function(t){return!!Ns.find((e=>e===t))};var Bs,Fs;!function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"}(Bs||(Bs={})),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}}(Fs||(Fs={}));const qs={h90:new Ms(160,90,9e4,20),h180:new Ms(320,180,16e4,20),h216:new Ms(384,216,18e4,20),h360:new Ms(640,360,45e4,20),h540:new Ms(960,540,8e5,25),h720:new Ms(1280,720,17e5,30),h1080:new Ms(1920,1080,3e6,30),h1440:new Ms(2560,1440,5e6,30),h2160:new Ms(3840,2160,8e6,30)},Vs={h120:new Ms(160,120,7e4,20),h180:new Ms(240,180,125e3,20),h240:new Ms(320,240,14e4,20),h360:new Ms(480,360,33e4,20),h480:new Ms(640,480,5e5,20),h540:new Ms(720,540,6e5,25),h720:new Ms(960,720,13e5,30),h1080:new Ms(1440,1080,23e5,30),h1440:new Ms(1920,1440,38e5,30)},zs={h360fps3:new Ms(640,360,2e5,3,"medium"),h360fps15:new Ms(640,360,4e5,15,"medium"),h720fps5:new Ms(1280,720,8e5,5,"medium"),h720fps15:new Ms(1280,720,15e5,15,"medium"),h720fps30:new Ms(1280,720,2e6,30,"medium"),h1080fps15:new Ms(1920,1080,25e5,15,"medium"),h1080fps30:new Ms(1920,1080,5e6,30,"medium"),original:new Ms(0,0,7e6,30,"medium")};function Js(t,e,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:h}=Xs(null!=t?t:{}),d=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&&(Ws(u.audio,e),null!==(n=(r=u.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||d)&&(u.audio.processor=null!=c?c:d)),u.video&&(Ws(u.video,i),null!==(s=(o=u.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(h||l)&&(u.video.processor=null!=h?h:l)),u}function Ws(t,e){return Object.keys(e).forEach((i=>{void 0===t[i]&&(t[i]=e[i])})),t}function Gs(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?Ws(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 Qs(){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=()=>Zi(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 Hs(t){return"audioinput"===t?nr.Source.Microphone:"videoinput"===t?nr.Source.Camera:nr.Source.Unknown}function Ks(t){return t===nr.Source.Microphone?"audioinput":t===nr.Source.Camera?"videoinput":void 0}function Ys(t){return t.split("/")[1].toLowerCase()}function $s(t){const e=[];return t.forEach((t=>{void 0!==t.track&&e.push(new Ke({cid:t.track.mediaStreamID,track:t.trackInfo}))})),e}function Zs(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?Zs(t.track):{})}}function Xs(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:(s=e,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function tr(t,e){return t.width*t.height<e.width*e.height}const er=[];var ir;!function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"}(ir||(ir={}));class nr extends nn.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=nr.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Qi,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=Hi(null!==(n=i.loggerName)&&void 0!==n?n:Ji.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=e,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=nr.Source.Unknown}get logContext(){var t;return Object.assign(Object.assign({},null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this)),Zs(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let e="audio";this.kind===nr.Kind.Video&&(e="video"),0===this.attachedElements.length&&this.kind===nr.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===e&&(er.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&er.splice(er.indexOf(t),1)),t||(t=document.createElement(e))),this.attachedElements.includes(t)||this.attachedElements.push(t),sr(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),n=i.some((t=>"audio"===t.kind));return t.play().then((()=>{this.emit(n?Ss.AudioPlaybackStarted:Ss.VideoPlaybackStarted)})).catch((e=>{"NotAllowedError"===e.name?this.emit(n?Ss.AudioPlaybackFailed:Ss.VideoPlaybackFailed,e):"AbortError"===e.name?Qi.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Qi.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(Ss.ElementAttached,t),t}detach(t){try{if(t){rr(this.mediaStreamTrack,t);const e=this.attachedElements.indexOf(t);return e>=0&&(this.attachedElements.splice(e,1),this.recycleElement(t),this.emit(Ss.ElementDetached,t)),t}const e=[];return this.attachedElements.forEach((t=>{rr(this.mediaStreamTrack,t),e.push(t),this.recycleElement(t),this.emit(Ss.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=Hi(t.loggerName)),t.loggerContextCb&&(this.loggerContextCb=t.loggerContextCb)}recycleElement(t){if(t instanceof HTMLAudioElement){let e=!0;t.pause(),er.forEach((t=>{t.parentElement||(e=!1)})),e&&er.push(t)}}handleAppVisibilityChanged(){return Zi(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==nr.Kind.Video||setTimeout((()=>this.attachedElements.forEach((t=>t.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){gr()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){gr()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function sr(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)),vr()&&e instanceof HTMLVideoElement||(e.autoplay=!0),e.muted=0===i.getAudioTracks().length,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==i&&(e.srcObject=i,(vr()||ur())&&e instanceof HTMLVideoElement&&setTimeout((()=>{e.srcObject=i,e.play().catch((()=>{}))}),0))}function rr(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 Ft.AUDIO;case e.Video:return Ft.VIDEO;default:return Ft.DATA}},t.kindFromProto=function(t){switch(t){case Ft.AUDIO:return e.Audio;case Ft.VIDEO:return e.Video;default:return e.Unknown}},t.sourceToProto=function(t){switch(t){case i.Camera:return qt.CAMERA;case i.Microphone:return qt.MICROPHONE;case i.ScreenShare:return qt.SCREEN_SHARE;case i.ScreenShareAudio:return qt.SCREEN_SHARE_AUDIO;default:return qt.UNKNOWN}},t.sourceFromProto=function(t){switch(t){case qt.CAMERA:return i.Camera;case qt.MICROPHONE:return i.Microphone;case qt.SCREEN_SHARE:return i.ScreenShare;case qt.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},t.streamStateFromProto=function(t){switch(t){case Be.ACTIVE:return n.Active;case Be.PAUSED:return n.Paused;default:return n.Unknown}}}(nr||(nr={}));const or="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ar(t){return new hs((e=>Ds.setTimeout(e,t)))}function cr(){return"addTransceiver"in RTCPeerConnection.prototype}function hr(){return"addTrack"in RTCPeerConnection.prototype}function dr(t){return"av1"===t||"vp9"===t}function lr(t){return!(!document||mr())&&(t||(t=document.createElement("audio")),"setSinkId"in t)}function ur(){var t;return"Firefox"===(null===(t=us())||void 0===t?void 0:t.name)}function fr(){const t=us();return!!t&&"Chrome"===t.name&&"iOS"!==t.os}function vr(){var t;return"Safari"===(null===(t=us())||void 0===t?void 0:t.name)}function mr(){const t=us();return"Safari"===(null==t?void 0:t.name)||"iOS"===(null==t?void 0:t.os)}function pr(){var t,e;return!!gr()&&(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 gr(){return"undefined"!=typeof document}function br(){return"ReactNative"==navigator.product}function yr(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function wr(t){return yr(t)?t.hostname.split(".")[0]:null}function kr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Tr(){if(!br())return;let t=kr();return t?t.platform:void 0}function Sr(){if(gr())return window.devicePixelRatio;if(br()){let t=kr();if(t)return t.devicePixelRatio}return 1}function Er(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 Or(t){for(const e of t)e.target.handleResize(e)}function Ar(t){for(const e of t)e.target.handleVisibilityChanged(e)}let xr=null;const Cr=()=>(xr||(xr=new ResizeObserver(Or)),xr);let _r=null;const Rr=()=>(_r||(_r=new IntersectionObserver(Ar,{root:null,rootMargin:"0px"})),_r);function Ir(){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 Pr(){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 Dr{get isResolved(){return this._isResolved}constructor(t,e){this._isResolved=!1,this.onFinally=e,this.promise=new Promise(((e,i)=>Zi(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 Mr(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 Nr(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function Ur(t){switch(t.reason){case gs.LeaveRequest:return t.context;case gs.Cancelled:return Wt.CLIENT_INITIATED;case gs.NotAllowed:return Wt.USER_REJECTED;case gs.ServerUnreachable:return Wt.JOIN_FAILURE;default:return Wt.UNKNOWN_REASON}}function Lr(t){return void 0!==t?Number(t):void 0}function Br(t){return void 0!==t?BigInt(t):void 0}function Fr(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function qr(t){return!!t&&t.kind==nr.Kind.Audio}function Vr(t){return!!t&&t.kind==nr.Kind.Video}function zr(t){return Fr(t)&&Vr(t)}function Jr(t){return Fr(t)&&qr(t)}function Wr(t){return!!t&&!t.isLocal}function Gr(t){return!!t&&!t.isLocal}function Qr(t){return Wr(t)&&Vr(t)}function Hr(t){return t.endsWith("/")?t:"".concat(t,"/")}function Kr(t,e){return t.pathname="".concat(Hr(t.pathname)).concat(e),t}function Yr(t){if("string"==typeof t)return Ve.fromJson(JSON.parse(t),{ignoreUnknownFields:!0});if(t instanceof ArrayBuffer)return Ve.fromBinary(new Uint8Array(t));throw new Error("could not decode websocket message: ".concat(typeof t))}const $r="lk_e2ee";var Zr,Xr,to,eo,io;function no(){return void 0!==window.RTCRtpScriptTransform}!function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"}(Zr||(Zr={})),function(t){t.KeyRatcheted="keyRatcheted"}(Xr||(Xr={})),function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"}(to||(to={})),function(t){t.Error="cryptorError"}(eo||(eo={})),function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"}(io||(io={}));class so extends nn.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(Qi.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(to.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(to.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(to.ParticipantEncryptionStatusChanged,s.enabled,t)}break;case"ratchetKey":this.keyProvider.emit(Zr.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=>{Qi.error("e2ee worker encountered an error:",{error:t.error}),this.emit(to.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||no()))throw new Os("tried to setup end-to-end encryption on an unsupported browser");if(Qi.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:Ki.getLevel()}};this.worker&&(Qi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(e))}}setParticipantCryptorEnabled(t,e){Qi.debug("set e2ee to ".concat(t," for participant ").concat(e)),this.postEnable(t,e)}setSifTrailer(t){t&&0!==t.length?this.postSifTrailer(t):Qi.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(Ts.RTPVideoMapUpdate,(t=>{this.postRTPMap(t)}))}setupEventListeners(t,e){t.on(ws.TrackPublished,((t,e)=>this.setParticipantCryptorEnabled(t.trackInfo.encryption!==ie.NONE,e.identity))),t.on(ws.ConnectionStateChanged,(e=>{e===Ea.Connected&&t.remoteParticipants.forEach((t=>{t.trackPublications.forEach((e=>{this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ie.NONE,t.identity)}))}))})).on(ws.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(ws.TrackSubscribed,((t,e,i)=>{this.setupE2EEReceiver(t,i.identity,e.trackInfo)})).on(ws.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(ks.LocalSenderCreated,((t,e)=>Zi(this,void 0,void 0,(function*(){this.setupE2EESender(e,t)})))),t.localParticipant.on(ks.LocalTrackPublished,(t=>{if(!Vr(t.track)||!mr())return;const e={kind:"updateCodec",data:{trackId:t.track.mediaStreamID,codec:Ys(t.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(e)})),e.on(Zr.SetKey,(t=>this.postKey(t))).on(Zr.RatchetRequest,((t,e)=>this.postRatchetRequest(t,e)))}encryptData(t){return Zi(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 Dr;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 Dr;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?Ys(i.mimeType):void 0)}}setupE2EESender(t,e){Fr(t)&&e?this.handleSender(e,t.mediaStreamID,void 0):e||Qi.warn("early return because sender is not ready")}handleReceiver(t,e,i,n){return Zi(this,void 0,void 0,(function*(){if(this.worker){if(no()&&!fr())t.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:e,codec:n});else{if($r 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:$r in t}},[r,s])}t[$r]=!0}}))}handleSender(t,e,i){var n;if(!($r 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(no()&&!fr())Qi.info("initialize script transform"),t.transform=new RTCRtpScriptTransform(this.worker,{kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:e,codec:i});else{Qi.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[$r]=!0}}}class ro{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new ro),this._instance}addFailedConnectionAttempt(t){var e;const i=wr(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,ar(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(t){const e=new URL(t),i=e&&wr(e);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(t){const e=new URL(t),i=e&&wr(e);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}ro._instance=null;const oo="default";class ao{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new ao),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return Zi(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=ao.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Qi.debug("awaiting getUserMedia promise");try{t?yield ao.userMediaPromiseMap.get(t):yield Promise.all(ao.userMediaPromiseMap.values())}catch(t){Qi.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!vr()||!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 Zi(this,void 0,void 0,(function*(){if(e!==oo)return e;const n=yield this.getDevices(t),s=n.find((t=>t.deviceId===oo));if(!s)return void Qi.warn("could not reliably determine default device");const r=n.find((t=>t.deviceId!==oo&&t.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;Qi.warn("could not reliably determine default device")}))}hasDeviceInUse(t){return t?ao.userMediaPromiseMap.has(t):ao.userMediaPromiseMap.size>0}}var co;ao.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ao.userMediaPromiseMap=new Map,function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"}(co||(co={}));class ho{constructor(){this.pendingTasks=new Map,this.taskMutex=new a,this.nextTaskIndex=0}run(t){return Zi(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:co.WAITING};this.pendingTasks.set(e.id,e);const i=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=co.RUNNING,yield t()}finally{e.status=co.COMPLETED,this.pendingTasks.delete(e.id),i()}}))}flush(){return Zi(this,void 0,void 0,(function*(){return this.run((()=>Zi(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}class lo{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 hs(((t,e)=>{const i=()=>{e(Es.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 hs(((t,e)=>{const i=()=>Zi(this,void 0,void 0,(function*(){const i=new hs((t=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",(e=>{t(e)}),{once:!0})})),n=yield hs.race([ar(250),i]);n?t(n):e(Es.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 uo=["syncState","trickle","offer","answer","simulate","leave"];var fo;!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"}(fo||(fo={}));class vo{get currentState(){return this.state}get isDisconnected(){return this.state===fo.DISCONNECTING||this.state===fo.DISCONNECTED}get isEstablishingConnection(){return this.state===fo.CONNECTING||this.state===fo.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=fo.DISCONNECTED,this.log=Qi,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=Hi(null!==(i=e.loggerName)&&void 0!==i?i:Ji.Signal),this.loggerContextCb=e.loggerContextCb,this.useJSON=t,this.requestQueue=new ho,this.queuedRequests=[],this.closingLock=new a,this.connectionLock=new a,this.state=fo.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 Zi(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=fo.CONNECTING,s.options=i,yield s.connect(t,e,i,n,r)}()}))}reconnect(t,e,i,n){return Zi(this,void 0,void 0,(function*(){if(this.options)return this.state=fo.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 Zi(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 Oe({sdk:Ae.JS,protocol:16,version:"2.17.0"});return br()&&(e.os=null!==(t=Tr())&&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",br()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),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.toString()),(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 Mi({clientInfo:e,connectionSettings:new Di({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 Ni({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}(e,a,i),h=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)})),Kr(i,"rtc")}(t,e);return i?n:Kr(n,"v1")}(t,c,r).toString(),d=(l=h,Kr(new URL(Nr(l)),"validate")).toString();var l;return new Promise(((t,e)=>Zi(s,void 0,void 0,(function*(){var s,r;try{let o=!1;const a=t=>Zi(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.toString():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(Es.cancelled(i))}));null==n||n.addEventListener("abort",a);const c=()=>{clearTimeout(l),null==n||n.removeEventListener("abort",a)},l=setTimeout((()=>{a(Es.timeout("room connection has timed out (signal)"))}),i.websocketTimeout),u=(t,e)=>{this.handleSignalConnected(t,l,e)},f=new URL(h);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 lo(h);try{this.ws.closed.then((t=>{var i;this.isEstablishingConnection&&e(Es.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===fo.CONNECTED&&this.handleOnClose(null!==(i=t.reason)&&void 0!==i?i:"Unexpected WS error"))})).catch((t=>{this.isEstablishingConnection&&e(Es.internal("Websocket error during a (re)connection attempt: ".concat(t)))}));const n=yield this.ws.opened.catch((t=>Zi(this,void 0,void 0,(function*(){if(this.state===fo.CONNECTED)this.handleWSError(t),e(t);else{this.state=fo.DISCONNECTED,clearTimeout(l);const i=yield this.handleConnectionError(t,d);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 Es.internal("no message received as first message");const c=Yr(a.value),h=this.validateFirstMessage(c,null!==(s=i.reconnect)&&void 0!==s&&s);if(!h.isValid)return void e(h.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,h.shouldProcessFirstMessage?c:void 0),t(h.response)}catch(t){e(t)}finally{c()}}finally{o()}}))))}()}))}startReadingLoop(t,e){return Zi(this,void 0,void 0,(function*(){for(e&&this.handleSignalResponse(e);;){this.signalLatency&&(yield ar(this.signalLatency));const{done:e,value:i}=yield t.read();if(e)break;const n=Yr(i);this.handleSignalResponse(n)}}))}close(){return Zi(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([fo.DISCONNECTING||fo.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=fo.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,ar(250)])}}catch(e){t.log.debug("websocket error while closing",Object.assign(Object.assign({},t.logContext),{error:e}))}finally{e&&(t.state=fo.DISCONNECTED),n()}}()}))}sendOffer(t,e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:t.sdp})),this.sendRequest({case:"offer",value:po(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:po(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 We({candidateInit:JSON.stringify(t),target:e})})}sendMuteTrack(t,e){return this.sendRequest({case:"mute",value:new Ge({sid:t,muted:e})})}sendAddTrack(t){return this.sendRequest({case:"addTrack",value:t})}sendUpdateLocalMetadata(t,e){return Zi(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 oi({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 ri({trackSid:t,layers:e})})}sendUpdateSubscriptionPermissions(t,e){return this.sendRequest({case:"subscriptionPermission",value:new yi({allParticipants:t,trackPermissions:e})})}sendSimulateScenario(t){return this.sendRequest({case:"simulate",value:t})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:x.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ai({timestamp:x.parse(Date.now()),rtt:x.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(t,e){return this.sendRequest({case:"updateAudioTrack",value:new ei({trackSid:t,features:e})})}sendLeave(){return this.sendRequest({case:"leave",value:new ni({reason:Wt.CLIENT_INITIATED,action:si.DISCONNECT})})}sendRequest(t){return Zi(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=uo.indexOf(t.case)>=0;return Qi.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}(t);if(n&&e.state===fo.RECONNECTING)return void e.queuedRequests.push((()=>Zi(e,void 0,void 0,(function*(){yield this.sendRequest(t,!0)}))));if(i||(yield e.requestQueue.flush()),e.signalLatency&&(yield ar(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 qe({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=mo(n.value);this.onAnswer&&this.onAnswer(t,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const t=mo(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.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"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 Zi(this,void 0,void 0,(function*(){if(this.state===fo.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=Ds.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&&Ds.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Ds.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&&Ds.clearInterval(this.pingInterval)}handleSignalConnected(t,e,i){this.state=fo.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===fo.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:Es.leaveRequest("Received leave request while trying to (re)connect",t.message.value.reason)}:e?{isValid:!1,error:Es.internal("Unexpected first message")}:{isValid:!1,error:Es.internal("did not receive join response, got ".concat(null===(o=t.message)||void 0===o?void 0:o.case," instead"))}}handleConnectionError(t,e){return Zi(this,void 0,void 0,(function*(){try{const i=yield fetch(e);switch(i.status){case 404:return Es.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield i.text();return Es.notAllowed(t,i.status)}return t instanceof Es?t:Es.internal("Encountered unknown websocket error during connection: ".concat(t),{status:i.status,statusText:i.statusText})}catch(t){return t instanceof Es?t:Es.serverUnreachable(t instanceof Error?t.message:"server was not reachable")}}))}}function mo(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 po(t,e){return new $e({sdp:t.sdp,type:t.type,id:e})}class go{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 bo{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 yo,wo,ko,To,So,Eo={},Oo={},Ao={exports:{}};function xo(){if(yo)return Ao.exports;yo=1;var t=Ao.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:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(t){return"imageattr:%s %s %s"+(t.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(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")}))})),Ao.exports}function Co(){return wo||(wo=1,function(t){var e=function(t){return String(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=xo(),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.toString().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}}))}))}}(Oo)),Oo}function _o(){if(To)return ko;To=1;var t=xo(),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 String(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 ko=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"},ko}var Ro=function(){if(So)return Eo;So=1;var t=Co(),e=_o(),i=xo();return Eo.grammar=i,Eo.write=e,Eo.parse=t.parse,Eo.parseParams=t.parseParams,Eo.parseFmtpConfig=t.parseFmtpConfig,Eo.parsePayloads=t.parsePayloads,Eo.parseRemoteCandidates=t.parseRemoteCandidates,Eo.parseImageAttributes=t.parseImageAttributes,Eo.parseSimulcastStreamList=t.parseSimulcastStreamList,Eo}();function Io(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,h=Date.now(),d=[];function l(){if(void 0!==c){var t=Date.now()-h;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,h=Date.now(),!o){var n=t.apply(i,e);a&&a(n),d.forEach((function(t){return(0,t.resolve)(n)})),d=[]}}),l()),c){var u=t.apply(i,e);return a&&a(u),n(u)}d.push({resolve:n,reject:s})}))};return u.cancel=function(t){void 0!==r&&clearTimeout(r),d.forEach((function(e){return(0,e.reject)(t)})),d=[]},u}const jo="negotiationStarted",Po="negotiationComplete",Do="rtpVideoPayloadTypes";class Mo extends nn.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=Qi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Io((t=>Zi(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=Hi(null!==(i=e.loggerName)&&void 0!==i?i:Ji.PCTransport),this.loggerOptions=e,this.config=t,this._pc=this.createPC(),this.offerLock=new a}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 Zi(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 Zi(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=Ro.parse(null!==(e=t.sdp)&&void 0!==e?e:"");let r=0;return s.media.forEach((t=>{var e;const s=Lo(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=Ro.parse(null!==(i=t.sdp)&&void 0!==i?i:"");e.media.forEach((t=>{const e=Lo(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=Ro.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(Po),t.sdp)&&Ro.parse(t.sdp).media.forEach((t=>{"video"===t.type&&this.emit(Do,t.rtp)})),!0}))}createAndSendOffer(t){return Zi(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=Ro.parse(null!==(e=n.sdp)&&void 0!==e?e:"");if(s.media.forEach((t=>{Uo(t),"audio"===t.type?No(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(dr(e.codec)&&!vr()&&this.ensureVideoDDExtensionForSVC(t,s),!dr(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,Ro.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}}))}createAndSetAnswer(){return Zi(this,void 0,void 0,(function*(){var t;const e=yield this.pc.createAnswer(),i=Ro.parse(null!==(t=e.sdp)&&void 0!==t?t:"");return i.media.forEach((t=>{Uo(t),"audio"===t.type&&No(t,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(e,Ro.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 Cs("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 Cs("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 Zi(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 Zi(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 _s(n)}}))}ensureVideoDDExtensionForSVC(t,e){var i,n;if(!(null===(i=t.ext)||void 0===i?void 0:i.some((t=>t.uri===or)))){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:or})}}}function No(t,e,i){const n=Lo(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 Uo(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 Lo(t){return"number"==typeof t?t.toFixed(0):t}const Bo="vp8",Fo={audioPreset:Fs.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:zs.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Bo,backupCodec:!0,preConnectBuffer:!1},qo={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Vo={deviceId:{ideal:"default"},resolution:qs.h720.resolution},zo={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(t){this._retryDelays=void 0!==t?[...t]:$i}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},Jo={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Wo;!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"}(Wo||(Wo={}));class Go{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=Jo.peerConnectionTimeout,this.log=Qi,this.updateState=()=>{var t,e;const i=this.state,n=this.requiredTransports.map((t=>t.getConnectionState()));n.every((t=>"connected"===t))?this.state=Wo.CONNECTED:n.some((t=>"failed"===t))?this.state=Wo.FAILED:n.some((t=>"connecting"===t))?this.state=Wo.CONNECTING:n.every((t=>"closed"===t))?this.state=Wo.CLOSED:n.some((t=>"closed"===t))?this.state=Wo.CLOSING:n.every((t=>"new"===t))&&(this.state=Wo.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(Wo[i]," to ").concat(Wo[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=Hi(null!==(n=i.loggerName)&&void 0!==n?n:Ji.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==e,this.isSubscriberConnectionRequired="subscriber-primary"===e,this.publisher=new Mo(t,i),this._mode=e,"publisher-only"!==e&&(this.subscriber=new Mo(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,Le.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,Le.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=Wo.NEW,this.connectionLock=new a,this.remoteOfferLock=new a}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 Zi(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 Zi(this,void 0,void 0,(function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(t,e){return Zi(this,void 0,void 0,(function*(){var i;e===Le.PUBLISHER?yield this.publisher.addIceCandidate(t):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(t)}))}createSubscriberAnswerFromOffer(t,e){return Zi(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().toString()}));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 Zi(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 Zi(this,void 0,void 0,(function*(){return new hs(((e,i)=>Zi(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i(new _s("negotiation timed out"))}),this.peerConnectionTimeout);t.signal.addEventListener("abort",(()=>{clearTimeout(n),i(new _s("negotiation aborted"))})),this.publisher.once(jo,(()=>{t.signal.aborted||this.publisher.once(Po,(()=>{clearTimeout(n),e()}))})),yield this.publisher.negotiate((t=>{clearTimeout(n),t instanceof Error?i(t):i(new Error(String(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===Le.PUBLISHER||t===Le.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 Zi(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)=>Zi(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Ds.clearTimeout(r),s(Es.cancelled("room connection has been cancelled"))};(null==e?void 0:e.signal.aborted)&&i(),null==e||e.signal.addEventListener("abort",i);const r=Ds.setTimeout((()=>{null==e||e.signal.removeEventListener("abort",i),s(Es.internal("could not establish pc connection"))}),n);for(;this.state!==Wo.CONNECTED;)if(yield ar(50),null==e?void 0:e.signal.aborted)return void s(Es.cancelled("room connection has been cancelled"));Ds.clearTimeout(r),null==e||e.signal.removeEventListener("abort",i),t()}))))}()}))}}class Qo{static fetchRegionSettings(t,e,i){return Zi(this,void 0,void 0,(function*(){const n=yield Qo.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?Es.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):Es.internal("Could not fetch region settings: ".concat(n.statusText))}catch(t){throw t instanceof Es?t:(null==i?void 0:i.aborted)?Es.cancelled("Region fetching was aborted"):Es.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 Zi(this,void 0,void 0,(function*(){const n=Qo.settingsTimeouts.get(t.hostname);clearTimeout(n),Qo.settingsTimeouts.set(t.hostname,setTimeout((()=>Zi(this,void 0,void 0,(function*(){try{const i=yield Qo.fetchRegionSettings(t,e);Qo.updateCachedRegionSettings(t,e,i)}catch(n){if(n instanceof Es&&n.reason===gs.NotAllowed)return void Qi.debug("token is not valid, cancelling auto region refresh");Qi.debug("auto refetching of region settings failed",{error:n}),Qo.scheduleRefetch(t,e,i)}}))),i))}))}static updateCachedRegionSettings(t,e,i){Qo.cache.set(t.hostname,i),Qo.scheduleRefetch(t,e,i.maxAgeInMs)}static stopRefetch(t){const e=Qo.settingsTimeouts.get(t);e&&(clearTimeout(e),Qo.settingsTimeouts.delete(t))}static scheduleCleanup(t){let e=Qo.connectionTrackers.get(t);e&&(e.cleanupTimeout&&clearTimeout(e.cleanupTimeout),e.cleanupTimeout=setTimeout((()=>{const e=Qo.connectionTrackers.get(t);e&&0===e.connectionCount&&(Qi.debug("stopping region refetch after disconnect delay",{hostname:t}),Qo.stopRefetch(t)),e&&(e.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(t){const e=Qo.connectionTrackers.get(t);(null==e?void 0:e.cleanupTimeout)&&(clearTimeout(e.cleanupTimeout),e.cleanupTimeout=void 0)}notifyConnected(){const t=this.serverUrl.hostname;let e=Qo.connectionTrackers.get(t);e||(e={connectionCount:0},Qo.connectionTrackers.set(t,e)),e.connectionCount++,Qo.cancelCleanup(t)}notifyDisconnected(){const t=this.serverUrl.hostname,e=Qo.connectionTrackers.get(t);e&&(e.connectionCount=Math.max(0,e.connectionCount-1),0===e.connectionCount&&Qo.scheduleCleanup(t))}constructor(t,e){this.attemptedRegions=[],this.serverUrl=new URL(t),this.token=e}updateToken(t){this.token=t}isCloud(){return yr(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return Zi(this,void 0,void 0,(function*(){return Qo.fetchRegionSettings(this.serverUrl,this.token,t)}))}getNextBestRegionUrl(t){return Zi(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let e=Qo.cache.get(this.serverUrl.hostname);(!e||Date.now()-e.updatedAtInMs>e.maxAgeInMs)&&(e=yield this.fetchRegionSettings(t),Qo.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),Qi.debug("next region: ".concat(t.region)),t.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){Qo.updateCachedRegionSettings(this.serverUrl,this.token,t)}}Qo.cache=new Map,Qo.settingsTimeouts=new Map,Qo.connectionTrackers=new Map,Qo.fetchLock=new a;class Ho extends Error{constructor(t,e,i){super(e),this.code=t,this.message=Yo(e,Ho.MAX_MESSAGE_BYTES),this.data=i?Yo(i,Ho.MAX_DATA_BYTES):void 0}static fromProto(t){return new Ho(t.code,t.message,t.data)}toProto(){return new ke({code:this.code,message:this.message,data:this.data})}static builtIn(t,e){return new Ho(Ho.ErrorCode[t],Ho.ErrorMessage[t],e)}}function Ko(t){return(new TextEncoder).encode(t).length}function Yo(t,e){if(Ko(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)}Ho.MAX_MESSAGE_BYTES=256,Ho.MAX_DATA_BYTES=15360,Ho.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},Ho.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 $o=2e3;function Zo(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 Xo="undefined"!=typeof MediaRecorder,ta=Xo?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class ea extends ta{constructor(t,e){if(!Xo)throw new 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=>Zi(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 new 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 ia extends nr{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=Io((()=>Zi(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Zi(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(Ss.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new a,this.pauseUpstreamLock=new a,this.trackChangeLock=new a,this.trackChangeLock.lock().then((e=>Zi(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!==nr.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 Zi(this,void 0,void 0,(function*(){var i;if(t===this._mediaStreamTrack&&!e)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((t=>{rr(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&&(sr(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=>{sr(null!=n?n:t,e)})))}))}waitForDimensions(){return Zi(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===nr.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=us())||void 0===i?void 0:i.os)&&(yield ar(10));const n=Date.now();for(;Date.now()-n<e;){const e=t.dimensions;if(e)return e;yield ar(50)}throw new As("unable to get track dimensions after timeout")}()}))}setDeviceId(t){return Zi(this,void 0,void 0,(function*(){return this._constraints.deviceId===t&&this._mediaStreamTrack.getSettings().deviceId===Mr(t)||(this._constraints.deviceId=t,!!this.isMuted||(yield this.restartTrack(),Mr(t)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Zi(this,arguments,void 0,(function(){var t=this;let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(t.source===nr.Source.ScreenShare)return;const{deviceId:i,groupId:n}=t._mediaStreamTrack.getSettings(),s=t.kind===nr.Kind.Audio?"audioinput":"videoinput";return e?ao.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return Zi(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Zi(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(t,e){return Zi(this,void 0,void 0,(function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new As("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 Zi(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===nr.Kind.Video?s.video=!e&&!i||{deviceId:e,facingMode:i}:s.audio=!e||Object.assign({deviceId:e},n),this.attachedElements.forEach((t=>{rr(this.mediaStreamTrack,t)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===nr.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(Ss.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?Ss.Muted:Ss.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 Zi(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),pr()&&(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 Zi(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(Ss.UpstreamPaused,this);const e=us();if("Safari"===(null==e?void 0:e.name)&&Er(e.version,"12.0")<0)throw new Os("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 Zi(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(Ss.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 Zi(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 Zi(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(sr(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&&(rr(e._mediaStreamTrack,t),sr(e.processor.processedTrack,t));yield null===(n=e.sender)||void 0===n?void 0:n.replaceTrack(e.processor.processedTrack)}e.emit(Ss.TrackProcessorUpdate,e.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Zi(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 Zi(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(Ss.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(Xo)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 ea(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 na extends ia{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,e){let i=arguments.length>3?arguments[3]:void 0;super(t,nr.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=()=>Zi(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=Zo(t,this.prevStats)),this.prevStats=t})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Ss.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Ss.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return Zi(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===nr.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 Zi(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!==Mr(this._constraints.deviceId);return this.source!==nr.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 Zi(this,void 0,void 0,(function*(){let e;if(t){const i=Gs({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 Zi(this,void 0,void 0,(function*(){const i=yield e.restart.call(this,t);return this.checkForSilence(),i}))}startMonitor(){gr()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),$o)))}setProcessor(t){return Zi(this,void 0,void 0,(function*(){var e;const i=yield this.trackChangeLock.lock();try{if(!br()&&!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(Ss.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(t){this.audioContext=t}getSenderStats(){return Zi(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 Zi(this,void 0,void 0,(function*(){const t=yield function(t){return Zi(this,arguments,void 0,(function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Qs();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([t.mediaStreamTrack])).connect(n),yield ar(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(Ss.AudioSilenceDetected)),t}))}}const sa=Object.values(qs),ra=Object.values(Vs),oa=Object.values(zs),aa=[qs.h180,qs.h360],ca=[Vs.h180,Vs.h360],ha=["q","h","f"];function da(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,h=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 oa;const n=e>i?e/i:i/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?sa:ra}(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,h),Qi.debug("using video encoding",o));const d=o.maxFramerate,l=new Ms(e,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&dr(h)){const t=new va(c),e=[];if(t.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=us();if(mr()||br()||"Chrome"===(null==i?void 0:i.name)&&Er(null==i?void 0:i.version,"113")<0){const n="h"==t.suffix?2:3,s=function(t){return t||(t=us()),"Safari"===(null==t?void 0:t.name)&&Er(t.version,"18.3")>0||"iOS"===(null==t?void 0:t.os)&&!!(null==t?void 0:t.osVersion)&&Er(t.osVersion,"18.3")>0}(i);for(let i=0;i<t.spatial;i+=1)e.push({rid:ha[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),Qi.debug("using svc encoding",{encodings:e}),e}if(!a)return[o];let u,f=[];if(f=t?null!==(s=fa(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:la(t,l):null!==(r=fa(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:la(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 ua(e,i,[t,u,l],d);if(n>=480)return ua(e,i,[t,l],d)}return ua(e,i,[l])}function la(t,e){if(t)return[{scaleResolutionDownBy:2,fps:(i=e).encoding.maxFramerate}].map((t=>{var e,n;return new Ms(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(e=i.encoding.maxFramerate)&&void 0!==e?e:30)/(null!==(n=t.fps)&&void 0!==n?n:30))))),t.fps,i.encoding.priority)}));var i;const{width:n,height:s}=e,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?aa:ca}function ua(t,e,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=ha.length)return;const o=Math.min(t,e),a={rid:ha[r],scaleResolutionDownBy:Math.max(1,o/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const h=ur()||0===r;i.encoding.priority&&h&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)})),br()&&"ios"===Tr()){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,Qi.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Qi.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(t)),i.maxFramerate=t)}))}return s}function fa(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 va{constructor(t){const e=t.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!e)throw new 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 ma extends ia{get sender(){return this._sender}set sender(t){this._sender=t,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,e){super(t,nr.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=()=>Zi(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(Ss.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+=Zo(e,s)})),this._currentBitrate=t}this.prevStats=e})),this.senderLock=new a}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(t){var e;if(this.signalClient=t,!gr())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()}),$o))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((t=>{t.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const t=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Zi(this,void 0,void 0,(function*(){var e,i,n,s;yield t.pauseUpstream.call(this);try{for(var r,o=!0,a=Xi(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 Zi(this,void 0,void 0,(function*(){var e,i,n,s;yield t.resumeUpstream.call(this);try{for(var r,o=!0,a=Xi(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 Zi(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!==nr.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 Zi(this,void 0,void 0,(function*(){const e=yield this.muteLock.lock();try{return this.isMuted?(this.source!==nr.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 Zi(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=ir.LOW;i<=ir.HIGH;i+=1)e.push(new vi({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(dr(this.codec),e)}restartTrack(t){return Zi(this,void 0,void 0,(function*(){var e,i,n,s;let r;if(t){const e=Gs({video:t});"boolean"!=typeof e.video&&(r=e.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var o,a=!0,c=Xi(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 Zi(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 h,d=!0,l=Xi(i.simulcastCodecs.values());!(s=(h=yield l.next()).done);d=!0){d=!1;const t=h.value;yield null===(c=t.sender)||void 0===c?void 0:c.replaceTrack(i.processor.processedTrack)}}catch(t){r={error:t}}finally{try{d||s||!(o=l.return)||(yield o.call(l))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(t){return Zi(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 Zi(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(dr(t[0].codec),t[0].qualities),[];this.subscribedCodecs=t;const a=[];try{for(e=!0,i=Xi(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 pa(e.sender,e.encodings,t.qualities,this.senderLock,dr(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(dr(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 Zi(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 pa(this.sender,this.encodings,e,this.senderLock,t,this.log,this.logContext)))}))}prioritizePerformance(){return Zi(this,void 0,void 0,(function*(){if(!this.sender)throw new 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&&dr(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 Zi(this,void 0,void 0,(function*(){yield t.handleAppVisibilityChanged.call(this),pr()&&this.isInBackground&&this.source===nr.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function pa(t,e,i,n,s,r,o){return Zi(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 h=ga(a),d=i.find((t=>t.quality===h));d&&t.active!==d.enabled&&(c=!0,t.active=d.enabled,r.debug("setting layer ".concat(d.quality," to ").concat(t.active?"enabled":"disabled"),o),ur()&&(d.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 ga(t){switch(t){case"f":default:return ir.HIGH;case"h":return ir.MEDIUM;case"q":return ir.LOW}}function ba(t,e,i,n){if(!i)return[new re({quality:ir.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(n){const n=new va(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 re({quality:Math.min(ir.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=ga(null!==(s=i.rid)&&void 0!==s?s:"");return new re({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 ya="_lossy",wa="_reliable",ka="leave-reconnect";var Ta,Sa,Ea,Oa;!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"}(Ta||(Ta={}));class Aa extends nn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var e;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Jo.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ta.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=Qi,this.reliableDataSequence=1,this.reliableMessageBuffer=new go,this.reliableReceivedState=new bo(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=t=>Zi(this,[t],void 0,(function(t){var e=this;let{channel:i}=t;return function*(){if(i){if(i.label===wa)e.reliableDCSub=i;else{if(i.label!==ya)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=>Zi(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=ae.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(Ts.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=de.fromBinary(t.payload),i=new ae({value:e.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&xa(i,i.value.value),this.emit(Ts.DataPacketReceived,i,a.value.value.encryptionType)}else"user"===(null===(r=a.value)||void 0===r?void 0:r.case)&&xa(a,a.value.value),this.emit(Ts.DataPacketReceived,a,ie.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?ce.LOSSY:ce.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===ka&&(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=Ds.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(Ts.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((t,e)=>{this.pcState===Ta.Connected&&t();const i=()=>{this.off(Ts.Disconnected,n),t()},n=()=>{this.off(Ts.Restarted,i),e()};this.once(Ts.Restarted,i),this.once(Ts.Disconnected,n)})),this.updateAndEmitDCBufferStatus=t=>{if(t===ce.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(Ts.DCBufferStatusChanged,e,t))},this.isBufferStatusLow=t=>{const e=this.dataChannelForKind(t);if(e)return e.bufferedAmount<=e.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>Zi(this,void 0,void 0,(function*(){this.url&&(yield fetch(Nr(this.url),{method:"HEAD"}).then((t=>t.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===fo.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===fo.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Gt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>Zi(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(Nr(this.url),{method:"HEAD"}),ar(4e3).then((()=>Promise.reject()))])}catch(t){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=Hi(null!==(e=t.loggerName)&&void 0!==e?e:Ji.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new vo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new a,this.dataProcessLock=new a,this.dcBufferStatus=new Map([[ce.LOSSY,!0],[ce.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(Ts.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(Ts.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(Ts.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(Ts.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(Ts.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(Ts.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(Ts.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(Ts.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 Zi(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=>{Qi.error(t,s.logContext)})),s.registerOnLineListener(),s.clientConfiguration=o.clientConfiguration,s.emit(Ts.SignalConnected,o),o}catch(o){if(o instanceof Es)if(o.reason===gs.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===gs.ServiceNotFound)return s.log.warn("Initial connection failed: ".concat(o.message," – Retrying")),s.join(t,e,i,n,!0);throw o}}()}))}close(){return Zi(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(Ts.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return Zi(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 go,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 Zi(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(t){if(this.pendingTrackResolvers[t.cid])throw new As("a track with the same ID has already been published");return new Promise(((e,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[t.cid],i(Es.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(new 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 Zi(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 Zi(this,void 0,void 0,(function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==Wo.NEW)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const s=this.makeRTCConfiguration(t);var r;this.pcManager=new Go(s,e?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(Ts.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)=>Zi(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===Wo.CONNECTED){const e=this.pcState===Ta.New;this.pcState=Ta.Connected,e&&this.emit(Ts.Connected,t)}else e===Wo.FAILED&&(this.pcState!==Ta.Connected&&this.pcState!==Ta.Reconnecting||(this.pcState=Ta.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?Gt.RR_SUBSCRIBER_FAILED:Gt.RR_PUBLISHER_FAILED)));const s=this.client.isDisconnected||this.client.currentState===fo.RECONNECTING,r=[Wo.FAILED,Wo.CLOSING,Wo.CLOSED].includes(e);s&&r&&!this._isClosed&&this.emit(Ts.Offline)})),this.pcManager.onTrack=t=>{0!==t.streams.length&&this.emit(Ts.MediaTrackAdded,t.track,t.streams[0],t.receiver)},void 0!==(r=null===(n=t.serverInfo)||void 0===n?void 0:n.protocol)&&r>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=(t,e,i)=>Zi(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)=>Zi(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(Ts.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(Ts.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(Ts.RemoteMute,t,e)},this.client.onSubscribedQualityUpdate=t=>{this.emit(Ts.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(Ts.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",Gt.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 si.DISCONNECT:this.emit(Ts.Disconnected,null==t?void 0:t.reason),this.close();break;case si.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ka);break;case si.RESUME:this.handleDisconnect(ka)}}}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===Jt.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(ya,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(wa,{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(ce.LOSSY);t&&(t.bufferedAmountLowThreshold=Math.min(Math.max(this.lossyDataStatByterate/10,8192),262144))}),1e3))}createSender(t,e,i){return Zi(this,void 0,void 0,(function*(){if(cr())return yield this.createTransceiverRTCRtpSender(t,e,i);if(hr())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(t.mediaStreamTrack);throw new Cs("Required webRTC APIs not supported on this device")}))}createSimulcastSender(t,e,i,n){return Zi(this,void 0,void 0,(function*(){if(cr())return this.createSimulcastTransceiverSender(t,e,i,n);if(hr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(t.mediaStreamTrack);throw new Cs("Cannot stream on this device")}))}createTransceiverRTCRtpSender(t,e,i){return Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Cs("publisher is closed");const n=[];t.mediaStream&&n.push(t.mediaStream),Vr(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 Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Cs("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 Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Cs("publisher is closed");return this.pcManager.addPublisherTrack(t)}))}attemptReconnect(t){return Zi(this,void 0,void 0,(function*(){var e,i,n;if(!this._isClosed)if(this.attemptingReconnect)Qi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(e=this.clientConfiguration)||void 0===e?void 0:e.resumeConnection)!==Jt.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:Wo.NEW)!==Wo.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 Cs?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof Ps||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",Gt.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(Ts.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 Zi(this,void 0,void 0,(function*(){var e,i,n;try{if(!this.url||!this.token)throw new Cs("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Ts.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 Ps;i=yield this.join(null!=t?t:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(t){if(t instanceof Es&&t.reason===gs.NotAllowed)throw new Cs("could not reconnect, token might be expired");throw new Ps}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Ts.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==fo.CONNECTED)throw new Ps("Signal connection got severed during reconnect");null===(e=this.regionUrlProvider)||void 0===e||e.resetAttempts(),this.emit(Ts.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 Zi(this,void 0,void 0,(function*(){var e;if(!this.url||!this.token)throw new Cs("could not reconnect, url or token not saved");if(!this.pcManager)throw new Cs("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Ts.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 Es&&t.reason===gs.NotAllowed)throw new Cs("could not reconnect, token might be expired");if(t instanceof Es&&t.reason===gs.LeaveRequest)throw t;throw new Ps(e)}if(this.emit(Ts.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,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==fo.CONNECTED)throw new Ps("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(Ts.Resumed)}))}waitForPCInitialConnection(t,e){return Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Cs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(e,t)}))}waitForPCReconnected(){return Zi(this,void 0,void 0,(function*(){this.pcState=Ta.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ar(2e3),!this.pcManager)throw new Cs("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ta.Connected}catch(t){throw this.pcState=Ta.Disconnected,Es.internal("could not establish PC connection, ".concat(t.message))}}))}publishRpcResponse(t,e,i,n){return Zi(this,void 0,void 0,(function*(){const s=new ae({destinationIdentities:[t],kind:ce.RELIABLE,value:{case:"rpcResponse",value:new we({requestId:e,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,ce.RELIABLE)}))}publishRpcAck(t,e){return Zi(this,void 0,void 0,(function*(){const i=new ae({destinationIdentities:[t],kind:ce.RELIABLE,value:{case:"rpcAck",value:new ye({requestId:e})}});yield this.sendDataPacket(i,ce.RELIABLE)}))}sendDataPacket(t,e){return Zi(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 de({value:t.value})}(t);if(e){const i=yield this.e2eeManager.encryptData(e.toBinary());t.value={case:"encryptedPacket",value:new he({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}e===ce.RELIABLE&&(t.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=t.toBinary(),n=this.dataChannelForKind(e);if(n){if(e===ce.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 Zi(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(ce.RELIABLE);const e=this.dataChannelForKind(ce.RELIABLE);e&&(this.reliableMessageBuffer.popToSequence(t),this.reliableMessageBuffer.getAll().forEach((t=>{e.send(t.data)}))),this.updateAndEmitDCBufferStatus(ce.RELIABLE)}))}waitForBufferStatusLow(t){return new hs(((e,i)=>Zi(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(t))e();else{const n=()=>i(new Cs("engine closed"));for(this.once(Ts.Closing,n);!this.dcBufferStatus.get(t);)yield ar(10);this.off(Ts.Closing,n),e()}}))))}ensureDataTransportConnected(t){return Zi(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 Cs("PC manager is closed");const s=i?e.pcManager.subscriber:e.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw Es.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=>{Qi.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 ar(50)}throw Es.internal("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))}()}))}ensurePublisherConnected(t){return Zi(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(t,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===Wo.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Zi(this,void 0,void 0,(function*(){return new hs(((t,e)=>Zi(this,void 0,void 0,(function*(){if(!this.pcManager)return void e(new _s("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 _s("cannot negotiate on closed engine")),this.on(Ts.Closing,n),this.pcManager.publisher.once(Do,(t=>{const e=new Map;t.forEach((t=>{const i=t.codec.toLowerCase();Us.includes(i)&&e.set(t.payload,i)})),this.emit(Ts.RTPVideoMapUpdate,e)}));try{yield this.pcManager.negotiate(i),t()}catch(t){t instanceof _s&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Gt.RR_UNKNOWN),t instanceof Error?e(t):e(new Error(String(t)))}finally{this.off(Ts.Closing,n)}}))))}))}dataChannelForKind(t,e){if(e){if(t===ce.LOSSY)return this.lossyDCSub;if(t===ce.RELIABLE)return this.reliableDCSub}else{if(t===ce.LOSSY)return this.lossyDC;if(t===ce.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(),h=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getLocalDescription(),d=null===(r=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===r||r,l=new Array,u=new Array;t.forEach((t=>{t.isDesired!==d&&l.push(t.trackSid),t.isEnabled||u.push(t.trackSid)})),this.client.sendSyncState(new Ti({answer:"publisher-only"===this.pcManager.mode?a?po({sdp:a.sdp,type:a.type}):void 0:h?po({sdp:h.sdp,type:h.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?po({sdp:o.sdp,type:o.type}):void 0:c?po({sdp:c.sdp,type:c.type}):void 0,subscription:new Xe({trackSids:l,subscribe:!d,participantTracks:[]}),publishTracks:$s(e),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:u,datachannelReceiveStates:this.reliableReceivedState.map(((t,e)=>new Si({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 Ei({label:e.label,id:e.id,target:i}))};return e(this.dataChannelForKind(ce.LOSSY),Le.PUBLISHER),e(this.dataChannelForKind(ce.RELIABLE),Le.PUBLISHER),e(this.dataChannelForKind(ce.LOSSY,!0),Le.SUBSCRIBER),e(this.dataChannelForKind(ce.RELIABLE,!0),Le.SUBSCRIBER),t}clearReconnectTimeout(){this.reconnectTimeout&&Ds.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){gr()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){gr()&&(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 xa(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 Ca{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 js("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),bs.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new js("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),bs.LengthExceeded)}}constructor(t,e,i,n){this.reader=e,this.totalByteSize=i,this._info=t,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class _a extends Ca{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 Dr,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:()=>Zi(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 Zi(this,void 0,void 0,(function*(){return s(),{done:!0,value:void 0}}))}}}withAbortSignal(t){return this.signal=t,this}readAll(){return Zi(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,h=Xi(o);!(i=(a=yield h.next()).done);c=!0)c=!1,r.add(a.value)}catch(t){n={error:t}}finally{try{c||i||!(s=h.return)||(yield s.call(h))}finally{if(n)throw n.error}}return Array.from(r)}()}))}}class Ra extends Ca{constructor(t,e,i,n){super(t,e,i,n),this.receivedChunks=new Map}handleChunkReceived(t){var e;const i=Lr(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 Dr,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:()=>Zi(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 js("Cannot decode datastream chunk ".concat(o.chunkIndex," as text: ").concat(t),bs.DecodeFailed)}return{done:!1,value:t}}}catch(t){throw r(),t}})),return(){return Zi(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(t){return this.signal=t,this}readAll(){return Zi(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,h=Xi(o);!(i=(a=yield h.next()).done);c=!0)c=!1,r+=a.value}catch(t){n={error:t}}finally{try{c||i||!(s=h.return)||(yield s.call(h))}finally{if(n)throw n.error}}return r}()}))}}class Ia{constructor(){this.log=Qi,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 js('A text stream handler for topic "'.concat(t,'" has already been set.'),bs.HandlerAlreadyRegistered);this.textStreamHandlers.set(t,e)}unregisterTextStreamHandler(t){this.textStreamHandlers.delete(t)}registerByteStreamHandler(t,e){if(this.byteStreamHandlers.has(t))throw new js('A byte stream handler for topic "'.concat(t,'" has already been set.'),bs.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 js("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),bs.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 Zi(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 new Error('DataPacket of value "'.concat(t.value.case,'" is not data stream related!'))}}))}handleStreamHeader(t,e,i){return Zi(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 Dr;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:Lr(t.timestamp),attributes:t.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(t.streamId))throw new js("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),bs.AlreadyOpened);this.byteStreamControllers.set(t.streamId,{info:a,controller:r,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:o})}});s(new _a(a,c,Lr(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 Dr;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 js("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),bs.AlreadyOpened);this.textStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now(),sendingParticipantIdentity:e,outOfBandFailureRejectingFuture:r})}});n(new Ra(o,a,Lr(t.totalLength),r),{identity:e})}}))}handleStreamChunk(t,e){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==e?(i.controller.error(new js("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(i.info.encryptionType),bs.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 js("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(n.info.encryptionType),bs.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 js("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(i.info.encryptionType),bs.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 js("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(e,", got ").concat(n.info.encryptionType),bs.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 Zi(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 Pa extends ja{}class Da extends ja{}class Ma{constructor(t,e){this.engine=t,this.log=e}setupEngine(t){this.engine=t}sendText(t,e){return Zi(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=new 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)=>Zi(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 Zi(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)?ie.GCM:ie.NONE},o=new De({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:Br(r.timestamp),totalLength:Br(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)?Ie.UPDATE:Ie.CREATE})}}),a=null==t?void 0:t.destinationIdentities,c=new ae({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,ce.RELIABLE);let h=0;const d=this.engine,l=new WritableStream({write(t){return Zi(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 Me({content:e,streamId:s,chunkIndex:Br(h)}),i=new ae({destinationIdentities:a,value:{case:"streamChunk",value:t}});yield d.sendDataPacket(i,ce.RELIABLE),h+=1}}))},close(){return Zi(this,void 0,void 0,(function*(){const t=new Ne({streamId:s}),e=new ae({destinationIdentities:a,value:{case:"streamTrailer",value:t}});yield d.sendDataPacket(e,ce.RELIABLE)}))},abort(t){console.log("Sink error:",t)}});let u=()=>Zi(this,void 0,void 0,(function*(){yield f.close()}));d.once(Ts.Closing,u);const f=new Pa(l,r,(()=>this.engine.off(Ts.Closing,u)));return f}))}sendFile(t,e){return Zi(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,t,e),{id:i}}))}_sendFile(t,e,i){return Zi(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 Zi(this,void 0,void 0,(function*(){var e,i,n,s,r,o;const c=null!==(e=null==t?void 0:t.streamId)&&void 0!==e?e:crypto.randomUUID(),h=null==t?void 0:t.destinationIdentities,d={id:c,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)?ie.GCM:ie.NONE},l=new De({totalLength:Br(null!==(o=d.size)&&void 0!==o?o:0),mimeType:d.mimeType,streamId:c,topic:d.topic,timestamp:Br(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Pe({name:d.name})}}),u=new ae({destinationIdentities:h,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,ce.RELIABLE);let f=0;const v=new a,m=this.engine,p=this.log,g=new WritableStream({write(t){return Zi(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 ae({destinationIdentities:h,value:{case:"streamChunk",value:new Me({content:e,streamId:c,chunkIndex:Br(f)})}});yield m.sendDataPacket(n,ce.RELIABLE),f+=1,i+=e.byteLength}}finally{e()}}))},close(){return Zi(this,void 0,void 0,(function*(){const t=new Ne({streamId:c}),e=new ae({destinationIdentities:h,value:{case:"streamTrailer",value:t}});yield m.sendDataPacket(e,ce.RELIABLE)}))},abort(t){p.error("Sink error:",t)}});return new Da(g,d)}))}}class Na extends nr{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?Ss.Muted:Ss.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(Ss.Ended,this))};t.addEventListener("removetrack",e)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Zi(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()),$o)),"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(Ss.TimeSyncUpdate,{timestamp:t,rtpTimestamp:e}),this.rtpTimestamp=e)}};t()}}class Ua extends Na{constructor(t,e,i,n,s,r){super(t,e,nr.Kind.Audio,i,r),this.monitorReceiver=()=>Zi(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=Zo(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;br()&&this._mediaStreamTrack._setVolume(t),this.elementVolume=t}getVolume(){if(this.elementVolume)return this.elementVolume;if(br())return 1;let t=0;return this.attachedElements.forEach((e=>{e.volume>t&&(t=e.volume)})),t}setSinkId(t){return Zi(this,void 0,void 0,(function*(){this.sinkId=t,yield Promise.all(this.attachedElements.map((e=>{if(lr(e))return e.setSinkId(t)})))}))}attach(t){const e=0===this.attachedElements.length;return t?super.attach(t):t=super.attach(),this.sinkId&&lr(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(Ss.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(Ss.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 Zi(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 La extends Na{constructor(t,e,i,n,s){super(t,e,nr.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Zi(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=Zo(t,this.prevStats)),this.prevStats=t})),this.debouncedHandleResize=Io((()=>{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===nr.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(t){super.setMuted(t),this.attachedElements.forEach((e=>{t?rr(this._mediaStreamTrack,e):sr(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 Ba(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 Zi(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 Zi(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?Ds.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(Ss.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(Ss.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var t;const e=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pixelDensity;return"screen"===e?Sr():e||(Sr()>2?2:1)}}class Ba{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=Fa(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=Fa(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var t;this.isPiP=Fa(this.element),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this)},this.element=t,this.isIntersecting=null!=e?e:qa(t),this.isPiP=gr()&&Fa(t),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var t,e,i;this.isIntersecting=qa(this.element),this.isPiP=Fa(this.element),this.element.handleResize=()=>{var t;null===(t=this.handleResize)||void 0===t||t.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Rr().observe(this.element),Cr().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=Rr())||void 0===t||t.unobserve(this.element),null===(e=Cr())||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 Fa(t){var e,i;return document.pictureInPictureElement===t||!!(null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)&&qa(t,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function qa(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 Va extends nn.EventEmitter{constructor(t,e,i,n){var s;super(),this.metadataMuted=!1,this.encryption=ie.NONE,this.log=Qi,this.handleMuted=()=>{this.emit(Ss.Muted)},this.handleUnmuted=()=>{this.emit(Ss.Unmuted)},this.log=Hi(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:Ji.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=e,this.trackName=i,this.source=nr.Source.Unknown}setTrack(t){this.track&&(this.track.off(Ss.Muted,this.handleMuted),this.track.off(Ss.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(Ss.Muted,this.handleMuted),t.on(Ss.Unmuted,this.handleUnmuted))}get logContext(){var t;return Object.assign(Object.assign({},null===(t=this.loggerContextCb)||void 0===t?void 0:t.call(this)),Zs(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ie.NONE}get audioTrack(){if(qr(this.track))return this.track}get videoTrack(){if(Vr(this.track))return this.track}updateInfo(t){this.trackSid=t.sid,this.trackName=t.name,this.source=nr.sourceFromProto(t.source),this.mimeType=t.mimeType,this.kind===nr.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){var e,i;(e=t.SubscriptionStatus||(t.SubscriptionStatus={})).Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",(i=t.PermissionStatus||(t.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(Va||(Va={}));class za extends Va{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(Ss.Ended)},this.handleCpuConstrained=()=>{this.track&&Vr(this.track)&&this.emit(Ss.CpuConstrained,this.track)},this.updateInfo(e),this.setTrack(i)}setTrack(t){this.track&&(this.track.off(Ss.Ended,this.handleTrackEnded),this.track.off(Ss.CpuConstrained,this.handleCpuConstrained)),super.setTrack(t),t&&(t.on(Ss.Ended,this.handleTrackEnded),t.on(Ss.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 Zi(this,void 0,void 0,(function*(){var t;return null===(t=this.track)||void 0===t?void 0:t.mute()}))}unmute(){return Zi(this,void 0,void 0,(function*(){var t;return null===(t=this.track)||void 0===t?void 0:t.unmute()}))}pauseUpstream(){return Zi(this,void 0,void 0,(function*(){var t;yield null===(t=this.track)||void 0===t?void 0:t.pauseUpstream()}))}resumeUpstream(){return Zi(this,void 0,void 0,(function*(){var t;yield null===(t=this.track)||void 0===t?void 0:t.resumeUpstream()}))}getTrackFeatures(){var t;if(qr(this.track)){const e=this.track.getSourceTrackSettings(),i=new Set;return e.autoGainControl&&i.add(Ht.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&i.add(Ht.TF_ECHO_CANCELLATION),e.noiseSuppression&&i.add(Ht.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&i.add(Ht.TF_STEREO),(null===(t=this.options)||void 0===t?void 0:t.dtx)||i.add(Ht.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Ht.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function Ja(t,e){return Zi(this,void 0,void 0,(function*(){null!=t||(t={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Xs(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=Gs(Js(r,qo,Vo)),h=navigator.mediaDevices.getUserMedia(c);r.audio&&(ao.userMediaPromiseMap.set("audioinput",h),h.catch((()=>ao.userMediaPromiseMap.delete("audioinput")))),r.video&&(ao.userMediaPromiseMap.set("videoinput",h),h.catch((()=>ao.userMediaPromiseMap.delete("videoinput"))));try{const t=yield h;return yield Promise.all(t.getTracks().map((i=>Zi(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)&&Mr(r.deviceId)!==a?r.deviceId=a:r||(r={deviceId:a});const h=function(t,e,i){switch(t.kind){case"audio":return new na(t,e,!1,void 0,i);case"video":return new ma(t,e,!1,i);default:throw new As("unsupported track type: ".concat(t.kind))}}(i,r,e);return h.kind===nr.Kind.Video?h.source=nr.Source.Camera:h.kind===nr.Kind.Audio&&(h.source=nr.Source.Microphone),h.mediaStream=t,qr(h)&&n?yield h.setProcessor(n):Vr(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(n){if(!i)throw n;return Ja(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"}(Sa||(Sa={}));class Wa extends nn.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===te.AGENT}get isActive(){var t;return(null===(t=this.participantInfo)||void 0===t?void 0:t.state)===Xt.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]:te.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Sa.Unknown,this.log=Qi,this.log=Hi(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:Ji.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 Dr,this.once(ks.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(nr.Source.Camera);return!(null===(t=null==e?void 0:e.isMuted)||void 0===t||t)}get isMicrophoneEnabled(){var t;const e=this.getTrackPublication(nr.Source.Microphone);return!(null===(t=null==e?void 0:e.isMuted)||void 0===t||t)}get isScreenShareEnabled(){return!!this.getTrackPublication(nr.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):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===Xt.ACTIVE&&(null===(e=this.participantInfo)||void 0===e?void 0:e.state)!==Xt.ACTIVE&&this.emit(ks.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(ks.ParticipantMetadataChanged,i)}_setName(t){const e=this.name!==t;this.name=t,e&&this.emit(ks.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(ks.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(ks.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(ks.IsSpeakingChanged,t))}setConnectionQuality(t){const e=this._connectionQuality;this._connectionQuality=function(t){switch(t){case zt.EXCELLENT:return Sa.Excellent;case zt.GOOD:return Sa.Good;case zt.POOR:return Sa.Poor;case zt.LOST:return Sa.Lost;default:return Sa.Unknown}}(t),e!==this._connectionQuality&&this.emit(ks.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var t,e;this.activeFuture&&(null===(e=(t=this.activeFuture).reject)||void 0===e||e.call(t,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(t){this.audioContext=t,this.audioTrackPublications.forEach((e=>qr(e.track)&&e.track.setAudioContext(t)))}addTrackPublication(t){switch(t.on(Ss.Muted,(()=>{this.emit(ks.TrackMuted,t)})),t.on(Ss.Unmuted,(()=>{this.emit(ks.TrackUnmuted,t)})),t.track&&(t.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case nr.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case nr.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class Ga extends Wa{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=ie.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Dr)},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,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(r=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,new 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 Dr),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 Is(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=Ho.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 new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new bi({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),Zs(t)))},this.onTrackUpstreamPaused=t=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Zs(t))),this.onTrackMuted(t,!0)},this.onTrackUpstreamResumed=t=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Zs(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),Zs(e))),this.emit(ks.LocalTrackCpuConstrained,t,e)},this.handleSubscribedQualityUpdate=t=>Zi(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,h=Xi(o);!(e=(a=yield h.next()).done);c=!0){c=!1;const t=a.value;Ls(t)&&(this.log.debug("publish ".concat(t," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Zs(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,t,r.options))}}catch(t){i={error:t}}finally{try{c||e||!(n=h.return)||(yield n.call(h))}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=>Zi(this,void 0,void 0,(function*(){if(t.source===nr.Source.ScreenShare||t.source===nr.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Zs(t))),this.unpublishTrack(t);else if(t.isUserProvided)yield t.mute();else if(Jr(t)||zr(t))try{if(gr())try{const e=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:t.source===nr.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),Zs(t))),e.onchange=()=>{"denied"!==e.state&&(t.isMuted||t.restartTrack(),e.onchange=null)},new 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),Zs(t))),Jr(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),Zs(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!==ie.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(Ts.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(Ts.Connected,this.handleReconnected).on(Ts.SignalConnected,this.handleSignalConnected).on(Ts.SignalRestarted,this.handleReconnected).on(Ts.SignalResumed,this.handleReconnected).on(Ts.Restarting,this.handleReconnecting).on(Ts.Resuming,this.handleReconnecting).on(Ts.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Ts.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Ts.Closing,this.handleClosing).on(Ts.SignalRequestResponse,this.handleSignalRequestResponse).on(Ts.DataPacketReceived,this.handleDataPacket)}setMetadata(t){return Zi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:t})}))}setName(t){return Zi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:t})}))}setAttributes(t){return Zi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:t})}))}requestMetadataUpdate(t){return Zi(this,arguments,void 0,(function(t){var e=this;let{metadata:i,name:n,attributes:s}=t;return function*(){return new hs(((t,r)=>Zi(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),h=performance.now();for(this.pendingSignalRequests.set(c,{resolve:t,reject:t=>{r(t),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-h<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 ar(50)}r(new Is("Request to update local metadata timed out","TimeoutError"))}catch(t){t instanceof Error?r(t):r(new Error(String(t)))}}))))}()}))}setCameraEnabled(t,e,i){return this.setTrackEnabled(nr.Source.Camera,t,e,i)}setMicrophoneEnabled(t,e,i){return this.setTrackEnabled(nr.Source.Microphone,t,e,i)}setScreenShareEnabled(t,e,i){return this.setTrackEnabled(nr.Source.ScreenShare,t,e,i)}setE2EEEnabled(t){return Zi(this,void 0,void 0,(function*(){this.encryptionType=t?ie.GCM:ie.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,e,i,n){return Zi(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 nr.Source.Camera:e=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case nr.Source.Microphone:e=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case nr.Source.ScreenShare:e=yield this.createScreenTracks(Object.assign({},i));break;default:throw new As(t)}}catch(i){throw null==e||e.forEach((t=>{t.stop()})),i instanceof Error&&this.emit(ks.MediaDevicesError,i,Ks(t)),this.pendingPublishing.delete(t),i}for(const n of e){const e=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);t===nr.Source.Microphone&&qr(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),Zs(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===nr.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const t=this.getTrackPublication(nr.Source.ScreenShareAudio);t&&t.track&&this.unpublishTrack(t.track)}else yield o.mute();return o}))}enableCameraAndMicrophone(){return Zi(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(nr.Source.Camera)&&!this.pendingPublishing.has(nr.Source.Microphone)){this.pendingPublishing.add(nr.Source.Camera),this.pendingPublishing.add(nr.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(nr.Source.Camera),this.pendingPublishing.delete(nr.Source.Microphone)}}}))}createTracks(t){return Zi(this,void 0,void 0,(function*(){var e,i;null!=t||(t={});const n=Js(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 Ja(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((t=>(qr(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=nr.Source.Microphone,this.emit(ks.AudioStreamAcquired)),Vr(t)&&(this.cameraError=void 0,t.source=nr.Source.Camera),t)))}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}}))}createScreenTracks(t){return Zi(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Os("getDisplayMedia not supported");void 0!==t.resolution||function(){const t=us();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)&&Er(t.osVersion,"17")>=0}()||(t.resolution=zs.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=vr()?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 As("no video track found");const s=new ma(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=nr.Source.ScreenShare,t.contentHint&&(s.mediaStreamTrack.contentHint=t.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(ks.AudioStreamAcquired);const t=new na(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=nr.Source.ScreenShareAudio,r.push(t)}return r}))}publishTrack(t,e){return Zi(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(t,e)}))}publishOrRepublishTrack(t,e){return Zi(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,h;if(Jr(t)&&t.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),Fr(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 nr.Source.Microphone:e="audioinput";break;case nr.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 na(t,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":t=new ma(t,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new As("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&&(h=e)})),h)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),Zs(h))),h;const d=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=d.forceStereo)&&void 0!==r?r:l;u&&(void 0===d.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),Zs(t))),void 0===d.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=d.dtx)&&void 0!==o||(d.dtx=!1),null!==(a=d.red)&&void 0!==a||(d.red=!1)),!function(){const t=us(),e="17.2";if(t)return"Safari"!==t.name&&"iOS"!==t.os||!!("iOS"===t.os&&t.osVersion&&Er(t.osVersion,e)>=0)||"Safari"===t.name&&Er(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)),d.simulcast=!1),d.source&&(t.source=d.source);const f=new Promise(((e,n)=>Zi(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==fo.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Zs(t)}));let i=!1;const s=setTimeout((()=>{i=!0,t.stop(),n(new Rs("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(s),i)return;const r=yield this.publish(t,d,u);e(r)}else try{const i=yield this.publish(t,d,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 Dr),this.signalConnectedFuture.promise}hasPermissionsToPublish(t){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Zs(t))),!1;const{canPublish:e,canPublishSources:i}=this.permissions;return!(!e||0!==i.length&&!i.map((t=>function(t){switch(t){case qt.CAMERA:return nr.Source.Camera;case qt.MICROPHONE:return nr.Source.Microphone;case qt.SCREEN_SHARE:return nr.Source.ScreenShare;case qt.SCREEN_SHARE_AUDIO:return nr.Source.ScreenShareAudio;default:return nr.Source.Unknown}}(t))).includes(t.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Zs(t))),!1)}publish(t,e,i){return Zi(this,void 0,void 0,(function*(){var n,s,r,o,a,c,h,d,l,u;if(!this.hasPermissionsToPublish(t))throw new Rs("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>Fr(t)&&e.source===t.source))&&t.source!==nr.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),Zs(t))),e.stopMicTrackOnMute&&qr(t)&&(t.stopOnMute=!0),t.source===nr.Source.ScreenShare&&ur()&&(e.simulcast=!1),"av1"!==e.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(vr()||ur())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(ur())return!1;if(vr()){const t=us();if((null==t?void 0:t.version)&&Er(t.version,"16")<0)return!1;if("iOS"===(null==t?void 0:t.os)&&(null==t?void 0:t.osVersion)&&Er(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=Bo),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((t=>e.videoCodec===Ys(t.mime)))||(e.videoCodec=Ys(this.enabledPublishVideoCodecs[0].mime)));const f=e.videoCodec;t.on(Ss.Muted,this.onTrackMuted),t.on(Ss.Unmuted,this.onTrackUnmuted),t.on(Ss.Ended,this.handleTrackEnded),t.on(Ss.UpstreamPaused,this.onTrackUpstreamPaused),t.on(Ss.UpstreamResumed,this.onTrackUpstreamResumed),t.on(Ss.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],m=!(null===(n=e.dtx)||void 0===n||n),p=t.getSourceTrackSettings();p.autoGainControl&&v.push(Ht.TF_AUTO_GAIN_CONTROL),p.echoCancellation&&v.push(Ht.TF_ECHO_CANCELLATION),p.noiseSuppression&&v.push(Ht.TF_NOISE_SUPPRESSION),p.channelCount&&p.channelCount>1&&v.push(Ht.TF_STEREO),m&&v.push(Ht.TF_NO_DTX),Jr(t)&&t.hasPreConnectBuffer&&v.push(Ht.TF_PRECONNECT_BUFFER);const g=new Je({cid:t.mediaStreamTrack.id,name:e.name,type:nr.kindToProto(t.kind),muted:t.isMuted,source:nr.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===nr.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:qs.h720.resolution;i={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Zs(t)),{dims:i}))}g.width=i.width,g.height=i.height,zr(t)&&(dr(f)&&(t.source===nr.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),Zs(t))))),e.scalabilityMode=null!==(a=e.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),g.simulcastCodecs=[new ze({codec:f,cid:t.mediaStreamTrack.id})],!0===e.backupCodec&&(e.backupCodec={codec:Bo}),e.backupCodec&&f!==e.backupCodec.codec&&g.encryption===ie.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new ze({codec:e.backupCodec.codec,cid:""})))),b=da(t.source===nr.Source.ScreenShare,g.width,g.height,e),g.layers=ba(g.width,g.height,b,dr(e.videoCodec))}else t.kind===nr.Kind.Audio&&(b=[{maxBitrate:null===(c=e.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(d=null===(h=e.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==d?d:"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 Cs("cannot publish track when not connected");const y=()=>Zi(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new Cs("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,e,b),this.emit(ks.LocalSenderCreated,t.sender,t),zr(t)&&(null!==(i=e.degradationPreference)&&void 0!==i||(e.degradationPreference=function(t){return t.source===nr.Source.ScreenShare||t.constraints.height&&Mr(t.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(e.degradationPreference)),b)if(ur()&&t.kind===nr.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&&dr(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)=>Zi(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),Zs(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===nr.Kind.Video){const n=Ys(i);n!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Zs(t)),{codec:n})),e.videoCodec=n,b=da(t.source===nr.Source.ScreenShare,g.width,g.height,e))}yield y()}const T=new za(t.kind,w,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(T.on(Ss.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})),zr(t)?t.startMonitor(this.engine.client):Jr(t)&&t.startMonitor(),this.addTrackPublication(T),this.emit(ks.LocalTrackPublished,T),Jr(t)&&w.audioFeatures.includes(Ht.TF_PRECONNECT_BUFFER)){const e=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(ks.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),Zs(t))),t.stopPreConnectBuffer()}})),e){const n=new Promise(((n,s)=>Zi(this,void 0,void 0,(function*(){var r,o,a,c,h;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Zs(t)));const f=setTimeout((()=>{s(new 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),Zs(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:String(null!==(c=p.sampleRate)&&void 0!==c?c:"48000"),channels:String(null!==(h=p.channelCount)&&void 0!==h?h:"1")}});try{for(var d,l=!0,u=Xi(e);!(r=(d=yield u.next()).done);l=!0){l=!1;const t=d.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),Zs(t)))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Zs(t)),{error:e}))}))}}return T}))}get isLocal(){return!0}publishAdditionalCodecForTrack(t,e,i){return Zi(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==ie.NONE)return;let s;if(this.trackPublications.forEach((e=>{e.track&&e.track===t&&(s=e)})),!s)throw new As("track is not published");if(!zr(t))throw new As("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&&Qi.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,h=null!==(r=a.height)&&void 0!==r?r:null===(o=t.dimensions)||void 0===o?void 0:o.height;return t.source===nr.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),da(t.source===nr.Source.ScreenShare,c,h,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),Zs(t)));const a=t.addSimulcastTrack(e,o);if(!a)return;const c=new Je({cid:a.mediaStreamTrack.id,type:nr.kindToProto(t.kind),muted:t.isMuted,source:nr.sourceToProto(t.source),sid:t.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=ba(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Cs("cannot publish track when not connected");const h=(yield Promise.all([this.engine.addTrack(c),(()=>Zi(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:h}))}))}unpublishTrack(t,e){return Zi(this,void 0,void 0,(function*(){var i,n;if(Fr(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Zs(t))),yield e)}const s=this.getPublicationForTrack(t),r=s?Zs(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(Ss.Muted,this.onTrackMuted),t.off(Ss.Unmuted,this.onTrackUnmuted),t.off(Ss.Ended,this.handleTrackEnded),t.off(Ss.UpstreamPaused,this.onTrackUpstreamPaused),t.off(Ss.UpstreamResumed,this.onTrackUpstreamResumed),t.off(Ss.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<Wo.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),zr(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 nr.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case nr.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(ks.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(t){return Zi(this,void 0,void 0,(function*(){return(yield Promise.all(t.map((t=>this.unpublishTrack(t))))).filter((t=>!!t))}))}republishAllTracks(t){return Zi(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 hs(((n,s)=>Zi(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=>Zi(this,void 0,void 0,(function*(){const e=t.track;yield this.unpublishTrack(e,!1),!i||e.isMuted||e.source===nr.Source.ScreenShare||e.source===nr.Source.ScreenShareAudio||!Jr(e)&&!zr(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){t instanceof Error?s(t):s(new Error(String(t)))}finally{this.republishPromise=void 0}})))),yield e.republishPromise}()}))}publishData(t){return Zi(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?ce.RELIABLE:ce.LOSSY;let s=new fe({participantIdentity:e.identity,payload:t,destinationIdentities:i.destinationIdentities,topic:i.topic});const r=new ae({kind:n,value:{case:"user",value:s}});yield e.engine.sendDataPacket(r,n)}()}))}publishDtmf(t,e){return Zi(this,void 0,void 0,(function*(){const i=new ae({kind:ce.RELIABLE,value:{case:"sipDtmf",value:new ve({code:t,digit:e})}});yield this.engine.sendDataPacket(i,ce.RELIABLE)}))}sendChatMessage(t,e){return Zi(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 ae({value:{case:"chatMessage",value:new ge(Object.assign(Object.assign({},i),{timestamp:x.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,ce.RELIABLE),this.emit(ks.ChatMessage,i),i}))}editChatMessage(t,e){return Zi(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},e),{message:t,editTimestamp:Date.now()}),n=new ae({value:{case:"chatMessage",value:new ge(Object.assign(Object.assign({},i),{timestamp:x.parse(i.timestamp),editTimestamp:x.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,ce.RELIABLE),this.emit(ks.ChatMessage,i),i}))}sendText(t,e){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(t,e)}))}streamText(t){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(t)}))}sendFile(t,e){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(t,e)}))}streamBytes(t){return Zi(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 hs(((t,r)=>Zi(this,void 0,void 0,(function*(){var o,a,c,h;if(Ko(n)>15360)return void r(Ho.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)&&Er(null===(h=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===h?void 0:h.version,"1.8.0")<0)return void r(Ho.builtIn("UNSUPPORTED_SERVER"));const d=Math.max(s,8e3),l=crypto.randomUUID();yield this.publishRpcRequest(e,l,i,n,d);const u=setTimeout((()=>{this.pendingAcks.delete(l),r(Ho.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(Ho.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 Zi(this,void 0,void 0,(function*(){const r=new ae({destinationIdentities:[t],kind:ce.RELIABLE,value:{case:"rpcRequest",value:new be({id:e,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,ce.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,Ho.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),Zs(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,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Dr),this.activeAgentFuture.promise)}getPublicationForTrack(t){let e;return this.trackPublications.forEach((i=>{const n=i.track;n&&(t instanceof MediaStreamTrack?(Jr(n)||zr(n))&&n.mediaStreamTrack===t&&(e=i):t===n&&(e=i))})),e}waitForPendingPublicationOfSource(t){return Zi(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 ar(20)}}))}}class Qa extends Va{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(Ss.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 Xe({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Te({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Ss.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(e),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Va.SubscriptionStatus.Unsubscribed:super.isSubscribed?Va.SubscriptionStatus.Subscribed:Va.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Va.PermissionStatus.Allowed:Va.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||(Qr(this.track)&&(this.requestedVideoDimensions=t),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(t){this.isManualOperationAllowed()&&Qr(this.track)&&this.fps!==t&&(this.fps=t,this.emitTrackUpdate())}get videoQuality(){var t;return null!==(t=this.requestedMaxQuality)&&void 0!==t?t:ir.HIGH}setTrack(t){const e=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==t&&(n&&(n.off(Ss.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Ss.VisibilityChanged,this.handleVisibilityChange),n.off(Ss.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Ss.Unsubscribed,n)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(Ss.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(Ss.VisibilityChanged,this.handleVisibilityChange),t.on(Ss.Ended,this.handleEnded),this.emit(Ss.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(Ss.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?Ss.Muted:Ss.Unmuted)}emitSubscriptionUpdateIfChanged(t){const e=this.subscriptionStatus;t!==e&&this.emit(Ss.SubscriptionStatusChanged,e,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(Ss.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Qr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new ti({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===nr.Kind.Video){let n=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(n)tr(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const t=(e=this.requestedMaxQuality,null===(i=this.trackInfo.layers)||void 0===i?void 0:i.find((t=>t.quality===e)));t&&tr(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(t.width=Math.ceil(n.width),t.height=Math.ceil(n.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:ir.HIGH})),t.quality=ir.HIGH)}var e,i;this.emit(Ss.UpdateSettings,t)}}class Ha extends Wa{static fromParticipantInfo(t,e,i){return new Ha(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]:te.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(Ss.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Zs(t)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)})),t.on(Ss.UpdateSubscription,(t=>{t.participantTracks.forEach((t=>{t.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(t)})),t.on(Ss.SubscriptionPermissionChanged,(e=>{this.emit(ks.TrackSubscriptionPermissionChanged,t,e)})),t.on(Ss.SubscriptionStatusChanged,(e=>{this.emit(ks.TrackSubscriptionStatusChanged,t,e)})),t.on(Ss.Subscribed,(e=>{this.emit(ks.TrackSubscribed,e,t)})),t.on(Ss.Unsubscribed,(e=>{this.emit(ks.TrackUnsubscribed,e,t)})),t.on(Ss.SubscriptionFailed,(e=>{this.emit(ks.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]:nr.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]:nr.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.toString()||(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),Zs(a))),void this.emit(ks.TrackSubscriptionFailed,e)):(o="video"===t.kind?new La(t,e,n,s):new Ua(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)&&Wr(o)&&qr(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(ks.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=nr.kindFromProto(t.type);if(!e)return;r=new Qa(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!==nr.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:Zs(o),newTrack:Zs(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),Zs(t))),this.unpublishTrack(t.trackSid,!0))})),i.forEach((t=>{this.emit(ks.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 nr.Kind.Audio:this.audioTrackPublications.delete(t);break;case nr.Kind.Video:this.videoTrackPublications.delete(t)}e&&this.emit(ks.TrackUnpublished,i)}setAudioOutput(t){return Zi(this,void 0,void 0,(function*(){this.audioOutput=t;const e=[];this.audioTrackPublications.forEach((i=>{var n;qr(i.track)&&Wr(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=new 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"}(Ea||(Ea={}));class Ka extends nn.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(t){var e,i,n,s,r;if(super(),e=this,this.state=Ea.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Qi,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(t,e,i)=>Zi(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!cr()&&!hr())throw br()?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===Ea.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(Ea.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==Hr(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),yr(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Qo(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)=>Zi(this,void 0,void 0,(function*(){var c,h;this.abortController&&this.abortController.abort();const d=new AbortController;this.abortController=d,null==s||s();try{if(yield ro.getInstance().getBackOffPromise(t),d.signal.aborted)throw Es.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=a?a:t,e,i,d),this.abortController=void 0,n()}catch(e){if(this.regionUrlProvider&&e instanceof Es&&e.reason!==gs.Cancelled&&e.reason!==gs.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 Es&&(401===t.status||t.reason===gs.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(t)}[gs.InternalError,gs.ServerUnreachable,gs.Timeout].includes(e.reason)&&(this.log.debug("Adding failed connection attempt to back off"),ro.getInstance().addFailedConnectionAttempt(t)),i&&!(null===(h=this.abortController)||void 0===h?void 0:h.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,Ur(e)),o(e))}else{let t=Wt.UNKNOWN_REASON;e instanceof Es&&(t=Ur(e)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),o(e)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Dr(((t,e)=>{r(t,e,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(t,e,i,n,s,r)=>Zi(this,void 0,void 0,(function*(){var o,a,c;const h=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 d=h.serverInfo;if(d||(d={version:h.serverVersion,region:h.serverRegion}),this.serverInfo=d,this.log.debug("connected to Livekit Server ".concat(Object.entries(d).map((t=>{let[e,i]=t;return"".concat(e,": ").concat(i)})).join(", ")),{room:null===(o=h.room)||void 0===o?void 0:o.name,roomSid:null===(a=h.room)||void 0===a?void 0:a.sid,identity:null===(c=h.participant)||void 0===c?void 0:c.identity}),!d.version)throw new xs("unknown server version");return"0.15.1"===d.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),h})),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)=>Zi(this,void 0,void 0,(function*(){var s,r;this.state===Ea.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({},Jo),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(ws.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();const e=n.signal.aborted?Es.cancelled("Signal connection aborted"):Es.serverUnreachable("could not establish signal connection");throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof Es&&(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(),Es.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(t){throw yield this.engine.close(),this.recreateEngine(),t}gr()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),gr()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Ea.Connected),this.emit(ws.Connected),ro.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return Zi(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===Ea.Disconnected)return void t.log.debug("already disconnected",t.logContext);if(t.log.info("disconnect from room",Object.assign({},t.logContext)),t.state===Ea.Connecting||t.state===Ea.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,Es.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,Wt.CLIENT_INITIATED),t.engine=void 0}finally{r()}}()}))},this.onPageLeave=()=>Zi(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Zi(this,void 0,void 0,(function*(){const t=[],e=us();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=Pr();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(ws.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=()=>Zi(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(Ea.Reconnecting)&&this.emit(ws.Reconnecting)},this.handleSignalRestarted=t=>Zi(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(Ea.Connected),this.emit(ws.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===Xt.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(ws.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(ws.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=nr.streamStateFromProto(t.state);i.track.setStreamState(n),n!==i.track.streamState&&(e.emit(ks.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(ws.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(ws.DataReceived,e.payload,t,i,e.topic,n),null==t||t.emit(ks.DataReceived,e.payload,i,n)},this.handleSipDtmf=(t,e)=>{this.emit(ws.SipDTMFReceived,e,t),null==t||t.emit(ks.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 h=null!==(c=e.get(i))&&void 0!==c?c:Date.now(),d=Date.now();return a?e.delete(i):e.set(i,h),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:h,lastReceivedTime:d}}))}(e,this.transcriptionReceivedTimes);null==n||n.emit(Ss.TranscriptionReceived,s),null==i||i.emit(ks.TranscriptionReceived,s,n),this.emit(ws.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.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(e);this.emit(ws.ChatMessage,i,t)},this.handleMetrics=(t,e)=>{this.emit(ws.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(ws.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(ws.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ws.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ws.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Zi(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=us())||void 0===t?void 0:t.os)&&(yield this.selectDefaultDevices()),this.emit(ws.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const e=this.roomInfo;this.roomInfo=t,e&&e.metadata!==t.metadata&&this.emitWhenConnected(ws.RoomMetadataChanged,t.metadata),(null==e?void 0:e.activeRecording)!==t.activeRecording&&this.emitWhenConnected(ws.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(ws.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(ws.ParticipantNameChanged,t,this.localParticipant)},this.onLocalAttributesChanged=t=>{this.emit(ws.ParticipantAttributesChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(ws.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(ws.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=>Zi(this,void 0,void 0,(function*(){var e,i,n,s,r,o;null===(e=t.track)||void 0===e||e.on(Ss.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.on(Ss.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(ws.LocalTrackPublished,t,this.localParticipant),Jr(t.track)&&(yield t.track.checkForSilence())&&this.emit(ws.LocalAudioSilenceDetected,t);const a=yield null===(o=t.track)||void 0===o?void 0:o.getDeviceId(!1),c=Ks(t.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(ws.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=t=>{var e,i;null===(e=t.track)||void 0===e||e.off(Ss.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.off(Ss.Restarted,this.onLocalTrackRestarted),this.emit(ws.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>Zi(this,void 0,void 0,(function*(){const e=yield t.getDeviceId(!1),i=Ks(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(ws.ActiveDeviceChanged,i,e))})),this.onLocalConnectionQualityChanged=t=>{this.emit(ws.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=(t,e)=>{this.emit(ws.MediaDevicesError,t,e)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(ws.ParticipantPermissionsChanged,t,this.localParticipant)},this.onLocalChatMessageSent=t=>{this.emit(ws.ChatMessage,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},zo),t),this.log=Hi(null!==(i=this.options.loggerName)&&void 0!==i?i:Ji.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},qo),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Vo),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Fo),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Ia,this.outgoingDataStreamManager=new Ma(this.engine,this.log),this.disconnectLock=new a,this.localParticipant=new Ga("","",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",Mr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Mr(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Mr(this.options.audioOutput.deviceId)).catch((t=>this.log.warn("Could not set audio output: ".concat(t.message),this.logContext))),gr()){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}),Ka.cleanupRegistry&&Ka.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 Zi(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 so(i,e),this.e2eeManager.on(to.ParticipantEncryptionStatusChanged,((t,e)=>{(function(t){return t.isLocal})(e)&&(this.isE2EEEnabled=t),this.emit(ws.ParticipantEncryptionStatusChanged,t,e)})),this.e2eeManager.on(to.EncryptionError,((t,e)=>{const i=e?this.getParticipantByIdentity(e):void 0;this.emit(ws.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===Ea.Disconnected?hs.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?hs.resolve(this.roomInfo.sid):new hs(((t,e)=>{const i=e=>{""!==e.sid&&(this.engine.off(Ts.RoomUpdate,i),t(e.sid))};this.engine.on(Ts.RoomUpdate,i),this.once(ws.Disconnected,(()=>{this.engine.off(Ts.RoomUpdate,i),e(new Cs("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 Aa(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Ts.ParticipantUpdate,this.handleParticipantUpdates).on(Ts.RoomUpdate,this.handleRoomUpdate).on(Ts.SpeakersChanged,this.handleSpeakersChanged).on(Ts.StreamStateChanged,this.handleStreamStateUpdate).on(Ts.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Ts.SubscriptionError,this.handleSubscriptionError).on(Ts.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Ts.MediaTrackAdded,((t,e,i)=>{this.onTrackAdded(t,e,i)})).on(Ts.Disconnected,(t=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t)})).on(Ts.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Ts.DataPacketReceived,this.handleDataPacket).on(Ts.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Ea.SignalReconnecting)&&this.emit(ws.SignalReconnecting)})).on(Ts.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Ea.Connected)&&this.emit(ws.Reconnected)})).on(Ts.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Ea.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Ts.Restarting,this.handleRestarting).on(Ts.SignalRestarted,this.handleSignalRestarted).on(Ts.Offline,(()=>{this.setAndEmitConnectionState(Ea.Reconnecting)&&this.emit(ws.Reconnecting)})).on(Ts.DCBufferStatusChanged,((t,e)=>{this.emit(ws.DCBufferStatusChanged,t,e)})).on(Ts.LocalTrackSubscribed,(t=>{const e=this.localParticipant.getTrackPublications().find((e=>{let{trackSid:i}=e;return i===t}));e?(this.localParticipant.emit(ks.LocalTrackSubscribed,e),this.emitWhenConnected(ws.LocalTrackSubscribed,e,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})).on(Ts.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(ws.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 ao.getInstance().getDevices(t,e)}prepareConnection(t,e){return Zi(this,void 0,void 0,(function*(){if(this.state===Ea.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(yr(new URL(t))&&e){this.regionUrlProvider=new Qo(t,e);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Ea.Disconnected&&(this.regionUrl=i,yield fetch(Nr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Nr(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 Zi(this,void 0,void 0,(function*(){let i,n=()=>Zi(this,void 0,void 0,(function*(){}));switch(t){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Oi({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Oi({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Oi({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Oi({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=()=>Zi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Oi({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Zi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Oi({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 Oi({scenario:{case:"switchCandidateProtocol",value:"force-tls"===t?2:1}}),n=()=>Zi(this,void 0,void 0,(function*(){const t=this.engine.client.onLeave;t&&t(new ni({reason:Wt.CLIENT_INITIATED,action:si.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===e||"number"!=typeof e)throw new Error("subscriber-bandwidth requires a number as argument");i=new Oi({scenario:{case:"subscriberBandwidth",value:Br(e)}});break;case"leave-full-reconnect":i=new Oi({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 Zi(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,h,d;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===nr.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===nr.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,!lr()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(e=null!==(o=yield ao.getInstance().normalizeDeviceId("audiooutput",e))&&void 0!==o?o:""),null!==(a=(d=i.options).audioOutput)&&void 0!==a||(d.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===(h=i.audioContext)||void 0===h||h.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(ws.ActiveDeviceChanged,t,e)),l}()}))}setupLocalParticipantEvents(){this.localParticipant.on(ks.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ks.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ks.AttributesChanged,this.onLocalAttributesChanged).on(ks.TrackMuted,this.onLocalTrackMuted).on(ks.TrackUnmuted,this.onLocalTrackUnmuted).on(ks.LocalTrackPublished,this.onLocalTrackPublished).on(ks.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ks.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ks.MediaDevicesError,this.onMediaDevicesError).on(ks.AudioStreamAcquired,this.startAudio).on(ks.ChatMessage,this.onLocalChatMessageSent).on(ks.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===Ea.Connecting||this.state===Ea.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(ws.Reconnected,n),this.off(ws.Connected,n),this.off(ws.Disconnected,s)};return this.once(ws.Reconnected,n),this.once(ws.Connected,n),void this.once(ws.Disconnected,s)}if(this.state===Ea.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 h=a.addSubscribedMediaTrack(t,o,e,i,c);(null==h?void 0:h.isEncrypted)&&!this.e2eeManager&&this.emit(ws.EncryptionError,new Error("Encrypted ".concat(h.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!==Ea.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(ks.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ks.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ks.AttributesChanged,this.onLocalAttributesChanged).off(ks.TrackMuted,this.onLocalTrackMuted).off(ks.TrackUnmuted,this.onLocalTrackUnmuted).off(ks.LocalTrackPublished,this.onLocalTrackPublished).off(ks.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ks.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ks.MediaDevicesError,this.onMediaDevicesError).off(ks.AudioStreamAcquired,this.startAudio).off(ks.ChatMessage,this.onLocalChatMessageSent).off(ks.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),gr()&&(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(Ea.Disconnected),this.emit(ws.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(ws.ParticipantDisconnected,e),e.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(e.identity))}handleIncomingRpcRequest(t,e,i,n,s,r){return Zi(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(t,e),1!==r)return void(yield this.engine.publishRpcResponse(t,e,null,Ho.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(t,e,null,Ho.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:e,callerIdentity:t,payload:n,responseTimeout:s});Ko(r)>15360?(a=Ho.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=r}catch(t){t instanceof Ho?a=t:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),t),a=Ho.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(t,e,c,a)}))}selectDefaultDevices(){return Zi(this,void 0,void 0,(function*(){var t,e,i;const n=ao.getInstance().previousDevices,s=yield ao.getInstance().getDevices(void 0,!1),r=us();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(ws.ActiveDeviceChanged,t.kind,t.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let r of o){const o=Hs(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)),h=this.getActiveDevice(r);h===(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)!==h?yield this.switchActiveDevice(r,c[0].deviceId):"audioinput"===r&&!mr()||"videoinput"===r||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(r)))||"audiooutput"===r&&mr()||(yield this.switchActiveDevice(r,c[0].deviceId))}}))}acquireAudioContext(){return Zi(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=Qs())&&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(),ar(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(ws.AudioPlaybackStatusChanged,i))}))}createParticipant(t,e){var i;let n;return n=e?Ha.fromParticipantInfo(this.engine.client,e,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new Ha(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(ws.ParticipantConnected,i),i.on(ks.TrackPublished,(t=>{this.emitWhenConnected(ws.TrackPublished,t,i)})).on(ks.TrackSubscribed,((t,e)=>{t.kind===nr.Kind.Audio?(t.on(Ss.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(Ss.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===nr.Kind.Video&&(t.on(Ss.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(Ss.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ws.TrackSubscribed,t,e,i)})).on(ks.TrackUnpublished,(t=>{this.emit(ws.TrackUnpublished,t,i)})).on(ks.TrackUnsubscribed,((t,e)=>{this.emit(ws.TrackUnsubscribed,t,e,i)})).on(ks.TrackMuted,(t=>{this.emitWhenConnected(ws.TrackMuted,t,i)})).on(ks.TrackUnmuted,(t=>{this.emitWhenConnected(ws.TrackUnmuted,t,i)})).on(ks.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(ws.ParticipantMetadataChanged,t,i)})).on(ks.ParticipantNameChanged,(t=>{this.emitWhenConnected(ws.ParticipantNameChanged,t,i)})).on(ks.AttributesChanged,(t=>{this.emitWhenConnected(ws.ParticipantAttributesChanged,t,i)})).on(ks.ConnectionQualityChanged,(t=>{this.emitWhenConnected(ws.ConnectionQualityChanged,t,i)})).on(ks.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(ws.ParticipantPermissionsChanged,t,i)})).on(ks.TrackSubscriptionStatusChanged,((t,e)=>{this.emitWhenConnected(ws.TrackSubscriptionStatusChanged,t,e,i)})).on(ks.TrackSubscriptionFailed,((t,e)=>{this.emit(ws.TrackSubscriptionFailed,t,i,e)})).on(ks.TrackSubscriptionPermissionChanged,((t,e)=>{this.emitWhenConnected(ws.TrackSubscriptionPermissionChanged,t,e,i)})).on(ks.Active,(()=>{this.emitWhenConnected(ws.ParticipantActive,i),i.kind===te.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&&Gr(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=Ds.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,Wt.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ds.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(ws.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=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];if(this.state===Ea.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===Ea.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){return Zi(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 Kt({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:x.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Zt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ws.SignalConnected),this.emit(ws.Connected),this.setAndEmitConnectionState(Ea.Connected),r.video){const t=new za(nr.Kind.Video,new se({source:qt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ft.AUDIO,name:"video-dummy"}),new ma(r.useRealTracks&&(null===(e=window.navigator.mediaDevices)||void 0===e?void 0:e.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Ir(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(ks.LocalTrackPublished,t)}if(r.audio){const t=new za(nr.Kind.Audio,new se({source:qt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ft.AUDIO}),new na(r.useRealTracks&&(null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Pr(),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(ks.LocalTrackPublished,t)}for(let t=0;t<o.count-1;t+=1){let e=new Zt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(t),state:Xt.ACTIVE,tracks:[],joinedAt:x.parse(Date.now())});const i=this.getOrCreateParticipant(e.identity,e);if(o.video){const n=Ir(160*(null!==(s=o.aspectRatios[t%o.aspectRatios.length])&&void 0!==s?s:1),160,!1,!0),r=new se({source:qt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ft.AUDIO});i.addSubscribedMediaTrack(n,r.sid,new MediaStream([n]),new RTCRtpReceiver),e.tracks=[...e.tracks,r]}if(o.audio){const t=Pr(),n=new se({source:qt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ft.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=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];if(t!==ws.ActiveSpeakersChanged&&t!==ws.TranscriptionReceived){const e=Ya(i).filter((t=>void 0!==t));t!==ws.TrackSubscribed&&t!==ws.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 Ya(t){return t.map((t=>{if(t)return Array.isArray(t)?Ya(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t}))}function $a(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 String(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}Ka.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"}(Oa||(Oa={})),new TextEncoder,new TextDecoder;class Za extends Error{constructor(t,e){var i;super(t,e),$a(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}function Xa(){return Xa=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},Xa.apply(null,arguments)}$a(Za,"code","ERR_JOSE_GENERIC"),$a(class extends Za{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}}),$a(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),$a(this,"claim",void 0),$a(this,"reason",void 0),$a(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=e}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),$a(class extends Za{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}}),$a(this,"code","ERR_JWT_EXPIRED"),$a(this,"claim",void 0),$a(this,"reason",void 0),$a(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=e}},"code","ERR_JWT_EXPIRED"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED"),$a(class extends Za{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),$a(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID"),$a(class extends Za{constructor(){super(...arguments),$a(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID"),$a(class extends Za{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),$a(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY"),$a(class extends Za{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),$a(this,Symbol.asyncIterator,void 0),$a(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS"),$a(class extends Za{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),$a(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT"),$a(class extends Za{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),$a(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const tc=new Uint8Array(0);class ec{static getFullOptions(t){return Xa({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:String(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):String(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 tc}getOutputByteFrequencyData(){return tc}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 ic{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 nc(t){const[e,i]=t.split("_");if(!["pcm","ulaw"].includes(e))throw new Error(`Invalid format: ${t}`);const n=Number.parseInt(i);if(Number.isNaN(n))throw new Error(`Invalid sample rate: ${i}`);return{format:e,sampleRate:n}}const sc="0.13.0";function rc(t){return!!t.type}const oc="conversation_initiation_client_data";function ac(t){var e;const i={type:oc};var n,s,r,o,a,c,h,d;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==(h=t.overrides.tts)?void 0:h.similarityBoost},conversation:{text_only:null==(d=t.overrides.conversation)?void 0:d.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 cc 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 hc extends ic{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(!rc(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:String(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)||sc,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 h=["convai"];t.authorization&&h.push(`bearer.${t.authorization}`),e=new WebSocket(o,h);const d=await new Promise(((i,n)=>{e.addEventListener("open",(()=>{var i;const n=ac(t);null==(i=e)||i.send(JSON.stringify(n))}),{once:!0}),e.addEventListener("error",(()=>{setTimeout((()=>n(new cc("The connection was closed due to a socket error."))),0)})),e.addEventListener("close",(t=>{n(new cc(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);rc(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}=d,v=nc(null!=f?f:"pcm_16000"),m=nc(u);return new hc(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 dc(t){const e=new Uint8Array(t);return window.btoa(String.fromCharCode(...e))}function lc(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 uc=new Map;function fc(t,e){return async(i,n)=>{const s=uc.get(t);if(s)return i.addModule(s);if(n)try{return await i.addModule(n),void uc.set(t,n)}catch(e){throw new 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 uc.set(t,o)}catch(t){URL.revokeObjectURL(o)}try{const n=`data:application/javascript;base64,${btoa(e)}`;await i.addModule(n),uc.set(t,n)}catch(e){throw new 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 vc=fc("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 mc extends ic{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 new 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)||sc,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}`,h=await fetch(c);if(!h.ok)throw new Error(`ElevenLabs API returned ${h.status} ${h.statusText}`);if(e=(await h.json()).token,!e)throw new Error("No conversation token received from API")}catch(e){let i=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes("401")&&(i="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error(`Failed to fetch conversation token for agent ${t.agentId}: ${i}`)}}var r;const o=new Ka;try{const i=`room_${Date.now()}`,n=nc("pcm_48000"),s=nc("pcm_48000"),r=new mc(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(ws.Connected,e),t()};o.on(ws.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 h=ac(t);return r.debug({type:oc,message:h}),await r.sendMessage(h),r}catch(t){throw await o.disconnect(),t}}setupRoomEventListeners(){var t=this;this.room.on(ws.Connected,(async function(){t.isConnected=!0,console.info("WebRTC room connected")})),this.room.on(ws.Disconnected,(t=>{this.isConnected=!1,this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:null==t?void 0:t.toString()})})})),this.room.on(ws.ConnectionStateChanged,(t=>{t===Ea.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:`LiveKit connection state changed to ${t}`,context:new Event("connection_state_changed")}))})),this.room.on(ws.DataReceived,((t,e)=>{try{const e=JSON.parse((new TextDecoder).decode(t));if("audio"===e.type)return;rc(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(ws.TrackSubscribed,(async function(e,i,n){if(e.kind===nr.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(ws.ActiveSpeakersChanged,(async function(e){t.updateMode(e.length>0&&e[0].identity.startsWith("agent")?"speaking":"listening")})),this.room.on(ws.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(nr.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 vc(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=dc(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 new 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 new Error("Cannot change input device: room not connected or no local participant");try{const e=this.room.localParticipant.getTrackPublication(nr.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 Zi(this,void 0,void 0,(function*(){return(yield Ja({audio:null==t||t,video:!1}))[0]}))}(i);await this.room.localParticipant.publishTrack(n,{name:"microphone",source:nr.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 pc(t){const e=function(t){return t.connectionType?t.connectionType:"conversationToken"in t&&t.conversationToken?"webrtc":"websocket"}(t);switch(e){case"websocket":return hc.create(t);case"webrtc":return mc.create(t);default:throw new Error(`Unknown connection type: ${e}`)}}function gc(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}async function bc(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(gc()){var n;e=null!=(n=t.ios)?n:e}e>0&&await new Promise((t=>setTimeout(t,e)))}class yc extends ec{static async startSession(t){const e=ec.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 bc(e.connectionDelay),i=await pc(t),new yc(e,i)}catch(t){var n;throw e.onStatusChange&&e.onStatusChange({status:"disconnected"}),null==(n=i)||n.close(),t}}}const wc={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}};class kc{static async create({sampleRate:t,format:e,preferHeadphonesForIosDevices:i,inputDeviceId:n,workletPaths:s,libsampleratePath:r}){let o=null,a=null;try{const c=Xa({sampleRate:{ideal:t}},wc);if(gc()&&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=kc.getDeviceIdConstraint(n));const h=navigator.mediaDevices.getSupportedConstraints().sampleRate;o=new window.AudioContext(h?{sampleRate:t}:{});const d=o.createAnalyser();if(!h){const t=r||"https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js";await o.audioWorklet.addModule(t)}await vc(o.audioWorklet,null==s?void 0:s.rawAudioProcessor);const l=Xa({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(d),d.connect(f),await o.resume(),new kc(o,d,f,a,u)}catch(t){var c,h;throw null==(c=a)||c.getTracks().forEach((t=>{t.stop()})),null==(h=o)||h.close(),t}}static getDeviceIdConstraint(t){if(t)return gc()?{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=Xa({},wc);t&&(e.deviceId=kc.getDeviceIdConstraint(t));const i=Xa({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 Tc=fc("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 Sc{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 Tc(s.audioWorklet,null==n?void 0:n.audioConcatProcessor);const h=new AudioWorkletNode(s,"audioConcatProcessor");return h.port.postMessage({type:"setFormat",format:e}),h.connect(a),await s.resume(),i&&r.setSinkId&&await r.setSinkId(i),new Sc(s,o,a,h,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 new 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 Ec extends ec{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=ec.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 Ec.requestWakeLock());try{var c;return o=await navigator.mediaDevices.getUserMedia({audio:!0}),await bc(i.connectionDelay),s=await pc(t),[n,r]=await Promise.all([kc.create(Xa({},s.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),Sc.create(Xa({},s.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),null==(c=o)||c.getTracks().forEach((t=>{t.stop()})),o=null,new Ec(i,s,n,r,a)}catch(t){var h,d,l,u;i.onStatusChange&&i.onStatusChange({status:"disconnected"}),null==(h=o)||h.getTracks().forEach((t=>{t.stop()})),null==(d=s)||d.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:dc(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:lc(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 mc?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&&Ec.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 mc||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 mc?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 mc?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 hc)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 mc&&await this.connection.setAudioInputDevice(n||""),await this.input.close();const s=await kc.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 hc)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 mc&&await this.connection.setAudioOutputDevice(i||""),await this.output.close();const n=await Sc.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 Oc,Ac,xc;!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"}(Oc||(Oc={})),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"}(Ac||(Ac={})),function(t){t.MANUAL="manual",t.VAD="vad"}(xc||(xc={}));const Cc=class{constructor(i){t(this,i),this.conversationStarted=e(this,"conversationStarted"),this.conversationEnded=e(this,"conversationEnded"),this.widgetError=e(this,"widgetError"),this.statusChanged=e(this,"statusChanged"),this.messageReceived=e(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(new Error("Connection timeout"))}),15e3),a=t?yc:Ec;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(new 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:String(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,n=this.getThemeColors(),s={"--sl-primary":this.primaryColor,"--sl-bg":n.bg,"--sl-text":n.text,"--sl-muted":n.muted,"--sl-border":n.border,"--sl-surface":n.surface};return"inline"===this.variant?i("div",{class:"sl-widget sl-inline",style:s},this.renderCard(t)):i("div",{class:`sl-widget sl-floating ${this.getPositionClasses()}`,style:s},this.isExpanded?i("div",{class:"sl-card"},this.renderCard(t)):i("div",{class:"sl-fab-pill"},i("div",{class:"sl-fab-avatar"},this.avatarUrl?i("img",{src:this.avatarUrl,alt:"",class:"sl-fab-avatar-img"}):i("staylift-orb",{size:48,primaryColor:this.primaryColor,inputVolume:this.inputVolume,outputVolume:this.outputVolume,isActive:e})),i("div",{class:"sl-fab-content"},i("span",{class:"sl-fab-prompt"},this.fabPrompt),i("button",{class:"sl-fab-btn",onClick:this.handleToggleExpand},i("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("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 i("div",{class:"sl-terms"},i("div",{class:"sl-terms-content"},i("h3",{class:"sl-terms-title"},this.t("termsTitle")),i("p",{class:"sl-terms-text"},this.t("termsText")),i("p",{class:"sl-terms-warning"},this.t("termsWarning"))),i("div",{class:"sl-terms-actions"},i("button",{class:"sl-terms-btn sl-terms-btn--decline",onClick:this.handleDeclineTerms},this.t("termsDecline")),i("button",{class:"sl-terms-btn sl-terms-btn--agree",onClick:this.handleAcceptTerms},this.t("termsAgree"))))}renderHeader(t){return i("div",{class:"sl-header"},i("div",{class:"sl-header-left"},i("div",{class:"sl-orb-ring"},this.avatarUrl?i("img",{src:this.avatarUrl,alt:"",class:"sl-header-avatar-img"}):i("staylift-orb",{size:40,primaryColor:this.primaryColor,inputVolume:this.inputVolume,outputVolume:this.outputVolume,isActive:"connected"===this.status&&!this.isTextOnlyMode})),i("div",{class:"sl-header-text"},i("span",{class:"sl-title"},this.brandName),i("span",{class:"sl-subtitle"},this.errorMessage?i("span",{class:"sl-error"},this.errorMessage):"disconnected"===this.status?this.t("tapToStart"):"connected"===this.status?i("span",{class:"sl-connected"},this.t("connected")):t?i("span",{class:"sl-shimmer"},this.status):null))),i("div",{class:"sl-header-right"},i("div",{class:`sl-dot ${"connected"===this.status?"sl-dot--active":""} ${t?"sl-dot--pulse":""}`}),"floating"===this.variant&&i("button",{class:"sl-close",onClick:this.handleToggleExpand},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("path",{d:"M18 6L6 18M6 6l12 12"})))))}renderContent(){const t="connecting"===this.status,e="connected"===this.status;return i("div",{class:"sl-content",ref:t=>this.messagesContainer=t??null},0===this.messages.length?i("div",{class:"sl-empty"},i("staylift-orb",{size:48,primaryColor:this.primaryColor,isActive:!1}),i("h3",{class:"sl-empty-title"},this.t(t?"starting":e?"talkOrType":"emptyTitle")),i("p",{class:"sl-empty-desc"},this.t(t?"connecting":e?"ready":"emptyDesc"))):this.messages.map(((t,e)=>i("div",{class:`sl-msg sl-msg--${t.role}`,key:e},i("div",{class:"sl-msg-row"},i("div",{class:"sl-msg-bubble"},t.content)),"assistant"===t.role&&i("div",{class:"sl-msg-actions"},i("button",{class:"sl-action",onClick:()=>this.copyToClipboard(t.content,e)},this.copiedIndex===e?i("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("polyline",{points:"20 6 9 17 4 12"})):i("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),i("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,n="connected"===this.status&&!this.isTextOnlyMode,s="connected"===this.status&&this.isTextOnlyMode;return i("div",{class:"sl-footer"},e&&i("div",{class:"sl-mode-toggle"},i("button",{class:"sl-mode-btn "+("text"===this.selectedMode?"sl-mode-btn--active":""),onClick:()=>this.selectedMode="text"},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("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")),i("button",{class:"sl-mode-btn "+("voice"===this.selectedMode?"sl-mode-btn--active":""),onClick:()=>this.selectedMode="voice"},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),i("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),i("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),i("line",{x1:"8",y1:"23",x2:"16",y2:"23"})),this.t("modeVoice"))),s&&i("div",{class:"sl-input-row"},i("button",{class:"sl-btn sl-btn--end",onClick:()=>this.handleTextButton(),disabled:t,title:this.t("endText")},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),i("line",{x1:"6",y1:"6",x2:"18",y2:"18"}))),i("input",{type:"text",class:"sl-input",placeholder:this.t("placeholder"),value:this.inputText,onInput:this.handleInputChange,onKeyDown:this.handleInputKeyDown,disabled:t}),i("button",{class:"sl-btn",onClick:()=>this.handleSendText(),disabled:!this.inputText.trim()||t},i("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),i("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})))),"text"===this.selectedMode&&e&&i("div",{class:"sl-voice-controls"},i("button",{class:"sl-voice-btn",onClick:()=>this.handleTextButton(),disabled:t},i("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("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&&i("div",{class:"sl-voice-controls"},i("button",{class:"sl-voice-btn",onClick:()=>this.handleVoiceButton(),disabled:t},i("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),i("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),i("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),i("line",{x1:"8",y1:"23",x2:"16",y2:"23"})),this.t(t?"connecting":"startVoice"))),n&&i("div",{class:"sl-voice-controls"},i("button",{class:"sl-voice-btn sl-voice-btn--end",onClick:()=>this.handleVoiceButton(),disabled:t},i("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},i("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"}),i("line",{x1:"22",y1:"2",x2:"2",y2:"22"})),this.t("endVoice"))),this.showBranding&&i("div",{class:"sl-branding"},i("a",{href:"https://stayliftnow.com",target:"_blank",rel:"noopener noreferrer"},i("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 n(this)}};Cc.style=":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}}";export{Cc as staylift_widget}