@speechos/client 0.2.9 → 0.2.11

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,12 +1,12 @@
1
- !function(e){"use strict";function t(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(e)}var i=Object.defineProperty,n=(e,t,n)=>((e,t,n)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);let s=class{constructor(){n(this,"_locking"),n(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}};function o(e,t){if(!e)throw new Error(t)}function r(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function a(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function c(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const d=Symbol("@bufbuild/protobuf/enum-type");function l(e){const t=e[d];return o(t,"missing enum type on enum object"),t}function u(e,t,i,n){e[d]=h(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function h(e,t,i){const n=Object.create(null),s=Object.create(null),o=[];for(const e of t){const t=m(e);o.push(t),n[e.name]=t,s[e.no]=t}return{typeName:e,values:o,findName:e=>n[e],findNumber:e=>s[e]}}function p(e,t,i){const n={};for(const e of t){const t=m(e);n[t.localName]=t.no,n[t.no]=t.localName}return u(n,e,t),n}function m(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class g{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function f(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function v(e,t,i){for(let n=0;n<28;n+=7){const s=e>>>n,o=!(s>>>7==0&&0==t),r=255&(o?128|s:s);if(i.push(r),!o)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),o=255&(s?128|n:n);if(i.push(o),!s)return}i.push(t>>>31&1)}}const b=4294967296;function y(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function o(t,o){const r=Number(e.slice(t,o));s*=i,n=n*i+r,n>=b&&(s+=n/b|0,n%=b)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?T(n,s):S(n,s)}function k(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(b*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,o=i+8147497*n,r=2*n;const a=1e7;return s>=a&&(o+=Math.floor(s/a),s%=a),o>=a&&(r+=Math.floor(o/a),o%=a),r.toString()+C(o)+C(s)}function S(e,t){return{lo:0|e,hi:0|t}}function T(e,t){return t=~t,e?e=1+~e:t+=1,S(e,t)}const C=e=>{const t=String(e);return"0000000".slice(t.length)+t};function w(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function E(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const x=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>o(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>o(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),y(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),y(e)),dec:(e,t)=>function(e,t){let i=S(e,t);const n=2147483648&i.hi;n&&(i=T(i.lo,i.hi));const s=k(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>k(e,t)}}();var R,P,I;function O(e,t,i){if(t===i)return!0;if(e==R.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case R.UINT64:case R.FIXED64:case R.INT64:case R.SFIXED64:case R.SINT64:return t==i}return!1}function A(e,t){switch(e){case R.BOOL:return!1;case R.UINT64:case R.FIXED64:case R.INT64:case R.SFIXED64:case R.SINT64:return 0==t?x.zero:"0";case R.DOUBLE:case R.FLOAT:return 0;case R.BYTES:return new Uint8Array(0);case R.STRING:return"";default:return 0}}function _(e,t){switch(e){case R.BOOL:return!1===t;case R.STRING:return""===t;case R.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(R||(R={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(P||(P={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(I||(I={}));class M{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(a(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return r(e),w(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){c(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){a(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){r(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return r(e),w(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=x.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=x.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=x.enc(e);return v(t.lo,t.hi,this.buf),this}sint64(e){let t=x.enc(e),i=t.hi>>31;return v(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=x.uEnc(e);return v(t.lo,t.hi,this.buf),this}}class D{constructor(e,t){this.varint64=f,this.uint32=E,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case I.Varint:for(;128&this.buf[this.pos++];);break;case I.Bit64:this.pos+=4;case I.Bit32:this.pos+=4;break;case I.LengthDelimited:let i=this.uint32();this.pos+=i;break;case I.StartGroup:for(;;){const[e,i]=this.tag();if(i===I.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return x.dec(...this.varint64())}uint64(){return x.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,x.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return x.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return x.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function N(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return A(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let L="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),U=[];for(let e=0;e<L.length;e++)U[L[e].charCodeAt(0)]=e;U["-".charCodeAt(0)]=L.indexOf("+"),U["_".charCodeAt(0)]=L.indexOf("/");const F={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,o=0,r=0;for(let t=0;t<e.length;t++){if(i=U[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":o=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(o){case 0:r=i,o=1;break;case 1:n[s++]=r<<2|(48&i)>>4,r=i,o=2;break;case 2:n[s++]=(15&r)<<4|(60&i)>>2,r=i,o=3;break;case 3:n[s++]=(3&r)<<6|i,o=0}}if(1==o)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let o=0;o<e.length;o++)switch(t=e[o],n){case 0:i+=L[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=L[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=L[s|t>>6],i+=L[63&t],n=0}return n&&(i+=L[s],i+="=",1==n&&(i+="=")),i}};function j(e,t,i){V(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[o,r]=N(t);for(const e of s)t.runtime.bin.readField(o,n.readerFactory(e.data),t.field,e.wireType,n);return r()}function B(e,t,i,n){V(t,e);const s=t.runtime.bin.makeReadOptions(n),o=t.runtime.bin.makeWriteOptions(n);if($(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const r=o.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,r,o);const c=s.readerFactory(r.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function $(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function V(e,t){o(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function q(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!_(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function H(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?A(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function z(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(g.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function W(e,t){return z(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}R.DOUBLE,R.FLOAT,R.INT64,R.UINT64,R.INT32,R.UINT32,R.BOOL,R.STRING,R.BYTES;const G={ignoreUnknownFields:!1},K={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function J(e){return e?Object.assign(Object.assign({},G),e):G}function Y(e){return e?Object.assign(Object.assign({},K),e):K}const Q=Symbol(),X=Symbol();function Z(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function ee(e,t,i,n,s){let r=i.localName;if(i.repeated){if(o("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(t)));const a=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=ne(i.T,e,n.ignoreUnknownFields,!0);t!==X&&a.push(t);break;case"scalar":try{a.push(ie(i.T,e,i.L,!0))}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)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(t)));const o=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let a;try{a=te(i.K,e)}catch(e){let n="cannot decode map key for 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)}switch(i.V.kind){case"message":o[a]=i.V.T.fromJson(r,n);break;case"enum":const e=ne(i.V.T,r,n.ignoreUnknownFields,!0);e!==X&&(o[a]=e);break;case"scalar":try{o[a]=ie(i.V.T,r,P.BIGINT,!0)}catch(e){let n="cannot decode map value for 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 switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const o=i.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let a=e[r];z(a)?a.fromJson(t,n):(e[r]=a=o.fromJson(t,n),o.fieldWrapper&&!i.oneof&&(e[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=ne(i.T,t,n.ignoreUnknownFields,!1);switch(c){case Q:H(i,e);break;case X:break;default:e[r]=c}break;case"scalar":try{const n=ie(i.T,t,i.L,!1);if(n===Q)H(i,e);else e[r]=n}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)}}}function te(e,t){if(e===R.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return ie(e,t,P.BIGINT,!0).toString()}function ie(e,t,i,n){if(null===t)return n?A(e,i):Q;switch(e){case R.DOUBLE:case R.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==R.FLOAT&&c(n),n;case R.INT32:case R.FIXED32:case R.SFIXED32:case R.SINT32:case R.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==R.UINT32||e==R.FIXED32?a(s):r(s),s;case R.INT64:case R.SFIXED64:case R.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=x.parse(t);return i?o.toString():o;case R.FIXED64:case R.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const d=x.uParse(t);return i?d.toString():d;case R.BOOL:if("boolean"!=typeof t)break;return t;case R.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case R.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return F.dec(t)}throw new Error}function ne(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Q;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return X}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Z(t)))}function se(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function oe(e,t,i){if("map"==e.kind){o("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,i]of s)n[t.toString()]=ae(e.V.T,i);break;case"message":for(const[e,t]of s)n[e.toString()]=t.toJson(i);break;case"enum":const t=e.V.T;for(const[e,o]of s)n[e.toString()]=re(t,o,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){o(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(ae(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(re(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return ae(e.T,t);case"enum":return re(e.T,t,i.enumAsInteger);case"message":return W(e.T,t).toJson(i)}}function re(e,t,i){var n;if(o("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function ae(e,t){switch(e){case R.INT32:case R.SFIXED32:case R.SINT32:case R.FIXED32:case R.UINT32:return o("number"==typeof t),t;case R.FLOAT:case R.DOUBLE:return o("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case R.STRING:return o("string"==typeof t),t;case R.BOOL:return o("boolean"==typeof t),t;case R.UINT64:case R.FIXED64:case R.INT64:case R.SFIXED64:case R.SINT64:return o("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case R.BYTES:return o(t instanceof Uint8Array),F.enc(t)}}const ce=Symbol("@bufbuild/protobuf/unknown-fields"),de={readUnknownFields:!0,readerFactory:e=>new D(e)},le={writeUnknownFields:!0,writerFactory:()=>new M};function ue(e){return e?Object.assign(Object.assign({},de),e):de}function he(e){return e?Object.assign(Object.assign({},le),e):le}function pe(e,t,i,n,s){let{repeated:o,localName:r}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=r&&delete e.value,e.case=r,r="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?R.INT32:i.T;let c=fe;if("scalar"==i.kind&&i.L>0&&(c=ge),o){let i=e[r];if(n==I.LengthDelimited&&a!=R.STRING&&a!=R.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[r]=c(t,a);break;case"message":const d=i.T;o?e[r].push(me(t,new d,s,i)):z(e[r])?me(t,e[r],s,i):(e[r]=me(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[r]=d.fieldWrapper.unwrapField(e[r])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let o,r;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:o=fe(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=fe(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=me(t,new e.V.T,i,void 0)}}}void 0===o&&(o=A(e.K,P.BIGINT));"string"!=typeof o&&"number"!=typeof o&&(o=o.toString());if(void 0===r)switch(e.V.kind){case"scalar":r=A(e.V.T,P.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[o,r]}(i,t,s);e[r][l]=u}}function me(e,t,i,n){const s=t.getType().runtime.bin,o=null==n?void 0:n.delimited;return s.readMessage(t,e,o?n.no:e.uint32(),i,o),t}function ge(e,t){const i=fe(e,t);return"bigint"==typeof i?i.toString():i}function fe(e,t){switch(t){case R.STRING:return e.string();case R.BOOL:return e.bool();case R.DOUBLE:return e.double();case R.FLOAT:return e.float();case R.INT32:return e.int32();case R.INT64:return e.int64();case R.UINT64:return e.uint64();case R.FIXED64:return e.fixed64();case R.BYTES:return e.bytes();case R.FIXED32:return e.fixed32();case R.SFIXED32:return e.sfixed32();case R.SFIXED64:return e.sfixed64();case R.SINT64:return e.sint64();case R.UINT32:return e.uint32();case R.SINT32:return e.sint32()}}function ve(e,t,i,n){o(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?R.INT32:e.T;if(s)if(o(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,I.LengthDelimited).fork();let[,s]=Se(t);for(let t=0;t<n.length;t++)e[s](n[t]);e.join()}(i,r,e.no,t);else for(const n of t)ke(i,r,e.no,n);else ke(i,r,e.no,t);break;case"message":if(s){o(Array.isArray(t));for(const s of t)ye(i,n,e,s)}else ye(i,n,e,t);break;case"map":o("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))be(i,n,e,s,o)}}function be(e,t,i,n,s){e.tag(i.no,I.LengthDelimited),e.fork();let r=n;switch(i.K){case R.INT32:case R.FIXED32:case R.UINT32:case R.SFIXED32:case R.SINT32:r=Number.parseInt(n);break;case R.BOOL:o("true"==n||"false"==n),r="true"==n}switch(ke(e,i.K,1,r),i.V.kind){case"scalar":ke(e,i.V.T,2,s);break;case"enum":ke(e,R.INT32,2,s);break;case"message":o(void 0!==s),e.tag(2,I.LengthDelimited).bytes(s.toBinary(t))}e.join()}function ye(e,t,i,n){const s=W(i.T,n);i.delimited?e.tag(i.no,I.StartGroup).raw(s.toBinary(t)).tag(i.no,I.EndGroup):e.tag(i.no,I.LengthDelimited).bytes(s.toBinary(t))}function ke(e,t,i,n){o(void 0!==n);let[s,r]=Se(t);e.tag(i,s)[r](n)}function Se(e){let t=I.Varint;switch(e){case R.BYTES:case R.STRING:t=I.LengthDelimited;break;case R.DOUBLE:case R.FIXED64:case R.SFIXED64:t=I.Bit64;break;case R.FIXED32:case R.SFIXED32:case R.FLOAT:t=I.Bit32}return[t,R[e].toLowerCase()]}function Te(e){if(void 0===e)return e;if(z(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ce(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class we{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Ee(e,t){const i=Re(e);return t?i:_e(Ae(i))}const xe=Re;function Re(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const Pe=new Set(["constructor","toString","toJSON","valueOf"]),Ie=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Oe=e=>"".concat(e,"$"),Ae=e=>Ie.has(e)?Oe(e):e,_e=e=>Pe.has(e)?Oe(e):e;class Me{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Ee(e,!1)}addField(e){o(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const De=(Ne=e=>new we(e,e=>function(e){var t,i,n,s,o,r;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Ee(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:xe(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:P.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(o=d.req)&&void 0!==o&&o,e.opt=null!==(r=d.opt)&&void 0!==r&&r,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=R.BYTES&&d.T!=R.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Me(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e)),Le=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=A(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:J,makeWriteOptions:Y,readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Z(t)));n=null!=n?n:new e;const s=new Map,o=i.typeRegistry;for(const[r,a]of Object.entries(t)){const t=e.fields.findJsonName(r);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(r,'"'));s.set(t.oneof,r)}ee(n,a,t,i,e)}else{let t=!1;if((null==o?void 0:o.findExtension)&&r.startsWith("[")&&r.endsWith("]")){const s=o.findExtension(r.substring(1,r.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,o]=N(s);ee(e,a,s.field,i,s),B(n,s,o(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(r,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!q(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!se(s))continue}const i=oe(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const o=t.typeRegistry;if(null==o?void 0:o.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const r=o.findExtensionFor(i.typeName,s.no);if(r&&$(e,r)){const i=j(e,r,t),s=oe(r.field,i,t);void 0!==s&&(n[r.field.jsonName]=s)}}}catch(e){const t=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),n=e instanceof Error?e.message:String(e);throw new Error(t+(n.length>0?": ".concat(n):""))}return n},readScalar:(e,t,i)=>ie(e,t,null!=i?i:P.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||_(e,t)?ae(e,t):void 0},debug:Z},bin:{makeReadOptions:ue,makeWriteOptions:he,listUnknownFields(e){var t;return null!==(t=e[ce])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[ce]},writeUnknownFields(e,t){const i=e[ce];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[ce])||(s[ce]=[]),s[ce].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const o=e.getType(),r=s?t.len:t.pos+i;let a,c;for(;t.pos<r&&([a,c]=t.tag(),!0!==s||c!=I.EndGroup);){const i=o.fields.find(a);if(!i){const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i);continue}pe(e,t,i,c,n)}if(s&&(c!=I.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:pe,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(q(s,e))ve(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&ve(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:u,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,o=e;if(null!=o[i])switch(n.kind){case"oneof":const e=o[i].case;if(void 0===e)continue;const t=n.findField(e);let r=o[i].value;t&&"message"==t.kind&&!z(r,t.T)?r=new t.T(r):t&&"scalar"===t.kind&&t.T===R.BYTES&&(r=Ce(r)),s[i]={case:e,value:r};break;case"scalar":case"enum":let a=o[i];n.T===R.BYTES&&(a=n.repeated?a.map(Ce):Ce(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===R.BYTES)for(const[e,t]of Object.entries(o[i]))s[i][e]=Ce(t);else Object.assign(s[i],o[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(o[i])){let n=o[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=o[i].map(e=>z(e,c)?e:new c(e));else{const e=o[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=Ce(e):s[i]=e:s[i]=z(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every(e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,s[i]));case"scalar":return n.every((t,i)=>O(e.T,t,s[i]));case"enum":return n.every((e,t)=>O(R.INT32,e,s[t]))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=n,i=s;return e.T.fieldWrapper&&(void 0===t||z(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===i||z(i)||(i=e.T.fieldWrapper.wrapField(i))),e.T.equals(t,i);case"enum":return O(R.INT32,n,s);case"scalar":return O(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const o=e.findField(n.case);if(void 0===o)return!0;switch(o.kind){case"message":return o.T.equals(n.value,s.value);case"enum":return O(R.INT32,n.value,s.value);case"scalar":return O(o.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const r=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return r.every(e=>t.equals(n[e],s[e]));case"enum":return r.every(e=>O(R.INT32,n[e],s[e]));case"scalar":const i=e.V.T;return r.every(e=>O(i,n[e],s[e]))}}}),clone(e){const t=e.getType(),i=new t,n=i;for(const i of t.fields.byMember()){const t=e[i.localName];let s;if(i.repeated)s=t.map(Te);else if("map"==i.kind){s=n[i.localName];for(const[e,i]of Object.entries(t))s[e]=Te(i)}else s="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:Te(t.value)}:{case:void 0}:Te(t);n[i.localName]=s}for(const i of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,i.no,i.wireType,i.data);return i}}),{newFieldList:Ne,initFields:Le}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const o=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),r={[o]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[o];return Object.setPrototypeOf(r.prototype,new g),Object.assign(r,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new r).fromBinary(e,t),fromJson:(e,t)=>(new r).fromJson(e,t),fromJsonString:(e,t)=>(new r).fromJsonString(e,t),equals:(t,i)=>e.util.equals(r,t,i)}),r}(this,e,t,i)},makeEnum:p,makeEnumType:h,getEnumType:l,makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Ne,Le;class Ue extends g{constructor(e){super(),this.seconds=x.zero,this.nanos=0,De.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(De.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=x.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return Ue.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ue({seconds:x.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Ue).fromBinary(e,t)}static fromJson(e,t){return(new Ue).fromJson(e,t)}static fromJsonString(e,t){return(new Ue).fromJsonString(e,t)}static equals(e,t){return De.util.equals(Ue,e,t)}}Ue.runtime=De,Ue.typeName="google.protobuf.Timestamp",Ue.fields=De.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Fe=De.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ue},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:je,repeated:!0},{no:5,name:"events",kind:"message",T:$e,repeated:!0}]),je=De.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:Be,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Be=De.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ue},{no:3,name:"value",kind:"scalar",T:2}]),$e=De.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:Ue},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ue,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Ve=De.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),qe=De.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),He=De.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),ze=De.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),We=De.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ge=De.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Ke=De.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"}]),Je=De.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"}]),Ye=De.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Qe=De.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"}]),Xe=De.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:Ze,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:Mt}]),Ze=De.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),et=De.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:De.getEnumType(He),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}]),tt=De.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:De.getEnumType(it)},{no:4,name:"tracks",kind:"message",T:at,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:et},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:De.getEnumType(nt)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:De.getEnumType(Ke)},{no:18,name:"kind_details",kind:"enum",T:De.getEnumType(st),repeated:!0}]),it=De.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),nt=De.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"}]),st=De.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),ot=De.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),rt=De.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:ct,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:De.getEnumType(dt)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),at=De.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:De.getEnumType(qe)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:De.getEnumType(He)},{no:10,name:"layers",kind:"message",T:ct,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:rt,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:De.getEnumType(ot)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Mt},{no:19,name:"audio_features",kind:"enum",T:De.getEnumType(Qe),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:De.getEnumType(Ve)}]),ct=De.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:De.getEnumType(ze)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),dt=De.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"}]),lt=De.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:De.getEnumType(ut)},{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:ft,oneof:"value"},{no:3,name:"speaker",kind:"message",T:mt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:vt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:bt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Fe,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:kt,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:St,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Tt,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ct,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Ut,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Ft,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:jt,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:ht,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),ut=De.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),ht=De.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:De.getEnumType(ot)},{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}]),pt=De.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:ft,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:kt,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:St,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Tt,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Ct,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Ut,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Ft,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:jt,oneof:"value"}]),mt=De.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:gt,repeated:!0}]),gt=De.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}]),ft=De.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}]),vt=De.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),bt=De.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:yt,repeated:!0}]),yt=De.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}]),kt=De.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}]),St=De.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}]),Tt=De.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Ct=De.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:wt,oneof:"value"}]),wt=De.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}]),Et=De.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),xt=De.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:De.getEnumType(Rt)},{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}]),Rt=De.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Pt=De.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:De.getEnumType(It)},{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}]),It=De.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"}]),Ot=De.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:At},{no:2,name:"screen",kind:"message",T:At},{no:3,name:"resume_connection",kind:"enum",T:De.getEnumType(Ge)},{no:4,name:"disabled_codecs",kind:"message",T:_t},{no:5,name:"force_relay",kind:"enum",T:De.getEnumType(Ge)}]),At=De.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:De.getEnumType(Ge)}]),_t=De.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Ze,repeated:!0},{no:2,name:"publish",kind:"message",T:Ze,repeated:!0}]),Mt=De.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Dt=De.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Nt=De.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:De.getEnumType(Dt)},{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"}),Lt=De.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Ut=De.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:De.getEnumType(ot)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Nt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Lt,oneof:"content_header"}],{localName:"DataStream_Header"}),Ft=De.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"}),jt=De.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"}),Bt=De.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),$t=De.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Vt=De.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),qt=De.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Ht=De.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:ei,oneof:"message"},{no:2,name:"answer",kind:"message",T:ei,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Kt,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Gt,oneof:"message"},{no:5,name:"mute",kind:"message",T:Jt,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ii,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ni,oneof:"message"},{no:8,name:"leave",kind:"message",T:ri,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ci,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Ti,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ei,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Pi,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:di,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ii,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:si,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:oi,oneof:"message"}]),zt=De.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Yt,oneof:"message"},{no:2,name:"answer",kind:"message",T:ei,oneof:"message"},{no:3,name:"offer",kind:"message",T:ei,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Kt,oneof:"message"},{no:5,name:"update",kind:"message",T:ti,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Xt,oneof:"message"},{no:8,name:"leave",kind:"message",T:ri,oneof:"message"},{no:9,name:"mute",kind:"message",T:Jt,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ui,oneof:"message"},{no:11,name:"room_update",kind:"message",T:hi,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:mi,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:fi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:yi,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Ci,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Zt,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Qt,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Oi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Mi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Di,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Li,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:wi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:$i,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:ki,oneof:"message"}]),Wt=De.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:ct,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:De.getEnumType(dt)}]),Gt=De.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:De.getEnumType(qe)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:De.getEnumType(He)},{no:9,name:"layers",kind:"message",T:ct,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Wt,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:De.getEnumType(ot)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:De.getEnumType(Ve)},{no:17,name:"audio_features",kind:"enum",T:De.getEnumType(Qe),repeated:!0}]),Kt=De.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:De.getEnumType($t)},{no:3,name:"final",kind:"scalar",T:8}]),Jt=De.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Yt=De.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Xe},{no:2,name:"participant",kind:"message",T:tt},{no:3,name:"other_participants",kind:"message",T:tt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:li,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:Ot},{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:xt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Ze,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Qt=De.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:li,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Ot},{no:3,name:"server_info",kind:"message",T:xt},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Xt=De.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:at}]),Zt=De.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ei=De.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}}]),ti=De.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:tt,repeated:!0}]),ii=De.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:Et,repeated:!0}]),ni=De.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:De.getEnumType(ze)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),si=De.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:De.getEnumType(Qe),repeated:!0}]),oi=De.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),ri=De.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:De.getEnumType(Ke)},{no:3,name:"action",kind:"enum",T:De.getEnumType(ai)},{no:4,name:"regions",kind:"message",T:Ai}]),ai=De.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),ci=De.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:ct,repeated:!0}]),di=De.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}]),li=De.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}]),ui=De.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:gt,repeated:!0}]),hi=De.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Xe}]),pi=De.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:De.getEnumType(We)},{no:3,name:"score",kind:"scalar",T:2}]),mi=De.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:pi,repeated:!0}]),gi=De.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:De.getEnumType(Vt)}]),fi=De.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:gi,repeated:!0}]),vi=De.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:De.getEnumType(ze)},{no:2,name:"enabled",kind:"scalar",T:8}]),bi=De.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:vi,repeated:!0}]),yi=De.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:bi,repeated:!0}]),ki=De.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Bt,repeated:!0}]),Si=De.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}]),Ti=De.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Si,repeated:!0}]),Ci=De.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}]),wi=De.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Xe},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:tt},{no:4,name:"other_participants",kind:"message",T:tt,repeated:!0}]),Ei=De.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:ei},{no:2,name:"subscription",kind:"message",T:ii},{no:3,name:"publish_tracks",kind:"message",T:Xt,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ri,repeated:!0},{no:5,name:"offer",kind:"message",T:ei},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:xi,repeated:!0}]),xi=De.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Ri=De.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:De.getEnumType($t)}]),Pi=De.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:De.getEnumType(qt),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"}]),Ii=De.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Oi=De.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Ai=De.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:_i,repeated:!0}]),_i=De.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}]),Mi=De.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:De.getEnumType(Ye)}]),Di=De.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:De.getEnumType(Ni)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Kt,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Gt,oneof:"request"},{no:6,name:"mute",kind:"message",T:Jt,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:di,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:si,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:oi,oneof:"request"}]),Ni=De.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"}]),Li=De.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Ui=De.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}]),Fi=De.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Pt},{no:2,name:"connection_settings",kind:"message",T:Ui},{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:Gt,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:ei},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:De.getEnumType(Je)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ei}]),ji=De.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:De.getEnumType(Bi)},{no:2,name:"join_request",kind:"scalar",T:12}]),Bi=De.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),$i=De.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function Vi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qi,Hi={exports:{}};var zi,Wi,Gi,Ki,Ji,Yi=(qi||(qi=1,Wi=Hi.exports,Gi=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},o=null;function r(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var o=n[s];this[o]=s<i?e:this.methodFactory(o,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,o){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?r(console,n):void 0!==console.log?r(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var r,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:r},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(o!==u&&(r=m(o.getLevel())),c.call(u),o===u)for(var e in s)s[e].rebuild()},r=m(o?o.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(o=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,o.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=h),o},o.getLoggers=function(){return s},o.default=o,o},(zi=Hi).exports?zi.exports=Gi():Wi.log=Gi()),Hi.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(Ki||(Ki={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(Ji||(Ji={}));let Qi=Yi.getLogger("livekit");function Xi(e){const t=Yi.getLogger(e);return t.setDefaultLevel(Qi.getLevel()),t}Object.values(Ji).map(e=>Yi.getLogger(e)),Qi.setDefaultLevel(Ki.info);const Zi=Yi.getLogger("lk-e2ee"),en=7e3,tn=[0,300,1200,2700,4800,en,en,en,en,en];function nn(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(r,a)}c((n=n.apply(e,t||[])).next())})}function sn(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function on(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=sn(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,s){(function(e,t,i,n){Promise.resolve(n).then(function(t){e({value:t,done:i})},t)})(n,s,(t=e[i](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;var rn,an={exports:{}};var cn=function(){if(rn)return an.exports;rn=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}an.exports=s,an.exports.once=function(e,t){return new Promise(function(i,n){function s(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,s,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,o,c,d;if(r(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),c=o[t]),void 0===c)c=o[t]=i,++e._eventsCount;else if("function"==typeof c?c=o[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function s(o){n.once&&e.removeEventListener(t,s),i(o)})}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,o=this._events;if(void 0!==o)s=s&&void 0===o.error;else if(!s)return!1;if(s){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return r(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,o,a;if(r(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,o=i.length-1;o>=0;o--)if(i[o]===t||i[o].listener===t){a=i[o].listener,s=o;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,o=Object.keys(i);for(n=0;n<o.length;++n)"removeListener"!==(s=o[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},an.exports}();let dn=!0,ln=!0;function un(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function hn(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const o=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),s.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function pn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(dn=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function mn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ln=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function gn(){if("object"==typeof window){if(dn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function fn(e,t){ln&&console.warn(e+" is deprecated, please use "+t+" instead.")}function vn(e){return"[object Object]"===Object.prototype.toString.call(e)}function bn(e){return vn(e)?Object.keys(e).reduce(function(t,i){const n=vn(e[i]),s=n?bn(e[i]):e[i],o=n&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[i]:s})},{}):e}function yn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?yn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach(t=>{yn(e,e.get(t),i)})}))}function kn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const o=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)}),o.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&yn(e,i,s)})}),s}const Sn=gn;function Tn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const r=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||r)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{i=i.filter(e=>"videoinput"===e.kind);let r=i.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!r&&i.length&&t.includes("back")&&(r=i[i.length-1]),r&&(e.video.deviceId=o.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=n(e.video),Sn("chrome: "+JSON.stringify(e)),s(e)})}e.video=n(e.video)}return Sn("chrome: "+JSON.stringify(e)),s(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){s(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(o(e))})})}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(o(e))))}}}function Cn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function wn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else hn(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function En(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function xn(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>kn(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),hn(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>kn(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach(i=>{i.track===e&&(t?n=!0:t=i)}),this.getReceivers().forEach(t=>(t.track===e&&(i?n=!0:i=t),t.track===e)),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Rn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{const t=this.getSenders().find(t=>t.track===e);if(t)throw new DOMException("Track already exists.","InvalidAccessError")});const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),s.apply(this,arguments)}}function Pn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Rn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{const t=this.getSenders().find(t=>t.track===e);if(t)throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const s=this.getSenders().find(e=>e.track===t);if(s)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[i.id];if(o)o.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>o(this,e))}};e.RTCPeerConnection.prototype[t]=n[t]});const r=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)}),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),r.apply(this,arguments)):r.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function In(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]})}function On(e,t){hn(e,"negotiationneeded",e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var An=Object.freeze({__proto__:null,fixNegotiationNeeded:On,shimAddTrackRemoveTrack:Pn,shimAddTrackRemoveTrackWithNative:Rn,shimGetSendersWithDtmf:En,shimGetUserMedia:Tn,shimMediaStream:Cn,shimOnTrack:wn,shimPeerConnection:In,shimSenderReceiverGetStats:xn});function _n(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){fn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Mn(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Dn(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]});const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,o]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!s)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(s,o)}}function Nn(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ln(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),hn(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Un(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){fn("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Fn(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function jn(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function Bn(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function $n(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Vn(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var qn=Object.freeze({__proto__:null,shimAddTransceiver:jn,shimCreateAnswer:Vn,shimCreateOffer:$n,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Bn,shimGetUserMedia:_n,shimOnTrack:Mn,shimPeerConnection:Dn,shimRTCDataChannel:Fn,shimReceiverGetStats:Ln,shimRemoveStream:Un,shimSenderGetStats:Nn});function Hn(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function zn(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function Wn(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,o=t.setRemoteDescription,r=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Gn(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Kn(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Kn(e){return e&&void 0!==e.video?Object.assign({},e,{video:bn(e.video)}):e}function Jn(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(fn("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Yn(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Qn(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Xn(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Zn,es=Object.freeze({__proto__:null,shimAudioContext:Xn,shimCallbacksAPI:Wn,shimConstraints:Kn,shimCreateOfferLegacy:Qn,shimGetUserMedia:Gn,shimLocalStreamsAPI:Hn,shimRTCIceServerUrls:Jn,shimRemoteStreamsAPI:zn,shimTrackEventTransceiver:Yn}),ts={exports:{}};var is=(Zn||(Zn=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let s=3;s<n.length;s++){const o=n[s],r=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(r){const n=t.parseRtpMap(r),s=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(n.parameters=s.length?t.parseFmtp(s[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{i.headerExtensions.push(t.parseExtmap(e))});const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(e=>{s.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)});let s=0;return i.codecs.forEach(e=>{e.maxptime>s&&(s=e.maxptime)}),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),r=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=r.length>0&&r[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}}),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach(e=>{e.maxBitrate=l})),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const r=t.matchPrefix(e,"a=sctpmap:");if(r.length>0){const e=r[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const o=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(ts)),ts.exports),ns=Vi(is),ss=t({__proto__:null,default:ns},[is]);function os(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=ns.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,hn(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function rs(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||hn(e,"icecandidate",e=>{if(e.candidate){const t=ns.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function as(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=ns.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=ns.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=ns.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>s}),this._sctp=o}return i.apply(this,arguments)}}function cs(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},hn(e,"datachannel",e=>(t(e.channel,e.target),e))}function ds(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function ls(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function us(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function hs(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var ps=Object.freeze({__proto__:null,removeExtmapAllowMixed:ls,shimAddIceCandidateNullOrEmpty:us,shimConnectionState:ds,shimMaxMessageSize:as,shimParameterlessSetLocalDescription:hs,shimRTCIceCandidate:os,shimRTCIceCandidateRelayProtocol:rs,shimSendThrowTypeError:cs});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=gn,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=parseInt(un(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(un(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(un(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=un(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),s={browserDetails:n,commonShim:ps,extractVersion:un,disableLog:pn,disableWarnings:mn,sdp:ss};switch(n.browser){case"chrome":if(!An||!In||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=An,us(e,n),hs(e),Tn(e,n),Cn(e),In(e,n),wn(e),Pn(e,n),En(e),xn(e),On(e,n),os(e),rs(e),ds(e),as(e,n),cs(e),ls(e,n);break;case"firefox":if(!qn||!Dn||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=qn,us(e,n),hs(e),_n(e,n),Dn(e,n),Mn(e),Un(e),Nn(e),Ln(e),Fn(e),jn(e),Bn(e),$n(e),Vn(e),os(e),ds(e),as(e,n),cs(e);break;case"safari":if(!es||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=es,us(e,n),hs(e),Jn(e),Qn(e),Wn(e),Hn(e),zn(e),Yn(e),Gn(e),Xn(e),os(e),rs(e),as(e,n),cs(e),ls(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class ms extends Promise{constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}const gs=/version\/(\d+(\.?_?\d+)+)/i;let fs;function vs(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const i=navigator.userAgent.toLowerCase();if(void 0===fs||t){const e=bs.find(e=>{let{test:t}=e;return t.test(i)});fs=null==e?void 0:e.describe(i)}return fs}const bs=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:ys(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ks(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:ys(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ks(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:ys(gs,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:ks(e)})}];function ys(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function ks(e){return e.includes("mac os")?ys(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class Ss extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var Ts,Cs,ws,Es,xs,Rs,Ps;!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(Ts||(Ts={}));class Is extends Ss{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=Ts[t]}static notAllowed(e,t,i){return new Is(e,Ts.NotAllowed,t,i)}static timeout(e){return new Is(e,Ts.Timeout)}static leaveRequest(e,t){return new Is(e,Ts.LeaveRequest,void 0,t)}static internal(e,t){return new Is(e,Ts.InternalError,void 0,t)}static cancelled(e){return new Is(e,Ts.Cancelled)}static serverUnreachable(e,t){return new Is(e,Ts.ServerUnreachable,t)}static websocket(e,t,i){return new Is(e,Ts.WebSocket,t,i)}static serviceNotFound(e,t){return new Is(e,Ts.ServiceNotFound,void 0,t)}}class Os extends Ss{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class As extends Ss{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class _s extends Ss{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Ms extends Ss{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Ds extends Ss{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Ns extends Ss{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Ls extends Ss{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:Ni[t]}}!function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(Cs||(Cs={}));class Us extends Ss{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=Cs[t]}}class Fs extends Ss{constructor(e){super(18,e),this.name="SignalReconnectError"}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(ws||(ws={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(ws||(ws={}));class js{}js.setTimeout=function(){return setTimeout(...arguments)},js.setInterval=function(){return setInterval(...arguments)},js.clearTimeout=function(){return clearTimeout(...arguments)},js.clearInterval=function(){return clearInterval(...arguments)},function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"}(Es||(Es={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(xs||(xs={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"}(Rs||(Rs={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(Ps||(Ps={}));class Bs{constructor(e,t,i,n,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const $s=["vp8","h264"],Vs=["vp8","h264","vp9","av1","h265"];const qs=function(e){return!!$s.find(t=>t===e)};var Hs,zs;!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(Hs||(Hs={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(zs||(zs={}));const Ws={h90:new Bs(160,90,9e4,20),h180:new Bs(320,180,16e4,20),h216:new Bs(384,216,18e4,20),h360:new Bs(640,360,45e4,20),h540:new Bs(960,540,8e5,25),h720:new Bs(1280,720,17e5,30),h1080:new Bs(1920,1080,3e6,30),h1440:new Bs(2560,1440,5e6,30),h2160:new Bs(3840,2160,8e6,30)},Gs={h120:new Bs(160,120,7e4,20),h180:new Bs(240,180,125e3,20),h240:new Bs(320,240,14e4,20),h360:new Bs(480,360,33e4,20),h480:new Bs(640,480,5e5,20),h540:new Bs(720,540,6e5,25),h720:new Bs(960,720,13e5,30),h1080:new Bs(1440,1080,23e5,30),h1440:new Bs(1920,1440,38e5,30)},Ks={h360fps3:new Bs(640,360,2e5,3,"medium"),h360fps15:new Bs(640,360,4e5,15,"medium"),h720fps5:new Bs(1280,720,8e5,5,"medium"),h720fps15:new Bs(1280,720,15e5,15,"medium"),h720fps30:new Bs(1280,720,2e6,30,"medium"),h1080fps15:new Bs(1920,1080,25e5,15,"medium"),h1080fps30:new Bs(1920,1080,5e6,30,"medium"),original:new Bs(0,0,7e6,30,"medium")};function Js(e,t,i){var n,s,o,r;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=oo(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(Ys(h.audio,t),null!==(n=(o=h.audio).deviceId)&&void 0!==n||(o.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(Ys(h.video,i),null!==(s=(r=h.video).deviceId)&&void 0!==s||(r.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function Ys(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function Qs(e){var t,i,n,s;const o={};if(e.video)if("object"==typeof e.video){const i={},s=i,r=e.video;Object.keys(r).forEach(e=>{if("resolution"===e)Ys(s,r.resolution);else s[e]=r[e]}),o.video=i,null!==(t=(n=o.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else o.video=!!e.video&&{deviceId:{ideal:"default"}};else o.video=!1;return e.audio?"object"==typeof e.audio?(o.audio=e.audio,null!==(i=(s=o.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):o.audio={deviceId:{ideal:"default"}}:o.audio=!1,o}function Xs(e){return nn(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Zs();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield mo(t),n.getByteTimeDomainData(o);const r=o.some(e=>128!==e&&0!==e);return i.close(),!r}return!1}()})}function Zs(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>nn(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}});i.addEventListener("statechange",()=>{var t;"closed"===i.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return i}}function eo(e){return"audioinput"===e?lo.Source.Microphone:"videoinput"===e?lo.Source.Camera:lo.Source.Unknown}function to(e){return e===lo.Source.Microphone?"audioinput":e===lo.Source.Camera?"videoinput":void 0}function io(e){return e.split("/")[1].toLowerCase()}function no(e){const t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new Xt({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function so(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?so(e.track):{})}}function oo(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function ro(e,t){return e.width*e.height<t.width*t.height}const ao=[];var co;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(co||(co={}));class lo extends cn.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=lo.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=Xi(null!==(n=i.loggerName)&&void 0!==n?n:Ji.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=lo.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),so(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===lo.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===lo.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(ao.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&ao.splice(ao.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),uo(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?Ps.AudioPlaybackStarted:Ps.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?Ps.AudioPlaybackFailed:Ps.VideoPlaybackFailed,t):"AbortError"===t.name?Qi.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Qi.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(Ps.ElementAttached,e),e}detach(e){try{if(e){ho(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Ps.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(e=>{ho(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Ps.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Xi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ao.forEach(e=>{e.parentElement||(t=!1)}),t&&ao.push(e)}}handleAppVisibilityChanged(){return nn(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==lo.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){wo()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){wo()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function uo(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),So()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(So()||yo())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function ho(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t,i,n;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(n=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return qe.AUDIO;case t.Video:return qe.VIDEO;default:return qe.DATA}},e.kindFromProto=function(e){switch(e){case qe.AUDIO:return t.Audio;case qe.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return He.CAMERA;case i.Microphone:return He.MICROPHONE;case i.ScreenShare:return He.SCREEN_SHARE;case i.ScreenShareAudio:return He.SCREEN_SHARE_AUDIO;default:return He.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case He.CAMERA:return i.Camera;case He.MICROPHONE:return i.Microphone;case He.SCREEN_SHARE:return i.ScreenShare;case He.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Vt.ACTIVE:return n.Active;case Vt.PAUSED:return n.Paused;default:return n.Unknown}}}(lo||(lo={}));const po="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function mo(e){return new ms(t=>js.setTimeout(t,e))}function go(){return"addTransceiver"in RTCPeerConnection.prototype}function fo(){return"addTrack"in RTCPeerConnection.prototype}function vo(e){return"av1"===e||"vp9"===e}function bo(e){return!(!document||To())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function yo(){var e;return"Firefox"===(null===(e=vs())||void 0===e?void 0:e.name)}function ko(){const e=vs();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function So(){var e;return"Safari"===(null===(e=vs())||void 0===e?void 0:e.name)}function To(){const e=vs();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function Co(){var e,t;return!!wo()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function wo(){return"undefined"!=typeof document}function Eo(){return"ReactNative"==navigator.product}function xo(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Ro(e){return xo(e)?e.hostname.split(".")[0]:null}function Po(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Io(){if(!Eo())return;let e=Po();return e?e.platform:void 0}function Oo(){if(wo())return window.devicePixelRatio;if(Eo()){let e=Po();if(e)return e.devicePixelRatio}return 1}function Ao(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let e=0;e<s;++e){const t=parseInt(i[e],10),o=parseInt(n[e],10);if(t>o)return 1;if(t<o)return-1;if(e===s-1&&t===o)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function _o(e){for(const t of e)t.target.handleResize(t)}function Mo(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Do=null;const No=()=>(Do||(Do=new ResizeObserver(_o)),Do);let Lo=null;const Uo=()=>(Lo||(Lo=new IntersectionObserver(Mo,{root:null,rootMargin:"0px"})),Lo);function Fo(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const o=s.getContext("2d");null==o||o.fillRect(0,0,s.width,s.height),n&&o&&(o.beginPath(),o.arc(e/2,t/2,50,0,2*Math.PI,!0),o.closePath(),o.fillStyle="grey",o.fill());const r=s.captureStream(),[a]=r.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let jo;function Bo(){if(!jo){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[jo]=n.stream.getAudioTracks(),!jo)throw Error("Could not get empty media stream audio track");jo.enabled=!1}return jo.clone()}class $o{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>nn(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)})}}function Vo(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function qo(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Ho(e){switch(e.reason){case Ts.LeaveRequest:return e.context;case Ts.Cancelled:return Ke.CLIENT_INITIATED;case Ts.NotAllowed:return Ke.USER_REJECTED;case Ts.ServerUnreachable:return Ke.JOIN_FAILURE;default:return Ke.UNKNOWN_REASON}}function zo(e){return void 0!==e?Number(e):void 0}function Wo(e){return void 0!==e?BigInt(e):void 0}function Go(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Ko(e){return!!e&&e.kind==lo.Kind.Audio}function Jo(e){return!!e&&e.kind==lo.Kind.Video}function Yo(e){return Go(e)&&Jo(e)}function Qo(e){return Go(e)&&Ko(e)}function Xo(e){return!!e&&!e.isLocal}function Zo(e){return!!e&&!e.isLocal}function er(e){return Xo(e)&&Jo(e)}function tr(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach((e,t)=>{i.searchParams.set(t,e)}),nr(i,"rtc")}(e,t);return i?n:nr(n,"v1")}function ir(e){return e.endsWith("/")?e:"".concat(e,"/")}function nr(e,t){return e.pathname="".concat(ir(e.pathname)).concat(t),e}function sr(e){if("string"==typeof e)return zt.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return zt.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const or="lk_e2ee";var rr,ar,cr,dr,lr;function ur(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||hr()}function hr(){return void 0!==window.RTCRtpScriptTransform}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(rr||(rr={})),function(e){e.KeyRatcheted="keyRatcheted"}(ar||(ar={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(cr||(cr={})),function(e){e.Error="cryptorError"}(dr||(dr={}));cn.EventEmitter;!function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(lr||(lr={}));class pr extends cn.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":if(Qi.error(s.error.message),s.uuid){const e=this.decryptDataRequests.get(s.uuid);if(null==e?void 0:e.reject){e.reject(s.error);break}const t=this.encryptDataRequests.get(s.uuid);if(null==t?void 0:t.reject){t.reject(s.error);break}}this.emit(cr.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(cr.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(cr.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(rr.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const e=this.decryptDataRequests.get(s.uuid);(null==e?void 0:e.resolve)&&e.resolve(s);break;case"encryptDataResponse":const n=this.encryptDataRequests.get(s.uuid);(null==n?void 0:n.resolve)&&n.resolve(s)}},this.onWorkerError=e=>{Qi.error("e2ee worker encountered an error:",{error:e.error}),this.emit(cr.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!ur())throw new Os("tried to setup end-to-end encryption on an unsupported browser");if(Qi.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Zi.getLevel()}};this.worker&&(Qi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Qi.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Qi.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(Rs.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(Es.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ot.NONE,t.identity)),e.on(Es.ConnectionStateChanged,t=>{t===Xa.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==ot.NONE,e.identity)})})}).on(Es.TrackUnsubscribed,(e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)}).on(Es.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(Es.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(xs.LocalSenderCreated,(e,t)=>nn(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(xs.LocalTrackPublished,e=>{if(!Jo(e.track)||!To())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:io(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(rr.SetKey,e=>this.postKey(e)).on(rr.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return nn(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new $o;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise})}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:i,keyIndex:n}},r=new $o;return r.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,r),this.worker.postMessage(o),r.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(o)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?io(i.mimeType):void 0)}}setupE2EESender(e,t){Go(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Qi.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return nn(this,void 0,void 0,function*(){if(this.worker){if(hr()&&!ko()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(or in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,o=e.readableStream;if(!s||!o){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,o=t.readable}const r={kind:"decode",data:{readableStream:o,writableStream:s,trackId:t,codec:n,participantIdentity:i,isReuse:or in e}};this.worker.postMessage(r,[o,s])}e[or]=!0}})}handleSender(e,t,i){var n;if(!(or in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(hr()&&!ko()){Qi.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{Qi.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(s,[n.readable,n.writable])}e[or]=!0}}}class mr{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new mr),this._instance}addFailedConnectionAttempt(e){var t;const i=Ro(new URL(e));if(!i)return;let n=null!==(t=this.failedConnectionAttempts.get(i))&&void 0!==t?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,mo(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){const t=new URL(e),i=t&&Ro(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Ro(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}mr._instance=null;const gr="default";class fr{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new fr),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return nn(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=fr.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Qi.debug("awaiting getUserMedia promise");try{e?yield fr.userMediaPromiseMap.get(e):yield Promise.all(fr.userMediaPromiseMap.values())}catch(e){Qi.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!So()||!t.hasDeviceInUse(e))){const t=0===s.filter(t=>t.kind===e).length||s.some(t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n});if(t){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach(e=>{e.stop()})}}return t._previousDevices=s,e&&(s=s.filter(t=>t.kind===e)),s}()})}normalizeDeviceId(e,t,i){return nn(this,void 0,void 0,function*(){if(t!==gr)return t;const n=yield this.getDevices(e),s=n.find(e=>e.deviceId===gr);if(!s)return void Qi.warn("could not reliably determine default device");const o=n.find(e=>e.deviceId!==gr&&e.groupId===(null!=i?i:s.groupId));if(o)return null==o?void 0:o.deviceId;Qi.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?fr.userMediaPromiseMap.has(e):fr.userMediaPromiseMap.size>0}}var vr;fr.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],fr.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(vr||(vr={}));class br{constructor(){this.pendingTasks=new Map,this.taskMutex=new s,this.nextTaskIndex=0}run(e){return nn(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:vr.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=vr.RUNNING,yield e()}finally{t.status=vr.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return nn(this,void 0,void 0,function*(){return this.run(()=>nn(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class yr{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;if(null===(i=t.signal)||void 0===i?void 0:i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const s=new WebSocket(e,null!==(n=t.protocols)&&void 0!==n?n:[]);s.binaryType="arraybuffer",this.ws=s;const o=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return s.close(e,t)};this.opened=new ms((e,t)=>{const i=()=>{t(Is.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{e({readable:new ReadableStream({start(e){s.onmessage=t=>{let{data:i}=t;return e.enqueue(i)},s.onerror=t=>e.error(t)},cancel:o}),writable:new WritableStream({write(e){s.send(e)},abort(){s.close()},close:o}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",i)},s.addEventListener("error",i)}),this.closed=new ms((e,t)=>{const i=()=>nn(this,void 0,void 0,function*(){const i=new ms(e=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",t=>{e(t)},{once:!0})}),n=yield ms.race([mo(250),i]);n?e(n):t(Is.websocket("Encountered unspecified websocket error without a timely close event"))});s.onclose=t=>{let{code:n,reason:o}=t;e({closeCode:n,reason:o}),s.removeEventListener("error",i)},s.addEventListener("error",i)}),t.signal&&(t.signal.onabort=()=>s.close()),this.close=o}}const kr=["syncState","trickle","offer","answer","simulate","leave"];var Sr;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(Sr||(Sr={}));class Tr{get currentState(){return this.state}get isDisconnected(){return this.state===Sr.DISCONNECTING||this.state===Sr.DISCONNECTED}get isEstablishingConnection(){return this.state===Sr.CONNECTING||this.state===Sr.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Sr.DISCONNECTED,this.log=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=Xi(null!==(i=t.loggerName)&&void 0!==i?i:Ji.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new br,this.queuedRequests=[],this.closingLock=new s,this.connectionLock=new s,this.state=Sr.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return nn(this,arguments,void 0,function(e,t,i,n){var s=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){s.state=Sr.CONNECTING,s.options=i;return yield s.connect(e,t,i,n,o)}()})}reconnect(e,t,i,n){return nn(this,void 0,void 0,function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=Sr.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath)})}connect(e,t,i,n){return nn(this,arguments,void 0,function(e,t,i,n){var s=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){const r=yield s.connectionLock.lock();s.connectOptions=i,s.useV0SignalPath=o;const a=function(){var e;const t=new Pt({sdk:It.JS,protocol:16,version:"2.17.0"});return Eo()&&(t.os=null!==(e=Io())&&void 0!==e?e:""),t}(),c=o?function(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",Eo()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return s}(t,a,i):function(e,t,i){const n=new URLSearchParams;n.set("access_token",e);const s=new Fi({clientInfo:t,connectionSettings:new Ui({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0});i.reconnectReason&&(s.reconnectReason=i.reconnectReason);const o=new ji({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(o.toBinary()))),n}(t,a,i),d=tr(e,c,o).toString(),l=(u=d,nr(new URL(qo(u)),"validate")).toString();var u;return new Promise((e,t)=>nn(s,void 0,void 0,function*(){var s,o;try{let r=!1;const a=e=>nn(this,void 0,void 0,function*(){if(r)return;r=!0;const i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;const i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(i)).catch(e=>{this.log.error(e),this.close()}):this.close(),c(),t(Is.cancelled(i))});null==n||n.addEventListener("abort",a);const c=()=>{clearTimeout(u),null==n||n.removeEventListener("abort",a)},u=setTimeout(()=>{a(Is.timeout("room connection has timed out (signal)"))},i.websocketTimeout),h=(e,t)=>{this.handleSignalConnected(e,u,t)},p=new URL(d);p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(p),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new yr(d);try{this.ws.closed.then(e=>{var i;this.isEstablishingConnection&&t(Is.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state})),this.state===Sr.CONNECTED&&this.handleOnClose(null!==(i=e.reason)&&void 0!==i?i:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(Is.internal("Websocket error during a (re)connection attempt: ".concat(e)))});const n=yield this.ws.opened.catch(e=>nn(this,void 0,void 0,function*(){if(this.state!==Sr.CONNECTED){this.state=Sr.DISCONNECTED,clearTimeout(u);const i=yield this.handleConnectionError(e,l);return void t(i)}this.handleWSError(e),t(e)}));if(clearTimeout(u),!n)return;const r=n.readable.getReader();this.streamWriter=n.writable.getWriter();const a=yield r.read();if(r.releaseLock(),!a.value)throw Is.internal("no message received as first message");const c=sr(a.value),d=this.validateFirstMessage(c,null!==(s=i.reconnect)&&void 0!==s&&s);if(!d.isValid)return void t(d.error);"join"===(null===(o=c.message)||void 0===o?void 0:o.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})));h(n,d.shouldProcessFirstMessage?c:void 0),e(d.response)}catch(e){t(e)}finally{c()}}finally{r()}}))}()})}startReadingLoop(e,t){return nn(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield mo(this.signalLatency));const{done:t,value:i}=yield e.read();if(t)break;const n=sr(i);this.handleSignalResponse(n)}})}close(){return nn(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([Sr.DISCONNECTING||Sr.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Sr.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,mo(250)])}}catch(t){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=Sr.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:wr(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:wr(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Kt({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Jt({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return nn(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new di({requestId:s,metadata:e,name:t,attributes:n})}),s}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new ci({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Ti({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:x.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ii({timestamp:x.parse(Date.now()),rtt:x.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new si({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ri({reason:Ke.CLIENT_INITIATED,action:ai.DISCONNECT})})}sendRequest(e){return nn(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=kr.indexOf(e.case)>=0;return Qi.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Sr.RECONNECTING)return void t.queuedRequests.push(()=>nn(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield mo(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new Ht({message:e});try{t.useJSON?yield t.streamWriter.write(s.toJsonString()):yield t.streamWriter.write(s.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=Cr(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const e=Cr(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),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 e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return nn(this,void 0,void 0,function*(){if(this.state===Sr.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=js.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&&js.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=js.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&&js.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=Sr.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,s,o,r;return"join"===(null===(i=e.message)||void 0===i?void 0:i.case)?{isValid:!0,response:e.message.value}:this.state===Sr.RECONNECTING&&"leave"!==(null===(n=e.message)||void 0===n?void 0:n.case)?"reconnect"===(null===(s=e.message)||void 0===s?void 0:s.case)?{isValid:!0,response:e.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===(o=e.message)||void 0===o?void 0:o.case)?{isValid:!1,error:Is.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:Is.internal("Unexpected first message")}:{isValid:!1,error:Is.internal("did not receive join response, got ".concat(null===(r=e.message)||void 0===r?void 0:r.case," instead"))}}handleConnectionError(e,t){return nn(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return Is.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const e=yield i.text();return Is.notAllowed(e,i.status)}return e instanceof Is?e:Is.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(e){return e instanceof Is?e:Is.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}})}}function Cr(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function wr(e,t){return new ei({sdp:e.sdp,type:e.type,id:t})}class Er{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class xr{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[n,s]of i.entries())t.push(e(s,n,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var Rr,Pr,Ir,Or,Ar,_r={},Mr={},Dr={exports:{}};function Nr(){if(Rr)return Dr.exports;Rr=1;var e=Dr.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),Dr.exports}function Lr(){return Pr||(Pr=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(i[n[o]]=t(e[o+1]))}(n.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},n=Nr(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],r=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach(function(e){var t=e[0],s=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),r=o[o.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,r,s)}}),t.media=o,t};var o=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}})})}}(Mr)),Mr}function Ur(){if(Or)return Ir;Or=1;var e=Nr(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var r=t.names[o];t.name?s.push(n[t.name][r]):s.push(n[t.names[o]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return Ir=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var r=i.outerOrder||s,a=i.innerOrder||o,c=[];return r.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})}),t.media.forEach(function(t){c.push(n("m",e.m[0],t)),a.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})})}),c.join("\r\n")+"\r\n"},Ir}var Fr=function(){if(Ar)return _r;Ar=1;var e=Lr(),t=Ur(),i=Nr();return _r.grammar=i,_r.write=t,_r.parse=e.parse,_r.parseParams=e.parseParams,_r.parseFmtpConfig=e.parseFmtpConfig,_r.parsePayloads=e.parsePayloads,_r.parseRemoteCandidates=e.parseRemoteCandidates,_r.parseImageAttributes=e.parseImageAttributes,_r.parseSimulcastStreamList=e.parseSimulcastStreamList,_r}();function jr(e,t,i){var n,s,o;void 0===t&&(t=50),void 0===i&&(i={});var r=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[];function u(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),i=this;return new Promise(function(n,s){var c=r&&void 0===o;if(void 0!==o&&clearTimeout(o),o=setTimeout(function(){if(o=void 0,d=Date.now(),!r){var n=e.apply(i,t);a&&a(n),l.forEach(function(e){return(0,e.resolve)(n)}),l=[]}},u()),c){var h=e.apply(i,t);return a&&a(h),n(h)}l.push({resolve:n,reject:s})})};return h.cancel=function(e){void 0!==o&&clearTimeout(o),l.forEach(function(t){return(0,t.reject)(e)}),l=[]},h}const Br="negotiationStarted",$r="negotiationComplete",Vr="rtpVideoPayloadTypes";class qr extends cn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Qi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=jr(e=>nn(this,void 0,void 0,function*(){this.emit(Br);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Xi(null!==(i=t.loggerName)&&void 0!==i?i:Ji.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new s}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return nn(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return nn(this,void 0,void 0,function*(){var i;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Fr.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let o=0;return s.media.forEach(e=>{var t;const s=Wr(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(o=e.payload,!0)),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some(e=>e.payload===o&&"nack"===e.type))&&n.push(s),e.fmtp.some(e=>e.payload===o&&(e.config.includes("sprop-stereo=1")&&i.push(s),!0)))}),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const t=Fr.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach(e=>{const t=Wr(e.mid);"audio"===e.type&&this.trackBitrates.some(i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;let s=!1;for(const t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),s=!0;break}return s||i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0})}),n=Fr.write(t)}if(yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit($r),e.sdp)){Fr.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(Vr,e.rtp)})}return!0})}createAndSendOffer(e){return nn(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=this.latestOfferId+1;this.latestOfferId=i;const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=Fr.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(s.media.forEach(e=>{zr(e),"audio"===e.type?Hr(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i)return!0;if(vo(t.codec)&&!So()&&this.ensureVideoDDExtensionForSVC(e,s),!vo(t.codec))return!0;const n=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,Fr.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return nn(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Fr.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach(e=>{zr(e),"audio"===e.type&&Hr(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Fr.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Ms("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Ms("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return nn(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0})}setMungedSDP(e,t,i){return nn(this,void 0,void 0,function*(){if(t){const n=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let n="unknown error";t instanceof Error?n=t.message:"string"==typeof t&&(n=t);const s={error:n,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Ds(n)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some(e=>e.uri===po))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:po})}}}function Hr(e,t,i){const n=Wr(e.mid);let s=0;e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),s>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some(e=>e.payload===s&&"nack"===e.type)&&e.rtcpFb.push({payload:s,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some(e=>e.payload===s&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function zr(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function Wr(e){return"number"==typeof e?e.toFixed(0):e}const Gr="vp8",Kr={audioPreset:zs.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ks.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Gr,backupCodec:!0,preConnectBuffer:!1},Jr={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Yr={deviceId:{ideal:"default"},resolution:Ws.h720.resolution},Qr={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:tn}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Xr={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Zr;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(Zr||(Zr={}));class ea{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var n;this.peerConnectionTimeout=Xr.peerConnectionTimeout,this.log=Qi,this.updateState=()=>{var e,t;const i=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>"connected"===e)?this.state=Zr.CONNECTED:n.some(e=>"failed"===e)?this.state=Zr.FAILED:n.some(e=>"connecting"===e)?this.state=Zr.CONNECTING:n.every(e=>"closed"===e)?this.state=Zr.CLOSED:n.some(e=>"closed"===e)?this.state=Zr.CLOSING:n.every(e=>"new"===e)&&(this.state=Zr.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(Zr[i]," to ").concat(Zr[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.log=Xi(null!==(n=i.loggerName)&&void 0!==n?n:Ji.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new qr(e,i),this._mode=t,"publisher-only"!==t&&(this.subscriber=new qr(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,$t.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,$t.PUBLISHER)},this.publisher.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=Zr.NEW,this.connectionLock=new s,this.remoteOfferLock=new s}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return nn(this,void 0,void 0,function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return nn(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return nn(this,void 0,void 0,function*(){var i;t===$t.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return nn(this,void 0,void 0,function*(){var i,n,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(i=this.subscriber)||void 0===i?void 0:i.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{if(!(yield null===(n=this.subscriber)||void 0===n?void 0:n.setRemoteDescription(e,t)))return;return yield null===(s=this.subscriber)||void 0===s?void 0:s.createAndSetAnswer()}finally{o()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null===(i=this.subscriber)||void 0===i||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return nn(this,void 0,void 0,function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map(i=>this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return nn(this,void 0,void 0,function*(){return new ms((t,i)=>nn(this,void 0,void 0,function*(){const n=setTimeout(()=>{i(new Ds("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(n),i(new Ds("negotiation aborted"))}),this.publisher.once(Br,()=>{e.signal.aborted||this.publisher.once($r,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(n),e instanceof Error?i(e):i(new Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e);return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===$t.PUBLISHER||e===$t.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return nn(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,s)=>nn(i,void 0,void 0,function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),js.clearTimeout(o),s(Is.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const o=js.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),s(Is.internal("could not establish pc connection"))},n);for(;this.state!==Zr.CONNECTED;)if(yield mo(50),null==t?void 0:t.signal.aborted)return void s(Is.cancelled("room connection has been cancelled"));js.clearTimeout(o),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class ta{static fetchRegionSettings(e,t,i){return nn(this,void 0,void 0,function*(){const n=yield ta.fetchLock.lock();try{const n=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){const e=function(e){var t;const i=e.get("Cache-Control");if(i){const e=null===(t=i.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers),t=e?1e3*e:5e3;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===n.status?Is.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):Is.internal("Could not fetch region settings: ".concat(n.statusText))}catch(e){throw e instanceof Is?e:(null==i?void 0:i.aborted)?Is.cancelled("Region fetching was aborted"):Is.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{n()}})}static scheduleRefetch(e,t,i){return nn(this,void 0,void 0,function*(){const n=ta.settingsTimeouts.get(e.hostname);clearTimeout(n),ta.settingsTimeouts.set(e.hostname,setTimeout(()=>nn(this,void 0,void 0,function*(){try{const i=yield ta.fetchRegionSettings(e,t);ta.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof Is&&n.reason===Ts.NotAllowed)return void Qi.debug("token is not valid, cancelling auto region refresh");Qi.debug("auto refetching of region settings failed",{error:n}),ta.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){ta.cache.set(e.hostname,i),ta.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=ta.settingsTimeouts.get(e);t&&(clearTimeout(t),ta.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=ta.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const t=ta.connectionTrackers.get(e);t&&0===t.connectionCount&&(Qi.debug("stopping region refetch after disconnect delay",{hostname:e}),ta.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){const t=ta.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=ta.connectionTrackers.get(e);t||(t={connectionCount:0},ta.connectionTrackers.set(e,t)),t.connectionCount++,ta.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=ta.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&ta.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return xo(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return nn(this,void 0,void 0,function*(){return ta.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return nn(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=ta.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),ta.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(i.length>0){const e=i[0];return this.attemptedRegions.push(e),Qi.debug("next region: ".concat(e.region)),e.url}return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){ta.updateCachedRegionSettings(this.serverUrl,this.token,e)}}ta.cache=new Map,ta.settingsTimeouts=new Map,ta.connectionTrackers=new Map,ta.fetchLock=new s;class ia extends Error{constructor(e,t,i){super(t),this.code=e,this.message=sa(t,ia.MAX_MESSAGE_BYTES),this.data=i?sa(i,ia.MAX_DATA_BYTES):void 0}static fromProto(e){return new ia(e.code,e.message,e.data)}toProto(){return new wt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ia(ia.ErrorCode[e],ia.ErrorMessage[e],t)}}ia.MAX_MESSAGE_BYTES=256,ia.MAX_DATA_BYTES=15360,ia.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},ia.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};function na(e){return(new TextEncoder).encode(e).length}function sa(e,t){if(na(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const o=Math.floor((i+n+1)/2);s.encode(e.slice(0,o)).length<=t?i=o:n=o-1}return e.slice(0,i)}const oa=2e3;function ra(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}const aa="undefined"!=typeof MediaRecorder;const ca=aa?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class da extends ca{constructor(e,t){if(!aa)throw new Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([e.mediaStreamTrack]),t);const s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),null==n||n.close(),n=void 0},o=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>nn(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();i=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");i=t.data.byteArray}void 0!==n&&e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",o)}}class la extends lo{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=jr(()=>nn(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>nn(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(Ps.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new s,this.pauseUpstreamLock=new s,this.trackChangeLock=new s,this.trackChangeLock.lock().then(t=>nn(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==lo.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return nn(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{ho(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(uo(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,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:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{uo(null!=n?n:e,t)}))})}waitForDimensions(){return nn(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===lo.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=vs())||void 0===i?void 0:i.os)&&(yield mo(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield mo(50)}throw new As("unable to get track dimensions after timeout")}()})}setDeviceId(e){return nn(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Vo(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Vo(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return nn(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===lo.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===lo.Kind.Audio?"audioinput":"videoinput";return t?fr.getInstance().normalizeDeviceId(s,i,n):i}()})}mute(){return nn(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return nn(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return nn(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 t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return nn(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===lo.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||Object.assign({deviceId:t},n),this.attachedElements.forEach(e=>{ho(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===lo.Kind.Video&&(yield o.applyConstraints(n)),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o),this._constraints=e,this.emit(Ps.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Ps.Muted:Ps.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return nn(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Co()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return nn(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(Ps.UpstreamPaused,this);const t=vs();if("Safari"===(null==t?void 0:t.name)&&Ao(t.version,"12.0")<0)throw new Os("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return nn(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(Ps.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return nn(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()})}setProcessor(e){return nn(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),o={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(o),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(uo(t._mediaStreamTrack,s),s.muted=!0,s.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{s.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(ho(t._mediaStreamTrack,e),uo(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(Ps.TrackProcessorUpdate,t.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return nn(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}}()})}internalStopProcessor(){return nn(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Ps.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(aa)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new da(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}else this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class ua extends la{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,lo.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>nn(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=ra(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Ps.AudioTrackFeatureUpdate,this,Qe.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Ps.AudioTrackFeatureUpdate,this,Qe.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return nn(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===lo.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return nn(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Vo(this._constraints.deviceId);return this.source!==lo.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return nn(this,void 0,void 0,function*(){let t;if(e){const i=Qs({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return nn(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){wo()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},oa)))}setProcessor(e){return nn(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Eo()&&!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(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(Ps.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return nn(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return nn(this,void 0,void 0,function*(){const e=yield Xs(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(Ps.AudioSilenceDetected)),e})}}const ha=Object.values(Ws),pa=Object.values(Gs),ma=Object.values(Ks),ga=[Ws.h180,Ws.h360],fa=[Gs.h180,Gs.h360],va=["q","h","f"];function ba(e,t,i,n){var s,o;let r=null==n?void 0:n.videoEncoding;e&&(r=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!r&&!a&&!c||!t||!i)return[{}];r||(r=function(e,t,i,n){const s=function(e,t,i){if(e)return ma;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return ha;return pa}(e,t,i);let{encoding:o}=s[0];const r=Math.max(t,i);for(let e=0;e<s.length;e+=1){const t=s[e];if(o=t.encoding,t.width>=r)break}if(n)switch(n){case"av1":case"h265":o=Object.assign({},o),o.maxBitrate=.7*o.maxBitrate;break;case"vp9":o=Object.assign({},o),o.maxBitrate=.85*o.maxBitrate}return o}(e,t,i,d),Qi.debug("using video encoding",r));const l=r.maxFramerate,u=new Bs(t,i,r.maxBitrate,r.maxFramerate,r.priority);if(c&&vo(d)){const e=new Ta(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=vs();if(To()||Eo()||"Chrome"===(null==i?void 0:i.name)&&Ao(null==i?void 0:i.version,"113")<0){const n="h"==e.suffix?2:3,s=function(e){return e||(e=vs()),"Safari"===(null==e?void 0:e.name)&&Ao(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&Ao(e.osVersion,"18.3")>0}(i);for(let i=0;i<e.spatial;i+=1)t.push({rid:va[2-i],maxBitrate:r.maxBitrate/Math.pow(n,i),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,i):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:r.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),Qi.debug("using svc encoding",{encodings:t}),t}if(!a)return[r];let h,p=[];if(p=e?null!==(s=Sa(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:ya(e,u):null!==(o=Sa(null==n?void 0:n.videoSimulcastLayers))&&void 0!==o?o:ya(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return ka(t,i,[e,h,u],l);if(n>=480)return ka(t,i,[e,u],l)}return ka(t,i,[u])}function ya(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map(e=>{var t,n;return new Bs(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)});var i;const{width:n,height:s}=t,o=n>s?n/s:s/n;return Math.abs(o-16/9)<Math.abs(o-4/3)?ga:fa}function ka(e,t,i,n){const s=[];if(i.forEach((i,o)=>{if(o>=va.length)return;const r=Math.min(e,t),a={rid:va[o],scaleResolutionDownBy:Math.max(1,r/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=yo()||0===o;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)}),Eo()&&"ios"===Io()){let e;s.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;s.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,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(e)),i.maxFramerate=e)})}return s}function Sa(e){if(e)return e.sort((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class Ta{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Ca extends la{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,lo.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>nn(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(Ps.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=ra(t,s)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new s}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!wo())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},oa))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return nn(this,void 0,void 0,function*(){var t,i,n,s,o;yield e.pauseUpstream.call(this);try{for(var r,a=!0,c=on(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(null)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return nn(this,void 0,void 0,function*(){var t,i,n,s,o;yield e.resumeUpstream.call(this);try{for(var r,a=!0,c=on(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(e.mediaStreamTrack)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return nn(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==lo.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return nn(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==lo.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return nn(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},o=i.get(e.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)}),t})}setPublishingQuality(e){const t=[];for(let i=co.LOW;i<=co.HIGH;i+=1)t.push(new vi({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(vo(this.codec),t)}restartTrack(e){return nn(this,void 0,void 0,function*(){var t,i,n,s,o;let r;if(e){const t=Qs({video:e});"boolean"!=typeof t.video&&(r=t.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var a,c=!0,d=on(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(o=e.sender.transport)||void 0===o?void 0:o.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){i={error:e}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return nn(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,o,r,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=on(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(e){o={error:e}}finally{try{u||s||!(r=h.return)||(yield r.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return nn(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return nn(this,void 0,void 0,function*(){var t,i,n,s,o,r,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(vo(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=on(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield wa(t.sender,t.encodings,e.qualities,this.senderLock,vo(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(vo(e.codec),e.qualities)}}catch(e){o={error:e}}finally{try{t||s||!(r=i.return)||(yield r.call(i))}finally{if(o)throw o.error}}return c})}setPublishingLayers(e,t){return nn(this,void 0,void 0,function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield wa(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return nn(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&vo(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return nn(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Co()&&this.isInBackground&&this.source===lo.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function wa(e,t,i,n,s,o,r){return nn(this,void 0,void 0,function*(){const a=yield n.lock();o.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void o.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(s){i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0)}a.forEach((e,n)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=Ea(a),l=i.find(e=>e.quality===d);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,o.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),yo()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})}c&&(n.encodings=a,o.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}})}function Ea(e){switch(e){case"f":default:return co.HIGH;case"h":return co.MEDIUM;case"q":return co.LOW}}function xa(e,t,i,n){if(!i)return[new ct({quality:co.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new Ta(n),o=[],r="h"==s.suffix?1.5:2,a="h"==s.suffix?2:3;for(let n=0;n<s.spatial;n+=1)o.push(new ct({quality:Math.min(co.HIGH,s.spatial-1)-n,width:Math.ceil(e/Math.pow(r,n)),height:Math.ceil(t/Math.pow(r,n)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,n)):0,ssrc:0}));return o}return i.map(i=>{var n,s,o;const r=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=Ea(null!==(s=i.rid)&&void 0!==s?s:"");return new ct({quality:a,width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:null!==(o=i.maxBitrate)&&void 0!==o?o:0,ssrc:0})})}const Ra="_lossy",Pa="_reliable",Ia="leave-reconnect";var Oa;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(Oa||(Oa={}));class Aa extends cn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Xr.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Oa.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 Er,this.reliableReceivedState=new xr(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>nn(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===Pa)t.reliableDCSub=i;else{if(i.label!==Ra)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>nn(this,void 0,void 0,function*(){var t,i,n,s,o;const r=yield this.dataProcessLock.lock();try{let r;if(e.data instanceof ArrayBuffer)r=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));r=yield e.data.arrayBuffer()}const a=lt.fromBinary(new Uint8Array(r));if(a.sequence>0&&""!==a.participantSid){const e=this.reliableReceivedState.get(a.participantSid);if(e&&a.sequence<=e)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}if("speaker"===(null===(t=a.value)||void 0===t?void 0:t.case))this.emit(Rs.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 e=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),t=pt.fromBinary(e.payload),i=new lt({value:t.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&_a(i,i.value.value),this.emit(Rs.DataPacketReceived,i,a.value.value.encryptionType)}else"user"===(null===(o=a.value)||void 0===o?void 0:o.case)&&_a(a,a.value.value),this.emit(Rs.DataPacketReceived,a,ot.NONE)}finally{r()}}),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?ut.LOSSY:ut.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(Rs.Disconnected),this.close()},n=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==s?(e===Ia&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=js.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),s)):i(n)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===Oa.Connected&&e();const i=()=>{this.off(Rs.Disconnected,n),e()},n=()=>{this.off(Rs.Restarted,i),t()};this.once(Rs.Restarted,i),this.once(Rs.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{if(e===ut.RELIABLE){const t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Rs.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>nn(this,void 0,void 0,function*(){if(!this.url)return;(yield fetch(qo(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===Sr.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Sr.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Je.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>nn(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(qo(this.url),{method:"HEAD"}),mo(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Xi(null!==(t=e.loggerName)&&void 0!==t?t:Ji.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Tr(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new s,this.dataProcessLock=new s,this.dcBufferStatus=new Map([[ut.LOSSY,!0],[ut.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(Rs.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Rs.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Rs.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Rs.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Rs.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Rs.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Rs.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Rs.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,o;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(o=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===o?void 0:o.identity,pID:this.participantSid}}join(e,t,i,n){return nn(this,arguments,void 0,function(e,t,i,n){var s=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){s.url=e,s.token=t,s.signalOpts=i,s.maxJoinAttempts=i.maxRetries;try{s.joinAttempts+=1,s.setupSignalClientCallbacks();const r=yield s.client.join(e,t,i,n,o);return s._isClosed=!1,s.latestJoinResponse=r,s.subscriberPrimary=r.subscriberPrimary,s.pcManager||(yield s.configure(r,!o)),s.subscriberPrimary&&!r.fastPublish||s.negotiate().catch(e=>{Qi.error(e,s.logContext)}),s.registerOnLineListener(),s.clientConfiguration=r.clientConfiguration,s.emit(Rs.SignalConnected,r),r}catch(r){if(r instanceof Is)if(r.reason===Ts.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(e,t,i,n,o)}else if(r.reason===Ts.ServiceNotFound)return s.log.warn("Initial connection failed: ".concat(r.message," – Retrying")),s.join(e,t,i,n,!0);throw r}}()})}close(){return nn(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Rs.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return nn(this,void 0,void 0,function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Er,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 nn(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new As("a track with the same ID has already been published");return new Promise((t,i)=>{const n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(Is.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return nn(this,void 0,void 0,function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return nn(this,void 0,void 0,function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==Zr.NEW)return;this.participantSid=null===(i=e.participant)||void 0===i?void 0:i.sid;const s=this.makeRTCConfiguration(e);var o;this.pcManager=new ea(s,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(Rs.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>nn(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===Zr.CONNECTED){const t=this.pcState===Oa.New;this.pcState=Oa.Connected,t&&this.emit(Rs.Connected,e)}else t===Zr.FAILED&&(this.pcState!==Oa.Connected&&this.pcState!==Oa.Reconnecting||(this.pcState=Oa.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?Je.RR_SUBSCRIBER_FAILED:Je.RR_PUBLISHER_FAILED)));const s=this.client.isDisconnected||this.client.currentState===Sr.RECONNECTING,o=[Zr.FAILED,Zr.CLOSING,Zr.CLOSED].includes(t);s&&o&&!this._isClosed&&this.emit(Rs.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(Rs.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(o=null===(n=e.serverInfo)||void 0===n?void 0:n.protocol)&&o>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>nn(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>nn(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Rs.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Rs.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Rs.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Rs.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(Rs.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const n={direction:"recvonly"};for(let i=0;i<e.numAudios;i++)null===(t=this.pcManager)||void 0===t||t.addPublisherTransceiverOfKind("audio",n);for(let t=0;t<e.numVideos;t++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("video",n);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",Je.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:e.regions})),e.action){case ai.DISCONNECT:this.emit(Rs.Disconnected,null==e?void 0:e.reason),this.close();break;case ai.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Ia);break;case ai.RESUME:this.handleDisconnect(Ia)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach(e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ge.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ra,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Pa,{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 e=this.dataChannelForKind(ut.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,8192),262144)}},1e3))}createSender(e,t,i){return nn(this,void 0,void 0,function*(){if(go()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(fo()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new Ms("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return nn(this,void 0,void 0,function*(){if(go())return this.createSimulcastTransceiverSender(e,t,i,n);if(fo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ms("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return nn(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ms("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Jo(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};i&&(s.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,n){return nn(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ms("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return nn(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ms("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return nn(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)Qi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Ge.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:Zr.NEW)!==Zr.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof Ms?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof Fs||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",Je.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(Rs.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return nn(this,void 0,void 0,function*(){var t,i,n;try{if(!this.url||!this.token)throw new Ms("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Rs.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 Fs;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(e){if(e instanceof Is&&e.reason===Ts.NotAllowed)throw new Ms("could not reconnect, token might be expired");throw new Fs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Rs.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Sr.CONNECTED)throw new Fs("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(Rs.Restarted)}catch(e){const t=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),e}})}resumeConnection(e){return nn(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Ms("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ms("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Rs.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t="";if(e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof Is&&e.reason===Ts.NotAllowed)throw new Ms("could not reconnect, token might be expired");if(e instanceof Is&&e.reason===Ts.LeaveRequest)throw e;throw new Fs(t)}if(this.emit(Rs.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Sr.CONNECTED)throw new Fs("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(Rs.Resumed)})}waitForPCInitialConnection(e,t){return nn(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ms("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return nn(this,void 0,void 0,function*(){this.pcState=Oa.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield mo(2e3),!this.pcManager)throw new Ms("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Oa.Connected}catch(e){throw this.pcState=Oa.Disconnected,Is.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,n){return nn(this,void 0,void 0,function*(){const s=new lt({destinationIdentities:[e],kind:ut.RELIABLE,value:{case:"rpcResponse",value:new Ct({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,ut.RELIABLE)})}publishRpcAck(e,t){return nn(this,void 0,void 0,function*(){const i=new lt({destinationIdentities:[e],kind:ut.RELIABLE,value:{case:"rpcAck",value:new Tt({requestId:t})}});yield this.sendDataPacket(i,ut.RELIABLE)})}sendDataPacket(e,t){return nn(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=function(e){var t,i,n,s,o;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"speaker"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"transcription"!==(null===(s=e.value)||void 0===s?void 0:s.case)&&"encryptedPacket"!==(null===(o=e.value)||void 0===o?void 0:o.case))return new pt({value:e.value})}(e);if(t){const i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new ht({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===ut.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===ut.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t))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(t)})}resendReliableMessagesForResume(e){return nn(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(ut.RELIABLE);const t=this.dataChannelForKind(ut.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(ut.RELIABLE)})}waitForBufferStatusLow(e){return new ms((t,i)=>nn(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i(new Ms("engine closed"));for(this.once(Rs.Closing,n);!this.dcBufferStatus.get(e);)yield mo(10);this.off(Rs.Closing,n),t()}}))}ensureDataTransportConnected(e){return nn(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new Ms("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw Is.internal("".concat(o," connection not set"));let r=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),r=!0),r||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(r=!0),r&&t.negotiate().catch(e=>{Qi.error(e,t.logContext)});const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield mo(50)}throw Is.internal("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()))}()})}ensurePublisherConnected(e){return nn(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===Zr.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return nn(this,void 0,void 0,function*(){return new ms((e,t)=>nn(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new Ds("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new Ds("cannot negotiate on closed engine")),this.on(Rs.Closing,n),this.pcManager.publisher.once(Vr,e=>{const t=new Map;e.forEach(e=>{const i=e.codec.toLowerCase();var n;n=i,Vs.includes(n)&&t.set(e.payload,i)}),this.emit(Rs.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(e){e instanceof Ds&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Je.RR_UNKNOWN),e instanceof Error?t(e):t(new Error(String(e)))}finally{this.off(Rs.Closing,n)}}))})}dataChannelForKind(e,t){if(t){if(e===ut.LOSSY)return this.lossyDCSub;if(e===ut.RELIABLE)return this.reliableDCSub}else{if(e===ut.LOSSY)return this.lossyDC;if(e===ut.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n,s,o;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const r=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),c=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),d=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getLocalDescription(),l=null===(o=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===o||o,u=new Array,h=new Array;e.forEach(e=>{e.isDesired!==l&&u.push(e.trackSid),e.isEnabled||h.push(e.trackSid)}),this.client.sendSyncState(new Ei({answer:"publisher-only"===this.pcManager.mode?a?wr({sdp:a.sdp,type:a.type}):void 0:d?wr({sdp:d.sdp,type:d.type}):void 0,offer:"publisher-only"===this.pcManager.mode?r?wr({sdp:r.sdp,type:r.type}):void 0:c?wr({sdp:c.sdp,type:c.type}):void 0,subscription:new ii({trackSids:u,subscribe:!l,participantTracks:[]}),publishTracks:no(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:h,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new xi({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Ri({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(ut.LOSSY),$t.PUBLISHER),t(this.dataChannelForKind(ut.RELIABLE),$t.PUBLISHER),t(this.dataChannelForKind(ut.LOSSY,!0),$t.SUBSCRIBER),t(this.dataChannelForKind(ut.RELIABLE,!0),$t.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&js.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){wo()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){wo()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(i){const e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===i});if(e)return e[1]}}}function _a(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}class Ma{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new Us("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Cs.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Us("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Cs.LengthExceeded)}}constructor(e,t,i,n){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class Da extends Ma{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new $o,i=null,n=null;if(this.signal){const e=this.signal;n=()=>{var i;null===(i=t.reject)||void 0===i||i.call(t,e.reason)},e.addEventListener("abort",n),i=e}const s=()=>{e.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>nn(this,void 0,void 0,function*(){var i,n;try{const{done:s,value:o}=yield Promise.race([e.read(),t.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(o),{done:!1,value:o.content})}catch(e){throw s(),e}}),return(){return nn(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return nn(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,o;let r=new Set;const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=on(a);!(i=(c=yield l.next()).done);d=!0){o=c.value,d=!1;const e=o;r.add(e)}}catch(e){n={error:e}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return Array.from(r)}()})}}class Na extends Ma{constructor(e,t,i,n){super(e,t,i,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=zo(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new $o,n=null,s=null;if(this.signal){const e=this.signal;s=()=>{var t;null===(t=i.reject)||void 0===t||t.call(i,e.reason)},e.addEventListener("abort",s),n=e}const o=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>nn(this,void 0,void 0,function*(){var n,s;try{const{done:o,value:r}=yield Promise.race([e.read(),i.promise,null!==(s=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==s?s:new Promise(()=>{})]);if(o)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(r);try{e=t.decode(r.content)}catch(e){throw new Us("Cannot decode datastream chunk ".concat(r.chunkIndex," as text: ").concat(e),Cs.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw o(),e}}),return(){return nn(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return nn(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,o;let r="";const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=on(a);!(i=(c=yield l.next()).done);d=!0){o=c.value,d=!1;r+=o}}catch(e){n={error:e}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return r}()})}}class La{constructor(){this.log=Qi,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Us('A text stream handler for topic "'.concat(e,'" has already been set.'),Cs.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Us('A byte stream handler for topic "'.concat(e,'" has already been set.'),Cs.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,n,s;const o=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),r=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(o.length>0||r.length>0){const a=new Us("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Cs.AbnormalEnd);for(const[e,n]of r)null===(i=(t=n.outOfBandFailureRejectingFuture).reject)||void 0===i||i.call(t,a),this.byteStreamControllers.delete(e);for(const[e,t]of o)null===(s=(n=t.outOfBandFailureRejectingFuture).reject)||void 0===s||s.call(n,a),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return nn(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return nn(this,void 0,void 0,function*(){var n;if("byteHeader"===e.contentHeader.case){const s=this.byteStreamHandlers.get(e.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let o;const r=new $o;r.promise.catch(e=>{this.log.error(e)});const a={id:e.streamId,name:null!==(n=e.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:zo(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(o=i,this.textStreamControllers.has(e.streamId))throw new Us("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Cs.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:r})}});s(new Da(a,c,zo(e.totalLength),r),{identity:t})}else if("textHeader"===e.contentHeader.case){const n=this.textStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let s;const o=new $o;o.promise.catch(e=>{this.log.error(e)});const r={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i},a=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(e.streamId))throw new Us("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Cs.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:r,controller:s,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});n(new Na(r,a,zo(e.totalLength),o),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Us("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Cs.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new Us("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),Cs.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Us("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Cs.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new Us("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),Cs.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Ua{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return nn(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)})}}class Fa extends Ua{}class ja extends Ua{}class Ba{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return nn(this,void 0,void 0,function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,o=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map(()=>crypto.randomUUID()),r=new Array(o?o.length+1:1).fill(0),a=(e,i)=>{var n;r[i]=e;const s=r.reduce((e,t)=>e+t,0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:o,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&o&&(yield Promise.all(t.attachments.map((e,i)=>nn(this,void 0,void 0,function*(){return this._sendFile(o[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))),c.info})}streamText(e){return nn(this,void 0,void 0,function*(){var t,i,n;const s=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),o={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null===(n=this.engine.e2eeManager)||void 0===n?void 0:n.isDataChannelEncryptionEnabled)?ot.GCM:ot.NONE},r=new Ut({streamId:s,mimeType:o.mimeType,topic:o.topic,timestamp:Wo(o.timestamp),totalLength:Wo(null==e?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new Nt({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?Dt.UPDATE:Dt.CREATE})}}),a=null==e?void 0:e.destinationIdentities,c=new lt({destinationIdentities:a,value:{case:"streamHeader",value:r}});yield this.engine.sendDataPacket(c,ut.RELIABLE);let d=0;const l=this.engine,u=new WritableStream({write(e){return nn(this,void 0,void 0,function*(){for(const t of function(e,t){const i=[];let n=(new TextEncoder).encode(e);for(;n.length>t;){let e=t;for(;e>0;){const t=n[e];if(void 0!==t&&128!=(192&t))break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,15e3)){const e=new Ft({content:t,streamId:s,chunkIndex:Wo(d)}),i=new lt({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(i,ut.RELIABLE),d+=1}})},close(){return nn(this,void 0,void 0,function*(){const e=new jt({streamId:s}),t=new lt({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield l.sendDataPacket(t,ut.RELIABLE)})},abort(e){console.log("Sink error:",e)}});let h=()=>nn(this,void 0,void 0,function*(){yield p.close()});l.once(Rs.Closing,h);const p=new Fa(u,o,()=>this.engine.off(Rs.Closing,h));return p})}sendFile(e,t){return nn(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return nn(this,void 0,void 0,function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:e,value:t}=yield o.read();if(e)break;yield s.write(t)}return yield s.close(),s.info})}streamBytes(e){return nn(this,void 0,void 0,function*(){var t,i,n,o,r,a;const c=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),d=null==e?void 0:e.destinationIdentities,l={id:c,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(o=null==e?void 0:e.name)&&void 0!==o?o:"unknown",encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?ot.GCM:ot.NONE},u=new Ut({totalLength:Wo(null!==(a=l.size)&&void 0!==a?a:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:Wo(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new Lt({name:l.name})}}),h=new lt({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,ut.RELIABLE);let p=0;const m=new s,g=this.engine,f=this.log,v=new WritableStream({write(e){return nn(this,void 0,void 0,function*(){const t=yield m.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3),n=new lt({destinationIdentities:d,value:{case:"streamChunk",value:new Ft({content:t,streamId:c,chunkIndex:Wo(p)})}});yield g.sendDataPacket(n,ut.RELIABLE),p+=1,i+=t.byteLength}}finally{t()}})},close(){return nn(this,void 0,void 0,function*(){const e=new jt({streamId:c}),t=new lt({destinationIdentities:d,value:{case:"streamTrailer",value:e}});yield g.sendDataPacket(t,ut.RELIABLE)})},abort(e){f.error("Sink error:",e)}});return new ja(v,l)})}}class $a extends lo{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Ps.Muted:Ps.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Ps.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return nn(this,void 0,void 0,function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),oa)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(Ps.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Va extends $a{constructor(e,t,i,n,s,o){super(e,t,lo.Kind.Audio,i,o),this.monitorReceiver=()=>nn(this,void 0,void 0,function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ra(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Eo()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Eo())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return nn(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(bo(t))return t.setSinkId(e)}))})}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&bo(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(Ps.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(Ps.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return nn(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})}),e})}}class qa extends $a{constructor(e,t,i,n,s){super(e,t,lo.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>nn(this,void 0,void 0,function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ra(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=jr(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===lo.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?ho(this._mediaStreamTrack,t):uo(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){const t=new Ha(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter(t=>t===e);for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return nn(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach(e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)}),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(t=>t.element===e);for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return nn(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const n=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),s=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,o=this.elementInfos.some(e=>e.pictureInPicture),r=this.elementInfos.some(e=>e.visible)&&!s||o;(this.lastVisible!==r||e)&&(!r&&Date.now()-n<100?js.setTimeout(()=>{this.updateVisibility()},100):(this.lastVisible=r,this.emit(Ps.VisibilityChanged,r,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,o=e.height()*s;t+o>i+n&&(i=t,n=o)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Ps.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return Oo();if(!t){return Oo()>2?2:1}return t}}class Ha{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=za(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=za(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=za(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Wa(e),this.isPiP=wo()&&za(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Wa(this.element),this.isPiP=za(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Uo().observe(this.element),No().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=Uo())||void 0===e||e.unobserve(this.element),null===(t=No())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function za(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Wa(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Wa(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const o=e.offsetWidth,r=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+r>i.pageYOffset&&s+o>i.pageXOffset&&!a&&"none"!==c}class Ga extends cn.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=ot.NONE,this.log=Qi,this.handleMuted=()=>{this.emit(Ps.Muted)},this.handleUnmuted=()=>{this.emit(Ps.Unmuted)},this.log=Xi(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:Ji.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=lo.Source.Unknown}setTrack(e){this.track&&(this.track.off(Ps.Muted,this.handleMuted),this.track.off(Ps.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Ps.Muted,this.handleMuted),e.on(Ps.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),so(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ot.NONE}get audioTrack(){if(Ko(this.track))return this.track}get videoTrack(){if(Jo(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=lo.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===lo.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}!function(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(Ga||(Ga={}));class Ka extends Ga{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Ps.Ended)},this.handleCpuConstrained=()=>{this.track&&Jo(this.track)&&this.emit(Ps.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(Ps.Ended,this.handleTrackEnded),this.track.off(Ps.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(Ps.Ended,this.handleTrackEnded),e.on(Ps.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 nn(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()})}unmute(){return nn(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()})}pauseUpstream(){return nn(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()})}resumeUpstream(){return nn(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ko(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Qe.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Qe.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Qe.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Qe.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(Qe.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Qe.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function Ja(e,t){return nn(this,void 0,void 0,function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:o}=oo(e);let r=o.audio,a=o.video;if(n&&"object"==typeof o.audio&&(o.audio.processor=n),s&&"object"==typeof o.video&&(o.video.processor=s),e.audio&&"object"==typeof o.audio&&"string"==typeof o.audio.deviceId){const e=o.audio.deviceId;o.audio.deviceId={exact:e},i=!0,r=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&"object"==typeof o.video&&"string"==typeof o.video.deviceId){const e=o.video.deviceId;o.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}!0===o.audio?o.audio={deviceId:"default"}:"object"==typeof o.audio&&null!==o.audio&&(o.audio=Object.assign(Object.assign({},o.audio),{deviceId:o.audio.deviceId||"default"})),!0===o.video?o.video={deviceId:"default"}:"object"!=typeof o.video||o.video.deviceId||(o.video.deviceId="default");const c=Js(o,Jr,Yr),d=Qs(c),l=navigator.mediaDevices.getUserMedia(d);o.audio&&(fr.userMediaPromiseMap.set("audioinput",l),l.catch(()=>fr.userMediaPromiseMap.delete("audioinput"))),o.video&&(fr.userMediaPromiseMap.set("videoinput",l),l.catch(()=>fr.userMediaPromiseMap.delete("videoinput")));try{const e=yield l;return yield Promise.all(e.getTracks().map(i=>nn(this,void 0,void 0,function*(){const o="audio"===i.kind;let r,a=o?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=o?d.audio:d.video;"boolean"!=typeof l&&(r=l);const u=i.getSettings().deviceId;(null==r?void 0:r.deviceId)&&Vo(r.deviceId)!==u?r.deviceId=u:r||(r={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new ua(e,t,!1,void 0,i);case"video":return new Ca(e,t,!1,i);default:throw new As("unsupported track type: ".concat(e.kind))}}(i,r,t);return h.kind===lo.Kind.Video?h.source=lo.Source.Camera:h.kind===lo.Kind.Audio&&(h.source=lo.Source.Microphone),h.mediaStream=e,Ko(h)&&n?yield h.setProcessor(n):Jo(h)&&s&&(yield h.setProcessor(s)),h})))}catch(n){if(!i)throw n;return Ja(Object.assign(Object.assign({},e),{audio:r,video:a}),t)}})}function Ya(e){return nn(this,void 0,void 0,function*(){return(yield Ja({audio:null==e||e,video:!1}))[0]})}var Qa,Xa;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(Qa||(Qa={}));class Za extends cn.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===nt.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===it.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,o){let r=arguments.length>6&&void 0!==arguments[6]?arguments[6]:nt.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Qa.Unknown,this.log=Qi,this.log=Xi(null!==(a=null==o?void 0:o.loggerName)&&void 0!==a?a:Ji.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=r,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new $o,this.once(xs.Active,()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(lo.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(lo.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(lo.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===it.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==it.ACTIVE&&this.emit(xs.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(xs.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(xs.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const o of n)e[o]!==t[o]&&(s[o]=null!==(i=t[o])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(xs.AttributesChanged,t)}setPermissions(e){var t,i,n,s,o,r;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null===(r=this.permissions)||void 0===r?void 0:r.canSubscribeMetrics);return this.permissions=e,c&&this.emit(xs.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(xs.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case We.EXCELLENT:return Qa.Excellent;case We.GOOD:return Qa.Good;case We.POOR:return Qa.Poor;case We.LOST:return Qa.Lost;default:return Qa.Unknown}}(e),t!==this._connectionQuality&&this.emit(xs.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Ko(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(Ps.Muted,()=>{this.emit(xs.TrackMuted,e)}),e.on(Ps.Unmuted,()=>{this.emit(xs.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case lo.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case lo.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class ec extends Za{constructor(e,t,i,n,s,o){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=ot.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new $o)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,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===(o=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===o||o.call(s,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new $o),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Ni.OK&&s.reject(new Ls(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=ia.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Si({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),so(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),so(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),so(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),so(t))),this.emit(xs.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>nn(this,void 0,void 0,function*(){var t,i,n,s,o;if(!(null===(o=this.roomOptions)||void 0===o?void 0:o.dynacast))return;const r=this.videoTrackPublications.get(e.trackSid);if(!r)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!r.videoTrack)return;const a=yield r.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=on(a);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;qs(e)&&(this.log.debug("publish ".concat(e," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),so(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,e,r.options))}}catch(e){i={error:e}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>nn(this,void 0,void 0,function*(){if(e.source===lo.Source.ScreenShare||e.source===lo.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),so(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Qo(e)||Yo(e))try{if(wo())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===lo.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),so(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),so(e))),Qo(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),so(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==ot.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(Rs.RemoteMute,(e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(Rs.Connected,this.handleReconnected).on(Rs.SignalConnected,this.handleSignalConnected).on(Rs.SignalRestarted,this.handleReconnected).on(Rs.SignalResumed,this.handleReconnected).on(Rs.Restarting,this.handleReconnecting).on(Rs.Resuming,this.handleReconnecting).on(Rs.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Rs.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Rs.Closing,this.handleClosing).on(Rs.SignalRequestResponse,this.handleSignalRequestResponse).on(Rs.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return nn(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return nn(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return nn(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return nn(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new ms((e,o)=>nn(t,void 0,void 0,function*(){var t,r;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(r=null!=n?n:this.name)&&void 0!==r?r:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{o(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]})))return this.pendingSignalRequests.delete(c),void e();yield mo(50)}o(new Ls("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error?o(e):o(new Error(String(e)))}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(lo.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(lo.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(lo.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return nn(this,void 0,void 0,function*(){this.encryptionType=e?ot.GCM:ot.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,n){return nn(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t)if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case lo.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case lo.Source.Microphone:t=yield this.createTracks({audio:null===(o=i)||void 0===o||o});break;case lo.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new As(e)}}catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(xs.MediaDevicesError,i,to(e)),this.pendingPublishing.delete(e),i}for(const n of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===lo.Source.Microphone&&Ko(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{const e=[];for(const i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),so(i))),e.push(this.publishTrack(i,n));const i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e)&&(r=yield this.waitForPendingPublicationOfSource(e),r||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),r&&r.track)if(e===lo.Source.ScreenShare){r=yield this.unpublishTrack(r.track);const e=this.getTrackPublication(lo.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r})}enableCameraAndMicrophone(){return nn(this,void 0,void 0,function*(){if(!this.pendingPublishing.has(lo.Source.Camera)&&!this.pendingPublishing.has(lo.Source.Microphone)){this.pendingPublishing.add(lo.Source.Camera),this.pendingPublishing.add(lo.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(lo.Source.Camera),this.pendingPublishing.delete(lo.Source.Microphone)}}})}createTracks(e){return nn(this,void 0,void 0,function*(){var t,i;null!=e||(e={});const n=Js(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const e=yield Ja(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return e.map(e=>(Ko(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=lo.Source.Microphone,this.emit(xs.AudioStreamAcquired)),Jo(e)&&(this.cameraError=void 0,e.source=lo.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return nn(this,void 0,void 0,function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Os("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=vs();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&Ao(e.osVersion,"17")>=0}()||(e.resolution=Ks.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=So()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new As("no video track found");const s=new Ca(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=lo.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(xs.AudioStreamAcquired);const e=new ua(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=lo.Source.ScreenShareAudio,o.push(e)}return o})}publishTrack(e,t){return nn(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return nn(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,o,r,a;let c,d;if(Qo(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),Go(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case lo.Source.Microphone:t="audioinput";break;case lo.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new ua(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new Ca(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new As("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(d=t)}),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),so(d))),d;const l=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),u="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,h=null!==(o=l.forceStereo)&&void 0!==o?o:u;h&&(void 0===l.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),so(e))),void 0===l.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=l.dtx)&&void 0!==r||(l.dtx=!1),null!==(a=l.red)&&void 0!==a||(l.red=!1)),!function(){const e=vs(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Ao(e.osVersion,t)>=0)||"Safari"===e.name&&Ao(e.version,t)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const p=new Promise((t,n)=>nn(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Sr.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:so(e)}));let i=!1;const s=setTimeout(()=>{i=!0,e.stop(),n(new Ns("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(s),i)return;const o=yield this.publish(e,l,h);t(o)}else try{const i=yield this.publish(e,l,h);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new $o),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),so(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map(e=>function(e){switch(e){case He.CAMERA:return lo.Source.Camera;case He.MICROPHONE:return lo.Source.Microphone;case He.SCREEN_SHARE:return lo.Source.ScreenShare;case He.SCREEN_SHARE_AUDIO:return lo.Source.ScreenShareAudio;default:return lo.Source.Unknown}}(e)).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),so(e))),!1)}publish(e,t,i){return nn(this,void 0,void 0,function*(){var n,s,o,r,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new Ns("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>Go(e)&&t.source===e.source)&&e.source!==lo.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),so(e))),t.stopMicTrackOnMute&&Ko(e)&&(e.stopOnMute=!0),e.source===lo.Source.ScreenShare&&yo()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(So()||yo())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(yo())return!1;if(So()){const e=vs();if((null==e?void 0:e.version)&&Ao(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&Ao(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/vp9"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=Gr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===io(e.mime))||(t.videoCodec=io(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Ps.Muted,this.onTrackMuted),e.on(Ps.Unmuted,this.onTrackUnmuted),e.on(Ps.Ended,this.handleTrackEnded),e.on(Ps.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Ps.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Ps.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(n=t.dtx)||void 0===n||n),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(Qe.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(Qe.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(Qe.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(Qe.TF_STEREO),g&&m.push(Qe.TF_NO_DTX),Qo(e)&&e.hasPreConnectBuffer&&m.push(Qe.TF_PRECONNECT_BUFFER);const v=new Gt({cid:e.mediaStreamTrack.id,name:t.name,type:lo.kindToProto(e.kind),muted:e.isMuted,source:lo.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m});let b;if(e.kind===lo.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(t){const n=null!==(r=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==r?r:Ws.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),so(e)),{dims:i}))}v.width=i.width,v.height=i.height,Yo(e)&&(vo(p)&&(e.source===lo.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),so(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),v.simulcastCodecs=[new Wt({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:Gr}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===ot.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new Wt({codec:t.backupCodec.codec,cid:""})))),b=ba(e.source===lo.Source.ScreenShare,v.width,v.height,t),v.layers=xa(v.width,v.height,b,vo(t.videoCodec))}else e.kind===lo.Kind.Audio&&(b=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ms("cannot publish track when not connected");const y=()=>nn(this,void 0,void 0,function*(){var i,n,s;if(!this.engine.pcManager)throw new Ms("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(xs.LocalSenderCreated,e.sender,e),Yo(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===lo.Source.ScreenShare||e.constraints.height&&Vo(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),b)if(yo()&&e.kind===lo.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=b[0])||void 0===n?void 0:n.maxBitrate)?b[0].maxBitrate/1e3:0})}else e.codec&&vo(e.codec)&&(null===(s=b[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let k;const S=new Promise((t,i)=>nn(this,void 0,void 0,function*(){var n;try{k=yield this.engine.addTrack(v),t(k)}catch(t){e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),so(e)),{error:t}))})),i(t)}}));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([S,y()]);k=e[0]}else{let i;if(k=yield S,k.codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===lo.Kind.Video){const n=io(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),so(e)),{codec:n})),t.videoCodec=n,b=ba(e.source===lo.Source.ScreenShare,v.width,v.height,t))}yield y()}const T=new Ka(e.kind,k,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(T.on(Ps.CpuConstrained,e=>this.onTrackCpuConstrained(e,T)),T.options=t,e.sid=k.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:k})),Yo(e)?e.startMonitor(this.engine.client):Qo(e)&&e.startMonitor(),this.addTrackPublication(T),this.emit(xs.LocalTrackPublished,T),Qo(e)&&k.audioFeatures.includes(Qe.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();if(this.on(xs.LocalTrackSubscribed,t=>{if(t.trackSid===k.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),so(e))),e.stopPreConnectBuffer()}}),t){const n=new Promise((n,s)=>nn(this,void 0,void 0,function*(){var o,r,a,c,d,l;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),so(e)));const m=setTimeout(()=>{s(new Error("agent not active within 10 seconds"))},1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),so(e)));const v=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:T.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=on(t);!(o=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){r={error:e}}finally{try{h||o||!(a=p.return)||(yield a.call(p))}finally{if(r)throw r.error}}yield v.close(),n()}catch(e){s(e)}}));n.then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),so(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),so(e)),{error:t}))})}}return T})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return nn(this,void 0,void 0,function*(){var n;if(this.encryptionType!==ot.NONE)return;let s;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(s=t)}),!s)throw new As("track is not published");if(!Yo(e))throw new As("track is not a video track");const o=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),r=function(e,t,i){var n,s,o,r;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Qi.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(o=a.height)&&void 0!==o?o:null===(r=e.dimensions)||void 0===r?void 0:r.height;return e.source===lo.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),ba(e.source===lo.Source.ScreenShare,c,d,i)}(e,t,o);if(!r)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),so(e)));const a=e.addSimulcastTrack(t,r);if(!a)return;const c=new Gt({cid:a.mediaStreamTrack.id,type:lo.kindToProto(e.kind),muted:e.isMuted,source:lo.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=xa(c.width,c.height,r),!this.engine||this.engine.isClosed)throw new Ms("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>nn(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,o,r),yield this.engine.negotiate()}))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:r,trackInfo:d}))})}unpublishTrack(e,t){return nn(this,void 0,void 0,function*(){var i,n;if(Go(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),so(e))),yield t)}const s=this.getPublicationForTrack(e),o=s?so(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));(e=s.track).off(Ps.Muted,this.onTrackMuted),e.off(Ps.Unmuted,this.onTrackUnmuted),e.off(Ps.Ended,this.handleTrackEnded),e.off(Ps.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Ps.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Ps.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let r=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Zr.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",r=!0);if(this.engine.removeTrack(a)&&(r=!0),Yo(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(r=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:e}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case lo.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case lo.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(xs.LocalTrackUnpublished,s),s.setTrack(void 0),r&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return nn(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return nn(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new ms((n,s)=>nn(t,void 0,void 0,function*(){try{const t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>nn(this,void 0,void 0,function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===lo.Source.ScreenShare||t.source===lo.Source.ScreenShareAudio||!Qo(t)&&!Yo(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),n()}catch(e){e instanceof Error?s(e):s(new Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return nn(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?ut.RELIABLE:ut.LOSSY,s=i.destinationIdentities,o=i.topic;let r=new ft({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:o});const a=new lt({kind:n,value:{case:"user",value:r}});yield t.engine.sendDataPacket(a,n)}()})}publishDtmf(e,t){return nn(this,void 0,void 0,function*(){const i=new lt({kind:ut.RELIABLE,value:{case:"sipDtmf",value:new vt({code:e,digit:t})}});yield this.engine.sendDataPacket(i,ut.RELIABLE)})}sendChatMessage(e,t){return nn(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new lt({value:{case:"chatMessage",value:new kt(Object.assign(Object.assign({},i),{timestamp:x.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,ut.RELIABLE),this.emit(xs.ChatMessage,i),i})}editChatMessage(e,t){return nn(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new lt({value:{case:"chatMessage",value:new kt(Object.assign(Object.assign({},i),{timestamp:x.parse(i.timestamp),editTimestamp:x.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,ut.RELIABLE),this.emit(xs.ChatMessage,i),i})}sendText(e,t){return nn(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return nn(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return nn(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return nn(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:n,responseTimeout:s=15e3}=e;return new ms((e,o)=>nn(this,void 0,void 0,function*(){var r,a,c,d;if(na(n)>15360)return void o(ia.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(r=this.engine.latestJoinResponse)||void 0===r?void 0:r.serverInfo)||void 0===a?void 0:a.version)&&Ao(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(ia.builtIn("UNSUPPORTED_SERVER"));const l=Math.max(s,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(t,u,i,n,l);const h=setTimeout(()=>{this.pendingAcks.delete(u),o(ia.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)},7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:t});const p=setTimeout(()=>{this.pendingResponses.delete(u),o(ia.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(u,{resolve:(t,i)=>{clearTimeout(p),this.pendingAcks.has(u)&&(this.log.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),i?o(i):e(null!=t?t:"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return nn(this,void 0,void 0,function*(){const o=new lt({destinationIdentities:[e],kind:ut.RELIABLE,value:{case:"rpcRequest",value:new St({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,ut.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,ia.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),so(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}}),!0)}setActiveAgent(e){var t,i,n,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(s=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new $o),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(Qo(n)||Yo(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return nn(this,void 0,void 0,function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield mo(20)}})}}class tc extends Ga{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Ps.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new ii({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Et({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Ps.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Ga.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ga.SubscriptionStatus.Subscribed:Ga.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ga.PermissionStatus.Allowed:Ga.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.requestedDisabled!==!e&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)===e.height||(er(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&er(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:co.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(Ps.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Ps.VisibilityChanged,this.handleVisibilityChange),n.off(Ps.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Ps.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Ps.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Ps.VisibilityChanged,this.handleVisibilityChange),e.on(Ps.Ended,this.handleEnded),this.emit(Ps.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Ps.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Ps.Muted:Ps.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Ps.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Ps.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return er(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ni({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===lo.Kind.Video){let s=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(s){ro(this.videoDimensionsAdaptiveStream,s)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(t=this.trackInfo,i=this.requestedMaxQuality,null===(n=t.layers)||void 0===n?void 0:n.find(e=>e.quality===i));e&&ro(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream;s?(e.width=Math.ceil(s.width),e.height=Math.ceil(s.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:co.HIGH})),e.quality=co.HIGH)}var t,i,n;this.emit(Ps.UpdateSettings,e)}}class ic extends Za{static fromParticipantInfo(e,t,i){return new ic(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,o,r){super(t,i||"",n,s,o,r,arguments.length>7&&void 0!==arguments[7]?arguments[7]:nt.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Ps.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),so(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(Ps.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(Ps.SubscriptionPermissionChanged,t=>{this.emit(xs.TrackSubscriptionPermissionChanged,e,t)}),e.on(Ps.SubscriptionStatusChanged,t=>{this.emit(xs.TrackSubscriptionStatusChanged,e,t)}),e.on(Ps.Subscribed,t=>{this.emit(xs.TrackSubscribed,t,e)}),e.on(Ps.Unsubscribed,t=>{this.emit(xs.TrackUnsubscribed,t,e)}),e.on(Ps.SubscriptionFailed,t=>{this.emit(xs.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:lo.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:lo.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,o){let r=this.getTrackPublicationBySid(t);if(r||t.startsWith("TR")||this.trackPublications.forEach(t=>{r||e.kind!==t.kind.toString()||(r=t)}),!r)return 0===o?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(xs.TrackSubscriptionFailed,t)):(void 0===o&&(o=20),void setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,s,o-1)},150));if("ended"===e.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),so(r))),void this.emit(xs.TrackSubscriptionFailed,t);let a;return a="video"===e.kind?new qa(e,t,n,s):new Va(e,t,n,this.audioContext,this.audioOutput),a.source=r.source,a.isMuted=r.isMuted,a.setMediaStream(i),a.start(),r.setTrack(a),this.volumeMap.has(r.source)&&Xo(a)&&Ko(a)&&a.setVolume(this.volumeMap.get(r.source)),r}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,s;let o=this.getTrackPublicationBySid(e.sid);if(o)o.updateInfo(e);else{const t=lo.kindFromProto(e.type);if(!t)return;o=new tc(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),o.updateInfo(e),i.set(e.sid,o);const r=Array.from(this.trackPublications.values()).find(e=>e.source===(null==o?void 0:o.source));r&&o.source!==lo.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:so(r),newTrack:so(o)})),this.addTrackPublication(o)}t.set(e.sid,o)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),so(e))),this.unpublishTrack(e.trackSid,!0))}),i.forEach(e=>{this.emit(xs.TrackPublished,e)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case lo.Kind.Audio:this.audioTrackPublications.delete(e);break;case lo.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(xs.TrackUnpublished,i)}setAudioOutput(e){return nn(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var n;Ko(i.track)&&Xo(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(Xa||(Xa={}));class nc extends cn.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,o,r;if(super(),t=this,this.state=Xa.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=(e,t,i)=>nn(this,void 0,void 0,function*(){var n;if("undefined"==typeof RTCPeerConnection||!go()&&!fo())throw Eo()?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===Xa.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(Xa.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==ir(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),xo(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new ta(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));const o=(n,r,a)=>nn(this,void 0,void 0,function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{if(yield mr.getInstance().getBackOffPromise(e),l.signal.aborted)throw Is.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=a?a:e,t,i,l),this.abortController=void 0,n()}catch(t){if(this.regionUrlProvider&&t instanceof Is&&t.reason!==Ts.Cancelled&&t.reason!==Ts.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof Is&&(401===e.status||e.reason===Ts.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void r(e)}[Ts.InternalError,Ts.ServerUnreachable,Ts.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),mr.getInstance().addFailedConnectionAttempt(e)),i&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield o(n,r,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ho(t)),r(t))}else{let e=Ke.UNKNOWN_REASON;t instanceof Is&&(e=Ho(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),r(t)}}}),r=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new $o((e,t)=>{o(e,t,r)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,s,o)=>nn(this,void 0,void 0,function*(){var r,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},o.signal,!s.singlePeerConnection);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null===(r=d.room)||void 0===r?void 0:r.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new _s("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d}),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>nn(this,void 0,void 0,function*(){var s,o;this.state===Xa.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Xr),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Es.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=n.signal.aborted?Is.cancelled("Signal connection aborted"):Is.serverUnreachable("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof Is&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:e})),t}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),Is.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}wo()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),wo()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Xa.Connected),this.emit(Es.Connected),mr.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return nn(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s;const o=yield e.disconnectLock.lock();try{if(e.state===Xa.Disconnected)return void e.log.debug("already disconnected",e.logContext);if(e.log.info("disconnect from room",Object.assign({},e.logContext)),e.state===Xa.Connecting||e.state===Xa.Reconnecting||e.isResuming){const t="Abort connection attempt due to user initiated disconnect";e.log.warn(t,e.logContext),null===(i=e.abortController)||void 0===i||i.abort(t),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,Is.cancelled("Client initiated disconnect")),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,Ke.CLIENT_INITIATED),e.engine=void 0}finally{o()}}()})},this.onPageLeave=()=>nn(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>nn(this,void 0,void 0,function*(){const e=[],t=vs();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=Bo();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(Es.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>nn(this,void 0,void 0,function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Xa.Reconnecting)&&this.emit(Es.Reconnecting)},this.handleSignalRestarted=e=>nn(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(Xa.Connected),this.emit(Es.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===it.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(Es.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach(e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});const i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(Es.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=lo.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(xs.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Es.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i,n)=>{this.emit(Es.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(xs.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit(Es.SipDTMFReceived,t,e),null==e||e.emit(xs.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map(e=>{let{id:i,text:n,language:s,startTime:o,endTime:r,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(r.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}})}(t,this.transcriptionReceivedTimes);null==n||n.emit(Ps.TranscriptionReceived,s),null==i||i.emit(xs.TranscriptionReceived,s,n),this.emit(Es.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(Es.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(Es.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Es.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Es.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Es.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Es.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>nn(this,void 0,void 0,function*(){var e;"iOS"!==(null===(e=vs())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit(Es.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Es.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Es.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(Es.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Es.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Es.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Es.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Es.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>nn(this,void 0,void 0,function*(){var t,i,n,s,o,r;if(null===(t=e.track)||void 0===t||t.on(Ps.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(Ps.Restarted,this.onLocalTrackRestarted),null===(o=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===o||o.call(s,this),this.emit(Es.LocalTrackPublished,e,this.localParticipant),Qo(e.track)){(yield e.track.checkForSilence())&&this.emit(Es.LocalAudioSilenceDetected,e)}const a=yield null===(r=e.track)||void 0===r?void 0:r.getDeviceId(!1),c=to(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(Es.ActiveDeviceChanged,c,a))}),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(Ps.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(Ps.Restarted,this.onLocalTrackRestarted),this.emit(Es.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>nn(this,void 0,void 0,function*(){const t=yield e.getDeviceId(!1),i=to(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(Es.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(Es.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(Es.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Es.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Es.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Qr),e),this.log=Xi(null!==(i=this.options.loggerName)&&void 0!==i?i:Ji.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Jr),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Yr),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Kr),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new La,this.outgoingDataStreamManager=new Ba(this.engine,this.log),this.disconnectLock=new s,this.localParticipant=new ec("","",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",Vo(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Vo(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Vo(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),wo()){const e=new AbortController;null===(r=null===(o=navigator.mediaDevices)||void 0===o?void 0:o.addEventListener)||void 0===r||r.call(o,"devicechange",this.handleDeviceChange,{signal:e.signal}),nc.cleanupRegistry&&nc.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return nn(this,void 0,void 0,function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)})}setupE2EE(){var e;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new pr(i,t),this.e2eeManager.on(cr.ParticipantEncryptionStatusChanged,(e,t)=>{(function(e){return e.isLocal})(t)&&(this.isE2EEEnabled=e),this.emit(Es.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(cr.EncryptionError,(e,t)=>{const i=t?this.getParticipantByIdentity(t):void 0;this.emit(Es.EncryptionError,e,i)}),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return this.state===Xa.Disconnected?ms.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?ms.resolve(this.roomInfo.sid):new ms((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(Rs.RoomUpdate,i),e(t.sid))};this.engine.on(Rs.RoomUpdate,i),this.once(Es.Disconnected,()=>{this.engine.off(Rs.RoomUpdate,i),t(new Ms("Room disconnected before room server id was available"))})})}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Aa(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Rs.ParticipantUpdate,this.handleParticipantUpdates).on(Rs.RoomUpdate,this.handleRoomUpdate).on(Rs.SpeakersChanged,this.handleSpeakersChanged).on(Rs.StreamStateChanged,this.handleStreamStateUpdate).on(Rs.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Rs.SubscriptionError,this.handleSubscriptionError).on(Rs.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Rs.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(Rs.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(Rs.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Rs.DataPacketReceived,this.handleDataPacket).on(Rs.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Xa.SignalReconnecting)&&this.emit(Es.SignalReconnecting)}).on(Rs.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Xa.Connected)&&this.emit(Es.Reconnected)}).on(Rs.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Xa.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(Rs.Restarting,this.handleRestarting).on(Rs.SignalRestarted,this.handleSignalRestarted).on(Rs.Offline,()=>{this.setAndEmitConnectionState(Xa.Reconnecting)&&this.emit(Es.Reconnecting)}).on(Rs.DCBufferStatusChanged,(e,t)=>{this.emit(Es.DCBufferStatusChanged,e,t)}).on(Rs.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});t?(this.localParticipant.emit(xs.LocalTrackSubscribed,t),this.emitWhenConnected(Es.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)}).on(Rs.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(Es.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return fr.getInstance().getDevices(e,t)}prepareConnection(e,t){return nn(this,void 0,void 0,function*(){if(this.state===Xa.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(xo(new URL(e))&&t){this.regionUrlProvider=new ta(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Xa.Disconnected&&(this.regionUrl=i,yield fetch(qo(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(qo(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return nn(this,void 0,void 0,function*(){let i,n=()=>nn(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Pi({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Pi({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Pi({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Pi({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=()=>nn(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new Pi({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>nn(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new Pi({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 Pi({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>nn(this,void 0,void 0,function*(){const e=this.engine.client.onLeave;e&&e(new ri({reason:Ke.CLIENT_INITIATED,action:ai.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Pi({scenario:{case:"subscriberBandwidth",value:Wo(t)}});break;case"leave-full-reconnect":i=new Pi({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return nn(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,o,r,a,c,d,l;let u=!0,h=!1;const p=n?{exact:t}:t;if("audioinput"===e){h=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===lo.Source.Microphone);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}const o=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&o&&(h=!0)}else if("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;const t=null!==(o=i.getActiveDevice(e))&&void 0!==o?o:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===lo.Source.Camera);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}const s=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&s&&(h=!0)}else if("audiooutput"===e){if(h=!0,!bo()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!==(r=yield fr.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==r?r:""),null!==(a=(l=i.options).audioOutput)&&void 0!==a||(l.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return h&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(Es.ActiveDeviceChanged,e,t)),u}()})}setupLocalParticipantEvents(){this.localParticipant.on(xs.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(xs.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(xs.AttributesChanged,this.onLocalAttributesChanged).on(xs.TrackMuted,this.onLocalTrackMuted).on(xs.TrackUnmuted,this.onLocalTrackUnmuted).on(xs.LocalTrackPublished,this.onLocalTrackPublished).on(xs.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(xs.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(xs.MediaDevicesError,this.onMediaDevicesError).on(xs.AudioStreamAcquired,this.startAudio).on(xs.ChatMessage,this.onLocalChatMessageSent).on(xs.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Xa.Connecting||this.state===Xa.Reconnecting){const n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,i),s()},s=()=>{this.off(Es.Reconnected,n),this.off(Es.Connected,n),this.off(Es.Disconnected,s)};return this.once(Es.Reconnected,n),this.once(Es.Connected,n),void this.once(Es.Disconnected,s)}if(this.state===Xa.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let o=n[1],r=e.id;if(o&&o.startsWith("TR")&&(r=o),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find(e=>e.sid===s);if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);if(!r.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s),this.logContext);r=e}let c;r.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(o,", trackId: ").concat(r),Object.assign(Object.assign({},this.logContext),{rpID:s,streamId:o,trackId:r})),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=a.addSubscribedMediaTrack(e,r,t,i,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit(Es.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i,n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Xa.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()}),this.localParticipant.off(xs.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(xs.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(xs.AttributesChanged,this.onLocalAttributesChanged).off(xs.TrackMuted,this.onLocalTrackMuted).off(xs.TrackUnmuted,this.onLocalTrackUnmuted).off(xs.LocalTrackPublished,this.onLocalTrackPublished).off(xs.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(xs.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(xs.MediaDevicesError,this.onMediaDevicesError).off(xs.AudioStreamAcquired,this.startAudio).off(xs.ChatMessage,this.onLocalChatMessageSent).off(xs.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),wo()&&(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(Xa.Disconnected),this.emit(Es.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(Es.ParticipantDisconnected,t),t.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,n,s,o){return nn(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==o)return void(yield this.engine.publishRpcResponse(e,t,null,ia.builtIn("UNSUPPORTED_VERSION")));const r=this.rpcHandlers.get(i);if(!r)return void(yield this.engine.publishRpcResponse(e,t,null,ia.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const o=yield r({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});na(o)>15360?(a=ia.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=o}catch(e){e instanceof ia?a=e:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),a=ia.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}selectDefaultDevices(){return nn(this,void 0,void 0,function*(){var e,t,i;const n=fr.getInstance().previousDevices,s=yield fr.getInstance().getDevices(void 0,!1),o=vs();if("Chrome"===(null==o?void 0:o.name)&&"iOS"!==o.os)for(let e of s){const t=n.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(Es.ActiveDeviceChanged,e.kind,e.deviceId)}const r=["audiooutput","audioinput","videoinput"];for(let o of r){const r=eo(o),a=this.localParticipant.getTrackPublication(r);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter(e=>e.kind===o),d=this.getActiveDevice(o);d===(null===(t=n.filter(e=>e.kind===o)[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(o,c[0].deviceId):"audioinput"===o&&!To()||"videoinput"===o||!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(o))||"audiooutput"===o&&To()||(yield this.switchActiveDevice(o,c[0].deviceId))}})}acquireAudioContext(){return nn(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=Zs())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),mo(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Es.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?ic.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new ic(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);if(t){i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity)}return i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Es.ParticipantConnected,i),i.on(xs.TrackPublished,e=>{this.emitWhenConnected(Es.TrackPublished,e,i)}).on(xs.TrackSubscribed,(e,t)=>{e.kind===lo.Kind.Audio?(e.on(Ps.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Ps.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===lo.Kind.Video&&(e.on(Ps.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Ps.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Es.TrackSubscribed,e,t,i)}).on(xs.TrackUnpublished,e=>{this.emit(Es.TrackUnpublished,e,i)}).on(xs.TrackUnsubscribed,(e,t)=>{this.emit(Es.TrackUnsubscribed,e,t,i)}).on(xs.TrackMuted,e=>{this.emitWhenConnected(Es.TrackMuted,e,i)}).on(xs.TrackUnmuted,e=>{this.emitWhenConnected(Es.TrackUnmuted,e,i)}).on(xs.ParticipantMetadataChanged,e=>{this.emitWhenConnected(Es.ParticipantMetadataChanged,e,i)}).on(xs.ParticipantNameChanged,e=>{this.emitWhenConnected(Es.ParticipantNameChanged,e,i)}).on(xs.AttributesChanged,e=>{this.emitWhenConnected(Es.ParticipantAttributesChanged,e,i)}).on(xs.ConnectionQualityChanged,e=>{this.emitWhenConnected(Es.ConnectionQualityChanged,e,i)}).on(xs.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(Es.ParticipantPermissionsChanged,e,i)}).on(xs.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(Es.TrackSubscriptionStatusChanged,e,t,i)}).on(xs.TrackSubscriptionFailed,(e,t)=>{this.emit(Es.TrackSubscriptionFailed,e,i,t)}).on(xs.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(Es.TrackSubscriptionPermissionChanged,e,t,i)}).on(xs.Active,()=>{this.emitWhenConnected(Es.ParticipantActive,i),i.kind===nt.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Zo(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=js.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ke.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&js.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Es.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===Xa.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Xa.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return nn(this,void 0,void 0,function*(){var t,i,n,s;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Xe({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 tt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Es.SignalConnected),this.emit(Es.Connected),this.setAndEmitConnectionState(Xa.Connected),o.video){const e=new Ka(lo.Kind.Video,new at({source:He.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:qe.AUDIO,name:"video-dummy"}),new Ca(o.useRealTracks&&(null===(t=window.navigator.mediaDevices)||void 0===t?void 0:t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Fo(160*(null!==(i=r.aspectRatios[0])&&void 0!==i?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(xs.LocalTrackPublished,e)}if(o.audio){const e=new Ka(lo.Kind.Audio,new at({source:He.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:qe.AUDIO}),new ua(o.useRealTracks&&(null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Bo(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(xs.LocalTrackPublished,e)}for(let e=0;e<r.count-1;e+=1){let t=new tt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:it.ACTIVE,tracks:[],joinedAt:x.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(r.video){const n=Fo(160*(null!==(s=r.aspectRatios[e%r.aspectRatios.length])&&void 0!==s?s:1),160,!1,!0),o=new at({source:He.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:qe.AUDIO});i.addSubscribedMediaTrack(n,o.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(r.audio){const e=Bo(),n=new at({source:He.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:qe.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==Es.ActiveSpeakersChanged&&e!==Es.TranscriptionReceived){const t=sc(i).filter(e=>void 0!==e);e!==Es.TrackSubscribed&&e!==Es.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function sc(e){return e.map(e=>{if(e)return Array.isArray(e)?sc(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e})}var oc;nc.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(oc||(oc={}));cn.EventEmitter;cn.EventEmitter;function rc(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}new TextEncoder,new TextDecoder;class ac extends Error{constructor(e,t){var i;super(e,t),rc(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}rc(ac,"code","ERR_JOSE_GENERIC");rc(class extends ac{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),rc(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),rc(this,"claim",void 0),rc(this,"reason",void 0),rc(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");rc(class extends ac{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),rc(this,"code","ERR_JWT_EXPIRED"),rc(this,"claim",void 0),rc(this,"reason",void 0),rc(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_EXPIRED");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");rc(class extends ac{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),rc(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");rc(class extends ac{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),rc(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");rc(class extends ac{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),rc(this,Symbol.asyncIterator,void 0),rc(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");rc(class extends ac{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),rc(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");rc(class extends ac{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),rc(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const cc="undefined"!=typeof process&&process.env?.SPEECHOS_HOST||"https://app.speechos.ai",dc={apiKey:"",userId:"",host:cc,debug:!1,webSocketFactory:void 0,fetchHandler:void 0,settingsToken:void 0};let lc={...dc};function uc(){return{...lc}}function hc(e){lc=function(e){if(!e.apiKey)throw new Error("SpeechOS requires an apiKey. Get one from your team dashboard at /a/<team-slug>/.");return{apiKey:e.apiKey,userId:e.userId??dc.userId,host:e.host??dc.host,debug:e.debug??dc.debug,webSocketFactory:e.webSocketFactory??dc.webSocketFactory,fetchHandler:e.fetchHandler??dc.fetchHandler,settingsToken:e.settingsToken??dc.settingsToken}}(e)}function pc(){return lc.settingsToken}const mc="speechos_anonymous_id";const gc=new class{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{const i=this.listeners.get(e);i&&(i.delete(t),0===i.size&&this.listeners.delete(e))}}once(e,t){const i=this.on(e,e=>{i(),t(e)});return i}emit(e,t){const i=this.listeners.get(e);i&&i.forEach(i=>{try{i(t)}catch(t){console.error(`Error in event listener for "${String(e)}":`,t)}})}clear(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){return this.listeners.get(e)?.size??0}},fc={isVisible:!1,isExpanded:!1,isConnected:!1,isMicEnabled:!1,activeAction:null,focusedElement:null,recordingState:"idle",errorMessage:null};const vc=new class{state;subscribers=new Set;snapshot;constructor(e){this.state={...e},this.snapshot=Object.freeze({...this.state})}getState(){return this.snapshot}setState(e){const t=this.snapshot;this.state={...this.state,...e},this.snapshot=Object.freeze({...this.state}),this.subscribers.forEach(e=>{try{e(this.snapshot,t)}catch(e){console.error("Error in state change callback:",e)}}),gc.emit("state:change",{state:this.snapshot})}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}reset(){const e=this.snapshot;this.state={...fc},this.snapshot=Object.freeze({...this.state}),this.subscribers.forEach(t=>{try{t(this.snapshot,e)}catch(e){console.error("Error in state change callback:",e)}}),gc.emit("state:change",{state:this.snapshot})}show(){this.setState({isVisible:!0}),gc.emit("widget:show",void 0)}hide(){this.setState({isVisible:!1,isExpanded:!1,activeAction:null}),gc.emit("widget:hide",void 0)}toggleExpanded(){this.setState({isExpanded:!this.state.isExpanded})}setFocusedElement(e){this.setState({focusedElement:e})}setActiveAction(e){this.setState({activeAction:e})}setRecordingState(e){this.setState({recordingState:e})}setConnected(e){this.setState({isConnected:e})}setMicEnabled(e){this.setState({isMicEnabled:e})}startRecording(){this.setState({recordingState:"connecting",isExpanded:!1})}stopRecording(){this.setState({recordingState:"processing",isMicEnabled:!1})}completeRecording(){this.setState({recordingState:"idle",activeAction:null,isConnected:!1,isMicEnabled:!1,isExpanded:!1})}cancelRecording(){this.setState({recordingState:"idle",activeAction:null,errorMessage:null,isConnected:!1,isMicEnabled:!1})}setError(e){this.setState({recordingState:"error",errorMessage:e})}clearError(){this.setState({recordingState:"idle",errorMessage:null})}}(fc),bc=24e4;var yc=class{promise;_resolve;_reject;_timeoutId=null;_settled=!1;constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}setTimeout(e,t,i,n){this._timeoutId=setTimeout(()=>{this._settled||(console.error(`[SpeechOS] Error: ${t} (${i})`),gc.emit("error",{code:i,message:t,source:n}),this.reject(new Error(t)))},e)}resolve(e){this._settled||(this._settled=!0,this.clearTimeout(),this._resolve(e))}reject(e){this._settled||(this._settled=!0,this.clearTimeout(),this._reject(e))}clearTimeout(){null!==this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=null)}get isSettled(){return this._settled}};const kc=new class{room=null;tokenData=null;micTrack=null;cachedTokenData=null;tokenCacheTimestamp=null;tokenPrefetchPromise=null;tokenRefreshTimer=null;autoRefreshEnabled=!1;pendingTranscript=null;pendingEditText=null;pendingCommand=null;pendingTrackSubscribed=null;editOriginalText=null;sessionSettings={};isCachedTokenValid(){if(!this.cachedTokenData||!this.tokenCacheTimestamp)return!1;return Date.now()-this.tokenCacheTimestamp<bc}async prefetchToken(){const e=uc();return this.isCachedTokenValid()&&this.cachedTokenData?(e.debug&&console.log("[SpeechOS] Using cached token (prefetch hit)"),this.cachedTokenData):this.tokenPrefetchPromise?(e.debug&&console.log("[SpeechOS] Prefetch already in progress, awaiting..."),this.tokenPrefetchPromise):(e.debug&&console.log("[SpeechOS] Starting token prefetch..."),this.tokenPrefetchPromise=this.fetchTokenFromServer().then(e=>(this.cachedTokenData=e,this.tokenCacheTimestamp=Date.now(),this.tokenPrefetchPromise=null,e)).catch(e=>{throw this.tokenPrefetchPromise=null,e}),this.tokenPrefetchPromise)}async fetchToken(){const e=uc();if(this.isCachedTokenValid()&&this.cachedTokenData)return e.debug&&console.log("[SpeechOS] Using cached token"),this.tokenData=this.cachedTokenData,this.cachedTokenData;if(this.tokenPrefetchPromise){e.debug&&console.log("[SpeechOS] Waiting for prefetch to complete...");const t=await this.tokenPrefetchPromise;return this.tokenData=t,t}const t=await this.fetchTokenFromServer();return this.cachedTokenData=t,this.tokenCacheTimestamp=Date.now(),this.tokenData=t,t}async fetchTokenFromServer(){const e=uc(),t=`${e.host}/livekit/api/token/`,i=this.sessionSettings,n=i.inputLanguageCode??"en-US",s=i.outputLanguageCode??"en-US",o=i.smartFormat??!0,r=i.vocabulary??[],a=i.snippets??[];e.debug&&(console.log("[SpeechOS] Fetching LiveKit token from:",t),console.log("[SpeechOS] Session settings:",{inputLanguage:n,outputLanguage:s,smartFormat:o,snippetsCount:a.length,vocabularyCount:r.length}));const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...e.apiKey?{Authorization:`Api-Key ${e.apiKey}`}:{}},body:JSON.stringify({user_id:e.userId||null,input_language:n,output_language:s,smart_format:o,custom_vocabulary:r,custom_snippets:a})});if(!c.ok)throw new Error(`Failed to fetch LiveKit token: ${c.status} ${c.statusText}`);const d=await c.json();return e.debug&&console.log("[SpeechOS] LiveKit token received:",{room:d.room,identity:d.identity,ws_url:d.ws_url}),d}async connect(){const e=uc();if(await this.fetchToken(),!this.tokenData)throw new Error("No token available for LiveKit connection");return this.room=new nc({adaptiveStream:!0,dynacast:!0}),this.setupRoomEvents(),e.debug&&console.log("[SpeechOS] Connecting to LiveKit room:",this.tokenData.room),await this.room.connect(this.tokenData.ws_url,this.tokenData.token),vc.setConnected(!0),e.debug&&console.log("[SpeechOS] Connected to LiveKit room:",this.room.name),this.room}async waitUntilReady(){if(!this.room||"connected"!==this.room.state)throw new Error("Not connected to room");return this.pendingTrackSubscribed||(this.pendingTrackSubscribed=new yc,this.pendingTrackSubscribed.setTimeout(15e3,"Connection timed out - agent not available","connection_timeout","connection")),this.pendingTrackSubscribed.promise}setupRoomEvents(){if(!this.room)return;const e=uc();this.room.on(Es.Connected,()=>{e.debug&&console.log("[SpeechOS] Room connected"),vc.setConnected(!0)}),this.room.on(Es.Disconnected,t=>{e.debug&&console.log("[SpeechOS] Room disconnected:",t),vc.setConnected(!1),vc.setMicEnabled(!1)}),this.room.on(Es.ParticipantConnected,t=>{e.debug&&console.log("[SpeechOS] Participant connected:",t.identity)}),this.room.on(Es.LocalTrackSubscribed,t=>{e.debug&&console.log("[SpeechOS] LocalTrackSubscribed event fired:",t.trackSid),this.pendingTrackSubscribed&&(this.pendingTrackSubscribed.resolve(),this.pendingTrackSubscribed=null)}),this.room.on(Es.LocalTrackPublished,t=>{e.debug&&console.log("[SpeechOS] LocalTrackPublished:",t.trackSid,t.source)}),this.room.on(Es.DataReceived,(e,t)=>{this.handleDataMessage(e,t)})}handleDataMessage(e,t){const i=uc();try{const t=JSON.parse((new TextDecoder).decode(e));if(i.debug&&console.log("[SpeechOS] Data received:",t),"transcript"===t.type){const e=t.transcript||"";i.debug&&console.log("[SpeechOS] Transcript received:",e),gc.emit("transcription:complete",{text:e}),this.pendingTranscript&&(this.pendingTranscript.resolve(e),this.pendingTranscript=null)}else if("edited_text"===t.type){const e=t.text||"";i.debug&&console.log("[SpeechOS] Edited text received:",e),gc.emit("edit:complete",{text:e,originalText:this.editOriginalText||""}),this.pendingEditText&&(this.pendingEditText.resolve(e),this.pendingEditText=null),this.editOriginalText=null}else if("command_result"===t.type){const e=t.command||null;i.debug&&console.log("[SpeechOS] Command result received:",e),gc.emit("command:complete",{command:e}),this.pendingCommand&&(this.pendingCommand.resolve(e),this.pendingCommand=null)}else if("error"===t.type){const e=t,n=e.code||"server_error",s=e.message||"A server error occurred";console.error(`[SpeechOS] Error: ${s} (${n})`),i.debug&&e.details&&console.error("[SpeechOS] Error details:",e.details),gc.emit("error",{code:n,message:s,source:"server"});const o=new Error(s);this.pendingTranscript&&(this.pendingTranscript.reject(o),this.pendingTranscript=null),this.pendingEditText&&(this.pendingEditText.reject(o),this.pendingEditText=null),this.pendingCommand&&(this.pendingCommand.reject(o),this.pendingCommand=null)}}catch(e){console.error("[SpeechOS] Failed to parse data message:",e)}}async enableMicrophone(){if(!this.room||"connected"!==this.room.state)throw new Error("Not connected to room");const e=uc();if(!this.micTrack){e.debug&&console.log("[SpeechOS] Creating microphone track...");const t=this.sessionSettings.audioDeviceId,i={echoCancellation:!0,noiseSuppression:!0};t&&(i.deviceId={exact:t},e.debug&&console.log("[SpeechOS] Using audio device:",t));try{this.micTrack=await Ya(i)}catch(e){if(!(t&&e instanceof Error))throw e;console.warn("[SpeechOS] Selected audio device unavailable, falling back to default:",e.message),this.micTrack=await Ya({echoCancellation:!0,noiseSuppression:!0})}this.logMicrophoneInfo()}this.room.localParticipant.getTrackPublication(lo.Source.Microphone)||(await this.room.localParticipant.publishTrack(this.micTrack,{source:lo.Source.Microphone}),vc.setMicEnabled(!0),e.debug&&console.log("[SpeechOS] Microphone track published"))}logMicrophoneInfo(){if(!this.micTrack)return;const e=uc(),t=this.micTrack.mediaStreamTrack,i=t.getSettings();console.log("[SpeechOS] Microphone active:",{deviceId:i.deviceId||"unknown",label:t.label||"Unknown device",sampleRate:i.sampleRate,channelCount:i.channelCount,echoCancellation:i.echoCancellation,noiseSuppression:i.noiseSuppression}),e.debug&&console.log("[SpeechOS] Full audio track settings:",i)}async disableMicrophone(){const e=uc();if(this.micTrack){if(e.debug&&console.log("[SpeechOS] Disabling microphone track..."),"connected"===this.room?.state)try{await this.room.localParticipant.unpublishTrack(this.micTrack),e.debug&&console.log("[SpeechOS] Microphone track unpublished")}catch(e){console.warn("[SpeechOS] Error unpublishing track:",e)}this.micTrack.stop(),this.micTrack.detach(),this.micTrack=null,vc.setMicEnabled(!1),e.debug&&console.log("[SpeechOS] Microphone track stopped and detached")}}async sendDataMessage(e){if(!this.room||"connected"!==this.room.state)throw new Error("Not connected to room");const t=(new TextEncoder).encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0,topic:"speechos"})}async startVoiceSession(e){const t=uc();if(t.debug&&console.log("[SpeechOS] Starting voice session..."),this.sessionSettings=e?.settings||{},await this.fetchToken(),!this.tokenData)throw new Error("No token available for LiveKit connection");this.pendingTrackSubscribed=new yc,this.pendingTrackSubscribed.setTimeout(15e3,"Connection timed out - agent not available","connection_timeout","connection"),this.room=new nc({adaptiveStream:!0,dynacast:!0}),this.setupRoomEvents(),t.debug&&console.log("[SpeechOS] Connecting to LiveKit room:",this.tokenData.room,"at",this.tokenData.ws_url),await this.room.connect(this.tokenData.ws_url,this.tokenData.token),t.debug&&console.log("[SpeechOS] Connected, enabling microphone with preConnectBuffer..."),await this.enableMicrophoneWithPreConnectBuffer(),e?.onMicReady&&e.onMicReady(),vc.setConnected(!0),t.debug&&console.log("[SpeechOS] Voice session ready - microphone active"),this.waitForAgentSubscription()}waitForAgentSubscription(){const e=uc();this.pendingTrackSubscribed&&this.pendingTrackSubscribed.promise.then(()=>{e.debug&&console.log("[SpeechOS] Agent subscribed to audio track - full duplex established"),this.pendingTrackSubscribed=null}).catch(e=>{console.warn("[SpeechOS] Agent subscription timeout:",e.message),this.pendingTrackSubscribed=null})}async enableMicrophoneWithPreConnectBuffer(){if(!this.room)throw new Error("Room not initialized");const e=uc(),t=this.sessionSettings.audioDeviceId,i={echoCancellation:!0,noiseSuppression:!0};t&&(i.deviceId={exact:t},e.debug&&console.log("[SpeechOS] Using audio device:",t));try{await this.room.localParticipant.setMicrophoneEnabled(!0,i,{preConnectBuffer:!0}),vc.setMicEnabled(!0);const t=this.room.localParticipant.getTrackPublication(lo.Source.Microphone);t?.track&&(this.micTrack=t.track,this.logMicrophoneInfo()),e.debug&&console.log("[SpeechOS] Microphone enabled with pre-connect buffer - audio is being captured")}catch(e){if(!(t&&e instanceof Error))throw e;console.warn("[SpeechOS] Selected audio device unavailable, falling back to default:",e.message),await this.room.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0},{preConnectBuffer:!0}),vc.setMicEnabled(!0)}}async stopVoiceSession(){const e=uc(),t=this.sessionSettings,i=t.inputLanguageCode??"en-US",n=t.outputLanguageCode??"en-US";console.log("[SpeechOS] Dictate command:",{inputLanguage:i,outputLanguage:n}),e.debug&&console.log("[SpeechOS] Stopping voice session, requesting transcript..."),await this.disableMicrophone(),e.debug&&console.log("[SpeechOS] Requesting transcript from agent..."),this.pendingTranscript=new yc,this.pendingTranscript.setTimeout(1e4,"Transcription timed out. Please try again.","transcription_timeout","timeout"),await this.sendDataMessage({type:"request_transcript"});const s=await this.pendingTranscript.promise;return this.pendingTranscript=null,s}async stopAndGetTranscript(){return this.stopVoiceSession()}async requestEditText(e){const t=uc(),i=this.sessionSettings,n=i.inputLanguageCode??"en-US",s=i.outputLanguageCode??"en-US";console.log("[SpeechOS] Edit command:",{inputLanguage:n,outputLanguage:s,originalTextLength:e.length}),t.debug&&console.log("[SpeechOS] Requesting text edit..."),this.editOriginalText=e,await this.disableMicrophone(),t.debug&&console.log("[SpeechOS] Sending edit_text request to agent..."),this.pendingEditText=new yc,this.pendingEditText.setTimeout(15e3,"Edit request timed out. Please try again.","edit_timeout","timeout"),await this.sendDataMessage({type:"edit_text",text:e});const o=await this.pendingEditText.promise;return this.pendingEditText=null,o}async stopAndEdit(e){return this.requestEditText(e)}async requestCommand(e){const t=uc(),i=this.sessionSettings.inputLanguageCode??"en-US";console.log("[SpeechOS] Command request:",{inputLanguage:i,commandCount:e.length}),t.debug&&console.log("[SpeechOS] Requesting command match..."),await this.disableMicrophone(),t.debug&&console.log("[SpeechOS] Sending execute_command request to agent..."),this.pendingCommand=new yc,this.pendingCommand.setTimeout(15e3,"Command request timed out. Please try again.","command_timeout","timeout"),await this.sendDataMessage({type:"execute_command",commands:e});const n=await this.pendingCommand.promise;return this.pendingCommand=null,n}async stopAndCommand(e){return this.requestCommand(e)}async disconnect(){const e=uc();e.debug&&console.log("[SpeechOS] Disconnecting from room..."),await this.disableMicrophone(),this.room&&(this.room.removeAllListeners(),await this.room.disconnect(),this.room=null,vc.setConnected(!1),e.debug&&console.log("[SpeechOS] Room disconnected and cleaned up")),this.pendingTranscript&&(this.pendingTranscript.reject(new Error("Disconnected")),this.pendingTranscript=null),this.pendingEditText&&(this.pendingEditText.reject(new Error("Disconnected")),this.pendingEditText=null),this.pendingCommand&&(this.pendingCommand.reject(new Error("Disconnected")),this.pendingCommand=null),this.pendingTrackSubscribed&&(this.pendingTrackSubscribed.reject(new Error("Disconnected")),this.pendingTrackSubscribed=null),this.tokenData=null,this.editOriginalText=null,this.sessionSettings={},e.debug&&console.log("[SpeechOS] Session state cleared")}invalidateTokenCache(){uc().debug&&console.log("[SpeechOS] Token cache invalidated"),this.cachedTokenData=null,this.tokenCacheTimestamp=null}startAutoRefresh(){const e=uc();this.autoRefreshEnabled=!0,e.debug&&console.log("[SpeechOS] Token auto-refresh enabled"),this.invalidateTokenCache(),this.prefetchToken().then(()=>{this.scheduleTokenRefresh()}).catch(t=>{e.debug&&console.warn("[SpeechOS] Failed to prefetch token after command:",t),this.autoRefreshEnabled&&(this.tokenRefreshTimer=setTimeout(()=>{this.performAutoRefresh()},5e3))})}stopAutoRefresh(){const e=uc();this.autoRefreshEnabled=!1,this.tokenRefreshTimer&&(clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null),e.debug&&console.log("[SpeechOS] Token auto-refresh disabled")}scheduleTokenRefresh(){if(!this.autoRefreshEnabled)return;this.tokenRefreshTimer&&(clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null);const e=uc();let t;if(this.tokenCacheTimestamp){const e=Date.now()-this.tokenCacheTimestamp,i=bc-e;t=Math.max(0,i-3e4)}else t=0;e.debug&&console.log(`[SpeechOS] Scheduling token refresh in ${Math.round(t/1e3)}s`),this.tokenRefreshTimer=setTimeout(()=>{this.performAutoRefresh()},t)}async performAutoRefresh(){if(!this.autoRefreshEnabled)return;const e=uc();if(this.isCachedTokenValid())return e.debug&&console.log("[SpeechOS] Token still valid on refresh check, rescheduling"),void this.scheduleTokenRefresh();e.debug&&console.log("[SpeechOS] Auto-refreshing token...");try{const t=await this.fetchTokenFromServer();this.cachedTokenData=t,this.tokenCacheTimestamp=Date.now(),e.debug&&console.log("[SpeechOS] Token auto-refreshed successfully"),this.scheduleTokenRefresh()}catch(e){console.warn("[SpeechOS] Token auto-refresh failed:",e),this.autoRefreshEnabled&&(this.tokenRefreshTimer=setTimeout(()=>{this.performAutoRefresh()},3e4))}}getRoom(){return this.room}getTokenData(){return this.tokenData}isConnected(){return"connected"===this.room?.state}isMicrophoneEnabled(){return null!==this.micTrack}};function Sc(){const e=navigator.userAgent.toLowerCase(),t=navigator.vendor?.toLowerCase()||"",i=e.includes("safari")&&!e.includes("chrome")&&!e.includes("chromium"),n=t.includes("apple");return i&&n}function Tc(){return Sc()?MediaRecorder.isTypeSupported("audio/mp4")?{mimeType:"audio/mp4",format:"mp4",needsEncodingParams:!1}:{mimeType:"",format:"mp4",needsEncodingParams:!0}:MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?{mimeType:"audio/webm;codecs=opus",format:"webm",needsEncodingParams:!1}:MediaRecorder.isTypeSupported("audio/webm")?{mimeType:"audio/webm",format:"webm",needsEncodingParams:!1}:MediaRecorder.isTypeSupported("audio/mp4")?{mimeType:"audio/mp4",format:"mp4",needsEncodingParams:!1}:{mimeType:"",format:"webm",needsEncodingParams:!0}}gc.on("settings:changed",()=>{kc.invalidateTokenCache()});var Cc=class e{mediaStream=null;recorder=null;buffer=[];isReady=!1;isRecording=!1;onChunk;audioFormat;deviceId;static TIME_SLICE_MS=100;static SAFARI_TIME_SLICE_MS=1e3;constructor(e,t){this.onChunk=e,this.audioFormat=Tc(),this.deviceId=t}getTimeSlice(){return Sc()?e.SAFARI_TIME_SLICE_MS:e.TIME_SLICE_MS}getTimeSliceMs(){return this.getTimeSlice()}getFormat(){return this.audioFormat}async start(){const e=uc();if(this.isRecording)return void(e.debug&&console.log("[SpeechOS] AudioCapture already recording"));this.buffer=[],this.isReady=!1;const t={audio:{echoCancellation:!0,noiseSuppression:!0,...this.deviceId?{deviceId:{exact:this.deviceId}}:{}}};e.debug&&(console.log("[SpeechOS] AudioCapture starting with format:",this.audioFormat.mimeType),console.log("[SpeechOS] Detected Safari:",Sc()),this.deviceId&&console.log("[SpeechOS] Using audio device:",this.deviceId));try{this.mediaStream=await navigator.mediaDevices.getUserMedia(t);const i={};this.audioFormat.mimeType&&(i.mimeType=this.audioFormat.mimeType),this.recorder=new MediaRecorder(this.mediaStream,i),this.recorder.ondataavailable=e=>{e.data&&e.data.size>0&&this.handleChunk(e.data)},this.recorder.onerror=e=>{console.error("[SpeechOS] MediaRecorder error:",e)};const n=this.getTimeSlice();this.recorder.start(n),this.isRecording=!0,e.debug&&console.log(`[SpeechOS] AudioCapture started with ${n}ms timeslice, buffering until ready`)}catch(e){if(!(this.deviceId&&e instanceof Error))throw e;{console.warn("[SpeechOS] Selected device unavailable, trying default:",e.message),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});const t={};this.audioFormat.mimeType&&(t.mimeType=this.audioFormat.mimeType),this.recorder=new MediaRecorder(this.mediaStream,t),this.recorder.ondataavailable=e=>{e.data&&e.data.size>0&&this.handleChunk(e.data)},this.recorder.start(this.getTimeSlice()),this.isRecording=!0}}}handleChunk(e){this.isReady?this.onChunk(e):this.buffer.push(e)}setReady(){const e=uc();if(this.isReady)return;const t=this.buffer;this.buffer=[];for(const e of t)this.onChunk(e);this.isReady=!0,e.debug&&console.log(`[SpeechOS] AudioCapture ready, flushed ${t.length} buffered chunks`)}async stop(){const e=uc(),t=Sc();if(this.recorder&&"inactive"!==this.recorder.state){if("recording"===this.recorder.state)try{const t=new Promise(t=>{const i=n=>{this.recorder?.removeEventListener("dataavailable",i),e.debug&&console.log(`[SpeechOS] requestData flush received: ${n.data.size} bytes`),t()};this.recorder?.addEventListener("dataavailable",i)});this.recorder.requestData(),e.debug&&console.log("[SpeechOS] Requested data flush before stop"),await t}catch(t){e.debug&&console.log("[SpeechOS] requestData() not supported or failed:",t)}const i=new Promise(t=>{this.recorder?this.recorder.onstop=()=>{e.debug&&console.log("[SpeechOS] MediaRecorder onstop fired"),t()}:t()});this.recorder.stop(),await i,t&&(e.debug&&console.log("[SpeechOS] Safari: waiting 2s for encoding pipeline to flush"),await new Promise(e=>setTimeout(e,2e3)))}if(this.mediaStream){for(const e of this.mediaStream.getTracks())e.stop();this.mediaStream=null}this.recorder=null,this.isRecording=!1,this.isReady=!1,this.buffer=[],e.debug&&console.log("[SpeechOS] AudioCapture stopped")}get recording(){return this.isRecording}get ready(){return this.isReady}get bufferedChunks(){return this.buffer.length}};const wc=15e3;var Ec=class{promise;_resolve;_reject;_timeoutId=null;_settled=!1;constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}setTimeout(e,t,i,n){this._timeoutId=setTimeout(()=>{this._settled||(console.error(`[SpeechOS] Error: ${t} (${i})`),gc.emit("error",{code:i,message:t,source:n}),this.reject(new Error(t)))},e)}resolve(e){this._settled||(this._settled=!0,this.clearTimeout(),this._resolve(e))}reject(e){this._settled||(this._settled=!0,this.clearTimeout(),this._reject(e))}clearTimeout(){null!==this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=null)}get isSettled(){return this._settled}};const xc=new class{ws=null;audioCapture=null;sessionId=null;pendingAuth=null;pendingTranscript=null;pendingEditText=null;pendingCommand=null;pendingAudioSends=new Set;editOriginalText=null;lastInputText=void 0;sessionAction="dictate";sessionInputText="";sessionCommands=[];sessionSettings={};getWebSocketUrl(){return`${(uc().host||"https://app.speechos.ai").replace(/^http/,"ws")}/ws/voice/`}async startVoiceSession(e){const t=uc();var i,n;this.sessionAction=e?.action||"dictate",this.sessionInputText=e?.inputText||"",this.sessionCommands=e?.commands||[],this.sessionSettings=e?.settings||{},"edit"===this.sessionAction&&(this.editOriginalText=this.sessionInputText),t.debug&&console.log("[SpeechOS] Starting WebSocket voice session..."),this.audioCapture=(i=e=>{this.sendAudioChunk(e)},n=this.sessionSettings.audioDeviceId,new Cc(i,n)),await this.audioCapture.start(),e?.onMicReady&&e.onMicReady(),vc.setMicEnabled(!0);const s=this.getWebSocketUrl();t.debug&&console.log("[SpeechOS] Connecting to WebSocket:",s),this.pendingAuth=new Ec,this.pendingAuth.setTimeout(wc,"Connection timed out","connection_timeout","connection");const o=t.webSocketFactory??(e=>new WebSocket(e));this.ws=o(s),this.ws.onopen=()=>{t.debug&&console.log("[SpeechOS] WebSocket connected, authenticating..."),this.authenticate()},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onerror=e=>{const t=3===this.ws?.readyState,i=t?"connection_blocked":"websocket_error",n=t?"This site's CSP blocks the extension. Try embedded mode instead.":"WebSocket connection error";console.error("[SpeechOS] WebSocket error:",e,{isConnectionBlocked:t}),gc.emit("error",{code:i,message:n,source:"connection"}),this.pendingAuth&&this.pendingAuth.reject(new Error(n))},this.ws.onclose=e=>{t.debug&&console.log("[SpeechOS] WebSocket closed:",e.code,e.reason),vc.setConnected(!1)},await this.pendingAuth.promise,this.pendingAuth=null,this.audioCapture&&this.audioCapture.setReady(),vc.setConnected(!0),t.debug&&console.log("[SpeechOS] WebSocket voice session ready")}authenticate(){const e=uc(),t=Tc(),i=this.sessionSettings,n=function(){if("undefined"==typeof localStorage)return crypto.randomUUID();let e=localStorage.getItem(mc);return e||(e=crypto.randomUUID(),localStorage.setItem(mc,e)),e}(),s={type:"auth",api_key:e.apiKey,user_id:e.userId||null,anonymous_id:n,input_language:i.inputLanguageCode??"en-US",output_language:i.outputLanguageCode??"en-US",smart_format:i.smartFormat??!0,custom_vocabulary:i.vocabulary??[],custom_snippets:i.snippets??[],audio_format:t.format,action:this.sessionAction,input_text:this.sessionInputText,commands:this.sessionCommands};e.debug&&console.log("[SpeechOS] Sending auth message with action:",this.sessionAction),this.ws?.send(JSON.stringify(s))}sendAudioChunk(e){const t=this.doSendAudioChunk(e);this.pendingAudioSends.add(t),t.finally(()=>{this.pendingAudioSends.delete(t)})}async doSendAudioChunk(e){if(this.ws&&1===this.ws.readyState){const t=await e.arrayBuffer();this.ws.send(t)}}handleMessage(e){const t=uc();try{const i=JSON.parse(e);switch(t.debug&&console.log("[SpeechOS] WebSocket message:",i),i.type){case"ready":this.handleReady(i);break;case"transcription":this.handleIntermediateTranscription(i);break;case"transcript":this.handleFinalTranscript(i);break;case"edited_text":this.handleEditedText(i);break;case"command_result":this.handleCommandResult(i);break;case"error":this.handleError(i);break;default:t.debug&&console.log("[SpeechOS] Unknown message type:",i.type)}}catch(e){console.error("[SpeechOS] Failed to parse message:",e)}}handleReady(e){const t=uc();this.sessionId=e.session_id,t.debug&&console.log("[SpeechOS] Session ready:",this.sessionId),this.pendingAuth&&this.pendingAuth.resolve()}handleIntermediateTranscription(e){const t=uc();gc.emit("transcription:interim",{transcript:e.transcript,isFinal:e.is_final}),t.debug&&console.log("[SpeechOS] Intermediate transcription:",e.transcript,"final:",e.is_final)}handleFinalTranscript(e){const t=e.transcript||"";gc.emit("transcription:complete",{text:t}),this.pendingTranscript&&(this.pendingTranscript.resolve(t),this.pendingTranscript=null)}handleEditedText(e){const t=e.text||"";gc.emit("edit:complete",{text:t,originalText:this.editOriginalText||""}),this.pendingEditText&&(this.pendingEditText.resolve(t),this.pendingEditText=null),this.editOriginalText=null}handleCommandResult(e){const t=e.command||null;this.lastInputText=e.transcript,gc.emit("command:complete",{command:t}),this.pendingCommand&&(this.pendingCommand.resolve(t),this.pendingCommand=null)}handleError(e){const t=e.code||"server_error",i=e.message||"A server error occurred";console.error(`[SpeechOS] Error: ${i} (${t})`),gc.emit("error",{code:t,message:i,source:"server"});const n=new Error(i);this.pendingAuth&&(this.pendingAuth.reject(n),this.pendingAuth=null),this.pendingTranscript&&(this.pendingTranscript.reject(n),this.pendingTranscript=null),this.pendingEditText&&(this.pendingEditText.reject(n),this.pendingEditText=null),this.pendingCommand&&(this.pendingCommand.reject(n),this.pendingCommand=null)}async stopVoiceSession(){uc().debug&&console.log("[SpeechOS] Stopping voice session, requesting transcript..."),await this.stopAudioCapture(),this.pendingTranscript=new Ec,this.pendingTranscript.setTimeout(wc,"Transcription timed out. Please try again.","transcription_timeout","timeout"),this.sendMessage({type:"request_transcript"});const e=await this.pendingTranscript.promise;return this.pendingTranscript=null,e}async requestEditText(e){uc().debug&&console.log("[SpeechOS] Requesting text edit..."),await this.stopAudioCapture(),this.pendingEditText=new Ec,this.pendingEditText.setTimeout(wc,"Edit request timed out. Please try again.","edit_timeout","timeout"),this.sendMessage({type:"edit_text"});const t=await this.pendingEditText.promise;return this.pendingEditText=null,t}async requestCommand(e){uc().debug&&console.log("[SpeechOS] Requesting command match..."),await this.stopAudioCapture(),this.pendingCommand=new Ec,this.pendingCommand.setTimeout(wc,"Command request timed out. Please try again.","command_timeout","timeout"),this.sendMessage({type:"execute_command"});const t=await this.pendingCommand.promise;return this.pendingCommand=null,t}async stopAudioCapture(){const e=uc(),t=Date.now();e.debug&&console.log("[SpeechOS] stopAudioCapture: starting..."),this.audioCapture&&(await this.audioCapture.stop(),this.audioCapture=null,e.debug&&console.log(`[SpeechOS] stopAudioCapture: recorder stopped after ${Date.now()-t}ms`)),vc.setMicEnabled(!1),this.pendingAudioSends.size>0?(e.debug&&console.log(`[SpeechOS] stopAudioCapture: waiting for ${this.pendingAudioSends.size} pending audio sends...`),await Promise.all(this.pendingAudioSends),e.debug&&console.log(`[SpeechOS] stopAudioCapture: all sends complete after ${Date.now()-t}ms`)):e.debug&&console.log("[SpeechOS] stopAudioCapture: no pending sends"),await this.waitForBufferDrain(),e.debug&&console.log(`[SpeechOS] stopAudioCapture: complete after ${Date.now()-t}ms`)}async waitForBufferDrain(){if(!this.ws||1!==this.ws.readyState)return;const e=uc(),t=Date.now();for(;this.ws.bufferedAmount>0;){if(Date.now()-t>5e3){console.warn(`[SpeechOS] Buffer drain timeout, ${this.ws.bufferedAmount} bytes still pending`);break}await new Promise(e=>setTimeout(e,50))}e.debug&&console.log(`[SpeechOS] Buffer drained in ${Date.now()-t}ms`)}sendMessage(e){this.ws&&1===this.ws.readyState&&this.ws.send(JSON.stringify(e))}async disconnect(){const e=uc();e.debug&&console.log("[SpeechOS] Disconnecting WebSocket..."),await this.stopAudioCapture(),this.ws&&(this.ws.close(),this.ws=null);const t=new Error("Disconnected");this.pendingAuth&&(this.pendingAuth.reject(t),this.pendingAuth=null),this.pendingTranscript&&(this.pendingTranscript.reject(t),this.pendingTranscript=null),this.pendingEditText&&(this.pendingEditText.reject(t),this.pendingEditText=null),this.pendingCommand&&(this.pendingCommand.reject(t),this.pendingCommand=null),this.sessionId=null,this.editOriginalText=null,this.lastInputText=void 0,this.sessionSettings={},vc.setConnected(!1),vc.setMicEnabled(!1),e.debug&&console.log("[SpeechOS] WebSocket disconnected")}isConnected(){return null!==this.ws&&1===this.ws.readyState}getLastInputText(){return this.lastInputText}},Rc={startVoiceSession:e=>xc.startVoiceSession(e),stopVoiceSession:()=>xc.stopVoiceSession(),requestEditText:e=>xc.requestEditText(e),requestCommand:e=>xc.requestCommand(e),disconnect:()=>xc.disconnect(),isConnected:()=>xc.isConnected(),getLastInputText:()=>xc.getLastInputText(),prefetchToken:()=>Promise.resolve({}),startAutoRefresh:()=>{},stopAutoRefresh:()=>{},invalidateTokenCache:()=>{}};function Pc(){return Rc}const Ic={commands:[],zIndex:999999,alwaysVisible:!1};let Oc={...Ic};function Ac(e){Oc=function(e){const t={commands:e.commands??Ic.commands,zIndex:e.zIndex??Ic.zIndex,alwaysVisible:e.alwaysVisible??Ic.alwaysVisible};return("number"!=typeof t.zIndex||t.zIndex<0)&&(console.warn(`Invalid zIndex "${t.zIndex}". Using default ${Ic.zIndex}.`),t.zIndex=Ic.zIndex),t}(e)}function _c(){return{...Oc}}function Mc(){Oc={...Ic}}function Dc(){return Oc.alwaysVisible}function Nc(e){if(!(e&&e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();if("input"===t||"textarea"===t){if("input"===t){const t=e.type.toLowerCase();if(["checkbox","radio","submit","button","reset","file","hidden"].includes(t))return!1}return!0}return!(!e.isContentEditable&&"true"!==e.getAttribute("contenteditable"))}class Lc{constructor(){this.isActive=!1,this.focusHandler=null,this.blurHandler=null,this.touchHandler=null,this.mouseDownHandler=null,this.isWidgetBeingInteracted=!1}start(){if(this.isActive)return void console.warn("FormDetector is already active");this.focusHandler=e=>{const t=e.target;Nc(t)&&(console.log("[SpeechOS] FormDetector: focus on form field",{element:t,tagName:t?.tagName}),vc.setFocusedElement(t),vc.show(),gc.emit("form:focus",{element:t}))},this.blurHandler=e=>{if(Nc(e.target)){if(this.isWidgetBeingInteracted)return void console.log("[SpeechOS] blurHandler: widget being interacted, skipping");const t=e.relatedTarget,i=document.querySelector("speechos-widget"),n=Nc(t),s=i&&(i.contains(t)||i.shadowRoot?.contains(t)||t===i),o=Boolean(t?.closest("[data-speechos-no-close]"));if(n||s||o)return void console.log("[SpeechOS] blurHandler: early return, not hiding");setTimeout(()=>{if(this.isWidgetBeingInteracted)return;const e=document.activeElement,t=i&&(i.contains(e)||i.shadowRoot?.contains(e)),n=Boolean(e?.closest("[data-speechos-no-close]"));Nc(e)||t||n||(vc.setFocusedElement(null),Dc()||vc.hide(),gc.emit("form:blur",{element:null}))},150)}};const e=(e,t)=>{const i=document.querySelector("speechos-widget");return i&&(t.includes(i)||i.contains(e)||i.shadowRoot?.contains(e))||!1};this.touchHandler=t=>{const i=t.target,n=t.composedPath?t.composedPath():[];e(i,n)&&(this.isWidgetBeingInteracted=!0,setTimeout(()=>{this.isWidgetBeingInteracted=!1},300))},this.mouseDownHandler=t=>{const i=t.target,n=t.composedPath?t.composedPath():[];e(i,n)&&(this.isWidgetBeingInteracted=!0,setTimeout(()=>{this.isWidgetBeingInteracted=!1},300))},document.addEventListener("focusin",this.focusHandler,!0),document.addEventListener("focusout",this.blurHandler,!0),document.addEventListener("touchstart",this.touchHandler,!0),document.addEventListener("mousedown",this.mouseDownHandler,!0),this.isActive=!0}stop(){this.isActive&&(this.focusHandler&&(document.removeEventListener("focusin",this.focusHandler,!0),this.focusHandler=null),this.blurHandler&&(document.removeEventListener("focusout",this.blurHandler,!0),this.blurHandler=null),this.touchHandler&&(document.removeEventListener("touchstart",this.touchHandler,!0),this.touchHandler=null),this.mouseDownHandler&&(document.removeEventListener("mousedown",this.mouseDownHandler,!0),this.mouseDownHandler=null),this.isWidgetBeingInteracted=!1,vc.setFocusedElement(null),Dc()||vc.hide(),this.isActive=!1)}get active(){return this.isActive}}const Uc=new Lc;function Fc(e){if("textarea"===e.tagName.toLowerCase())return!0;return["text","search","url","tel","password"].includes(e.type||"text")}class jc{getSelection(e){const t=e.tagName.toLowerCase();if("input"===t||"textarea"===t){const t=e;if(Fc(t)){const e=t.selectionStart,i=t.selectionEnd;return{start:e,end:i,text:null!==e&&null!==i&&e!==i?t.value.substring(e,i):""}}{const e=t.value.length;return{start:e,end:e,text:""}}}if(e.isContentEditable){const e=window.getSelection();if(e&&e.rangeCount>0){const t=e.toString();return{start:0,end:t.length,text:t}}return{start:null,end:null,text:""}}return{start:null,end:null,text:""}}getContent(e,t){const i=e.tagName.toLowerCase();if("input"===i||"textarea"===i){const i=e.value;if(t){const e=t.start??0,n=t.end??i.length;if(e!==n)return i.substring(e,n)}return i}if(e.isContentEditable){const t=window.getSelection();return t&&t.toString().length>0?t.toString():e.textContent||""}return""}insertText(e,t,i){const n=e.tagName.toLowerCase();if("input"===n||"textarea"===n){const n=e,s=i?.start??n.value.length,o=i?.end??n.value.length,r=n.value.substring(0,s),a=n.value.substring(o);if(n.value=r+t+a,Fc(n)){const e=s+t.length;n.setSelectionRange(e,e)}n.dispatchEvent(new Event("input",{bubbles:!0})),n.focus(),vc.setFocusedElement(n)}else if(e.isContentEditable){e.focus(),vc.setFocusedElement(e);const i=document.createTextNode(t);e.appendChild(i);const n=window.getSelection();if(n){const e=document.createRange();e.selectNodeContents(i),e.collapse(!1),n.removeAllRanges(),n.addRange(e)}e.dispatchEvent(new Event("input",{bubbles:!0}))}gc.emit("transcription:inserted",{text:t,element:e})}replaceContent(e,t,i){const n=e.tagName.toLowerCase();if("input"===n||"textarea"===n){const n=e;if(n.focus(),Fc(n)){const e=i?.start??0,s=i?.end??n.value.length;e!==s?n.setSelectionRange(e,s):n.setSelectionRange(0,n.value.length),document.execCommand("insertText",!1,t)}else n.value=t,n.dispatchEvent(new Event("input",{bubbles:!0}));vc.setFocusedElement(n)}else if(e.isContentEditable){e.focus(),vc.setFocusedElement(e);if(!(null!==i?.start&&null!==i?.end&&i?.start!==i?.end)){const t=window.getSelection(),i=document.createRange();i.selectNodeContents(e),t?.removeAllRanges(),t?.addRange(i)}document.execCommand("insertText",!1,t)}}}const Bc=new jc;let $c=Bc;function Vc(e){$c=e}function qc(){$c=Bc}const Hc="speechos_language_settings";let zc=null;const Wc=[{name:"Bulgarian",code:"bg",variants:["bg"]},{name:"Catalan",code:"ca",variants:["ca"]},{name:"Chinese",code:"zh",variants:["zh"]},{name:"Czech",code:"cs",variants:["cs"]},{name:"Danish",code:"da",variants:["da","da-DK"]},{name:"Dutch",code:"nl",variants:["nl"]},{name:"English (Australia)",code:"en-AU",variants:["en-AU"]},{name:"English (India)",code:"en-IN",variants:["en-IN"]},{name:"English (New Zealand)",code:"en-NZ",variants:["en-NZ"]},{name:"English (UK)",code:"en-GB",variants:["en-GB"]},{name:"English (US)",code:"en-US",variants:["en","en-US"]},{name:"Estonian",code:"et",variants:["et"]},{name:"Finnish",code:"fi",variants:["fi"]},{name:"Flemish",code:"nl-BE",variants:["nl-BE"]},{name:"French",code:"fr",variants:["fr","fr-CA"]},{name:"German",code:"de",variants:["de"]},{name:"German (Switzerland)",code:"de-CH",variants:["de-CH"]},{name:"Greek",code:"el",variants:["el"]},{name:"Hindi",code:"hi",variants:["hi"]},{name:"Hungarian",code:"hu",variants:["hu"]},{name:"Indonesian",code:"id",variants:["id"]},{name:"Italian",code:"it",variants:["it"]},{name:"Japanese",code:"ja",variants:["ja"]},{name:"Korean",code:"ko",variants:["ko","ko-KR"]},{name:"Latvian",code:"lv",variants:["lv"]},{name:"Lithuanian",code:"lt",variants:["lt"]},{name:"Malay",code:"ms",variants:["ms"]},{name:"Norwegian",code:"no",variants:["no"]},{name:"Polish",code:"pl",variants:["pl"]},{name:"Portuguese",code:"pt",variants:["pt","pt-BR","pt-PT"]},{name:"Romanian",code:"ro",variants:["ro"]},{name:"Russian",code:"ru",variants:["ru"]},{name:"Slovak",code:"sk",variants:["sk"]},{name:"Spanish",code:"es",variants:["es","es-419"]},{name:"Swedish",code:"sv",variants:["sv","sv-SE"]},{name:"Turkish",code:"tr",variants:["tr"]},{name:"Ukrainian",code:"uk",variants:["uk"]},{name:"Vietnamese",code:"vi",variants:["vi"]}],Gc={inputLanguageCode:"en-US",outputLanguageCode:"en-US",smartFormat:!0};function Kc(){if(null!==zc)return{...zc};try{const e=localStorage.getItem(Hc);return e?{...Gc,...JSON.parse(e)}:{...Gc}}catch{return{...Gc}}}function Jc(e){zc={...Gc,...e}}function Yc(e){zc=e;try{localStorage.setItem(Hc,JSON.stringify(e))}catch{}}function Qc(){return Kc().inputLanguageCode}function Xc(e){const t=Kc();t.inputLanguageCode!==e&&(t.inputLanguageCode=e,Yc(t),gc.emit("settings:changed",{setting:"language"}))}function Zc(){return Kc().outputLanguageCode}function ed(e){const t=Kc();t.outputLanguageCode!==e&&(t.outputLanguageCode=e,Yc(t),gc.emit("settings:changed",{setting:"language"}))}function td(e){return Wc.find(t=>t.code===e||t.variants.includes(e))}function id(){const e=td(Qc());return e?.name||"English"}function nd(){const e=td(Zc());return e?.name||"English"}function sd(){return Kc().smartFormat}function od(e){const t=Kc();t.smartFormat!==e&&(t.smartFormat=e,Yc(t),gc.emit("settings:changed",{setting:"smartFormat"}))}function rd(){return Qc()}function ad(e){Xc(e)}function cd(){return id()}function dd(){zc=null;try{localStorage.removeItem(Hc)}catch{}}const ld={getLanguageSettings:Kc,setLanguageSettings:Jc,getInputLanguageCode:Qc,setInputLanguageCode:Xc,getOutputLanguageCode:Zc,setOutputLanguageCode:ed,getLanguageByCode:td,getInputLanguageName:id,getOutputLanguageName:nd,getSmartFormatEnabled:sd,setSmartFormatEnabled:od,resetLanguageSettings:dd,resetMemoryCache:function(){zc=null},SUPPORTED_LANGUAGES:Wc,getLanguageCode:rd,setLanguageCode:ad,getLanguageName:cd},ud="speechos_snippets",hd=25;let pd=null;function md(){if(null!==pd)return[...pd].sort((e,t)=>t.createdAt-e.createdAt);try{const e=localStorage.getItem(ud);if(!e)return[];return JSON.parse(e).sort((e,t)=>t.createdAt-e.createdAt)}catch{return[]}}function gd(e){pd=e.slice(0,hd)}function fd(e){pd=e;try{localStorage.setItem(ud,JSON.stringify(e))}catch{}}function vd(e,t,i){const n=e.trim();if(!n)return{field:"trigger",message:"Trigger phrase is required."};if(n.length>30)return{field:"trigger",message:"Trigger must be 30 characters or less."};const s=t.find(e=>e.trigger.toLowerCase()===n.toLowerCase()&&e.id!==i);return s?{field:"trigger",message:"This trigger phrase already exists."}:null}function bd(e){const t=e.trim();return t?t.length>300?{field:"expansion",message:"Expansion must be 300 characters or less."}:null:{field:"expansion",message:"Expansion text is required."}}function yd(e,t){const i=md();if(i.length>=hd)return{success:!1,error:{field:"limit",message:"You've reached the 25 snippet limit. Delete unused snippets to add more."}};const n=vd(e,i);if(n)return{success:!1,error:n};const s=bd(t);if(s)return{success:!1,error:s};const o={id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,trigger:e.trim(),expansion:t.trim(),createdAt:Date.now()};return i.unshift(o),fd(i),gc.emit("settings:changed",{setting:"snippets"}),{success:!0,snippet:o}}function kd(e,t,i){const n=md(),s=n.findIndex(t=>t.id===e);if(-1===s)return{success:!1,error:{field:"trigger",message:"Snippet not found."}};const o=vd(t,n,e);if(o)return{success:!1,error:o};const r=bd(i);return r?{success:!1,error:r}:(n[s]={...n[s],trigger:t.trim(),expansion:i.trim()},fd(n),gc.emit("settings:changed",{setting:"snippets"}),{success:!0,snippet:n[s]})}function Sd(e){const t=md().filter(t=>t.id!==e);fd(t),gc.emit("settings:changed",{setting:"snippets"})}function Td(){pd=[];try{localStorage.removeItem(ud)}catch{}gc.emit("settings:changed",{setting:"snippets"})}function Cd(){return{current:md().length,max:hd}}function wd(){return md().length>=hd}const Ed={getSnippets:md,setSnippets:gd,addSnippet:yd,updateSnippet:kd,deleteSnippet:Sd,clearSnippets:Td,getSnippetCount:Cd,isAtSnippetLimit:wd,resetMemoryCache:function(){pd=null},MAX_SNIPPETS:hd,MAX_TRIGGER_LENGTH:30,MAX_EXPANSION_LENGTH:300},xd="speechos_vocabulary",Rd=50;let Pd=null;function Id(){if(null!==Pd)return[...Pd].sort((e,t)=>t.createdAt-e.createdAt);try{const e=localStorage.getItem(xd);if(!e)return[];return JSON.parse(e).sort((e,t)=>t.createdAt-e.createdAt)}catch{return[]}}function Od(e){Pd=e.slice(0,Rd)}function Ad(e){Pd=e;try{localStorage.setItem(xd,JSON.stringify(e))}catch{}}function _d(e){const t=Id();if(t.length>=Rd)return{success:!1,error:{field:"limit",message:"You've reached the 50 term limit. Remove unused terms to add more."}};const i=function(e,t){const i=e.trim();if(!i)return{field:"term",message:"Term is required."};if(i.length>50)return{field:"term",message:"Term must be 50 characters or less."};const n=t.find(e=>e.term.toLowerCase()===i.toLowerCase());return n?{field:"term",message:"This term is already in your vocabulary."}:null}(e,t);if(i)return{success:!1,error:i};const n={id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,term:e.trim(),createdAt:Date.now()};return t.unshift(n),Ad(t),gc.emit("settings:changed",{setting:"vocabulary"}),{success:!0,term:n}}function Md(e){const t=Id().filter(t=>t.id!==e);Ad(t),gc.emit("settings:changed",{setting:"vocabulary"})}function Dd(){Pd=[];try{localStorage.removeItem(xd)}catch{}gc.emit("settings:changed",{setting:"vocabulary"})}function Nd(){return{current:Id().length,max:Rd}}function Ld(){return Id().length>=Rd}const Ud={getVocabulary:Id,setVocabulary:Od,addTerm:_d,deleteTerm:Md,clearVocabulary:Dd,getVocabularyCount:Nd,isAtVocabularyLimit:Ld,resetMemoryCache:function(){Pd=null},MAX_TERMS:Rd,MAX_TERM_LENGTH:50},Fd="speechos_audio_settings",jd={deviceId:""};function Bd(){try{const e=localStorage.getItem(Fd);return e?{...jd,...JSON.parse(e)}:{...jd}}catch{return{...jd}}}function $d(){return Bd().deviceId}function Vd(e){const t=Bd();t.deviceId=e,function(e){try{localStorage.setItem(Fd,JSON.stringify(e))}catch{}}(t)}async function qd(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(e=>"audioinput"===e.kind)}catch{return[]}}async function Hd(){const e=$d();if(!e)return!0;return(await qd()).some(t=>t.deviceId===e)}function zd(){try{localStorage.removeItem(Fd)}catch{}}const Wd={getAudioSettings:Bd,getAudioDeviceId:$d,setAudioDeviceId:Vd,getAudioInputDevices:qd,isSelectedDeviceAvailable:Hd,resetAudioSettings:zd},Gd="speechos_transcripts";let Kd=null;function Jd(){if(null!==Kd)return[...Kd].sort((e,t)=>t.timestamp-e.timestamp);try{const e=localStorage.getItem(Gd);if(!e)return[];return JSON.parse(e).sort((e,t)=>t.timestamp-e.timestamp)}catch{return[]}}function Yd(e){Kd=e.slice(0,50)}function Qd(e,t,i){const n={id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,text:e,timestamp:Date.now(),action:t};if("edit"===t&&"string"==typeof i&&(n.originalText=i),"command"===t&&"object"==typeof i){const e=i;void 0!==e.inputText&&(n.inputText=e.inputText),void 0!==e.commandResult&&(n.commandResult=e.commandResult),void 0!==e.commandConfig&&(n.commandConfig=e.commandConfig)}const s=Jd();s.unshift(n);const o=s.slice(0,50);Kd=o;try{localStorage.setItem(Gd,JSON.stringify(o))}catch{}return gc.emit("settings:changed",{setting:"history"}),n}function Xd(){Kd=[];try{localStorage.removeItem(Gd)}catch{}gc.emit("settings:changed",{setting:"history"})}function Zd(e){const t=Jd().filter(t=>t.id!==e);Kd=t;try{localStorage.setItem(Gd,JSON.stringify(t))}catch{}gc.emit("settings:changed",{setting:"history"})}const el={getTranscripts:Jd,setTranscripts:Yd,saveTranscript:Qd,clearTranscripts:Xd,deleteTranscript:Zd};const tl=new class{constructor(){this.syncTimer=null,this.isSyncing=!1,this.retryCount=0,this.isInitialized=!1,this.unsubscribe=null,this.syncDisabled=!1}async doFetch(e,t){const i=uc(),n=lc.fetchHandler;if(n)return i.debug&&console.log("[SpeechOS] Using custom fetch handler (extension proxy)",t.method,e),n(e,t);i.debug&&console.log("[SpeechOS] Using native fetch",t.method,e);return await fetch(e,t)}async init(){pc()&&(this.isInitialized||(this.isInitialized=!0,this.unsubscribe=gc.on("settings:changed",()=>{this.scheduleSyncToServer()}),await this.loadFromServer()))}destroy(){this.syncTimer&&(clearTimeout(this.syncTimer),this.syncTimer=null),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.isInitialized=!1,this.retryCount=0,this.syncDisabled=!1}async loadFromServer(){const e=pc();if(!e)return;const t=uc();try{const i=await this.doFetch(`${t.host}/api/user-settings/`,{method:"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(t.debug&&console.log("[SpeechOS] Settings fetch response:",i.status,i.ok?"OK":i.statusText),404===i.status)return t.debug&&console.log("[SpeechOS] No server settings found, syncing local to server"),void await this.syncToServer();if(401===i.status||403===i.status)return void this.handleTokenExpired();if(!i.ok)throw new Error(`Server returned ${i.status}`);const n=await i.json();t.debug&&(console.log("[SpeechOS] Settings received from server:",{language:n.language,vocabularyCount:n.vocabulary?.length??0,snippetsCount:n.snippets?.length??0,historyCount:n.history?.length??0,lastSyncedAt:n.lastSyncedAt}),n.history?.length>0&&console.log("[SpeechOS] History entries:",n.history)),this.mergeSettings(n),gc.emit("settings:loaded",void 0),t.debug&&console.log("[SpeechOS] Settings merged and loaded")}catch(e){const i=e instanceof Error?e.message:"Unknown error";this.isNetworkRestrictionError(e)?(this.syncDisabled=!0,t.debug&&console.log("[SpeechOS] Settings sync disabled (CSP/network restriction), using localStorage only")):t.debug&&console.warn("[SpeechOS] Failed to load settings from server:",i),gc.emit("settings:syncFailed",{error:i})}}mergeSettings(e){e.language&&Jc(e.language),e.vocabulary&&Od(e.vocabulary),e.snippets&&gd(e.snippets),e.history&&Yd(e.history)}scheduleSyncToServer(){pc()&&!this.syncDisabled&&(this.syncTimer&&clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this.syncToServer()},2e3))}async syncToServer(){const e=pc();if(!e||this.isSyncing||this.syncDisabled)return;this.isSyncing=!0;const t=uc();try{const i=Kc(),n=Id(),s=md(),o=Jd(),r={language:{inputLanguageCode:i.inputLanguageCode,outputLanguageCode:i.outputLanguageCode,smartFormat:i.smartFormat},vocabulary:n.map(e=>({id:e.id,term:e.term,createdAt:e.createdAt})),snippets:s.map(e=>({id:e.id,trigger:e.trigger,expansion:e.expansion,createdAt:e.createdAt})),history:o.map(e=>({id:e.id,text:e.text,timestamp:e.timestamp,action:e.action,...e.originalText&&{originalText:e.originalText},...e.inputText&&{inputText:e.inputText},...void 0!==e.commandResult&&{commandResult:e.commandResult}}))},a=await this.doFetch(`${t.host}/api/user-settings/`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(401===a.status||403===a.status)return void this.handleTokenExpired();if(!a.ok)throw new Error(`Server returned ${a.status}`);this.retryCount=0,gc.emit("settings:synced",void 0),t.debug&&console.log("[SpeechOS] Settings synced to server")}catch(e){const i=e instanceof Error?e.message:"Unknown error";this.isNetworkRestrictionError(e)?(this.syncDisabled=!0,t.debug&&console.log("[SpeechOS] Settings sync disabled (CSP/network restriction), using localStorage only"),gc.emit("settings:syncFailed",{error:i})):(t.debug&&console.warn("[SpeechOS] Failed to sync settings to server:",i),gc.emit("settings:syncFailed",{error:i}),this.scheduleRetry())}finally{this.isSyncing=!1}}scheduleRetry(){if(this.retryCount>=3){return uc().debug&&console.warn("[SpeechOS] Max retries reached, giving up sync"),void(this.retryCount=0)}this.retryCount++;const e=2e3*Math.pow(2,this.retryCount-1);this.syncTimer=setTimeout(()=>{this.syncToServer()},e)}isNetworkRestrictionError(e){if(e instanceof TypeError){const t=e.message.toLowerCase();return t.includes("failed to fetch")||t.includes("network request failed")||t.includes("content security policy")||t.includes("csp")||t.includes("blocked")}return!1}handleTokenExpired(){lc={...lc,settingsToken:void 0},gc.emit("settings:tokenExpired",void 0);uc().debug&&console.warn("[SpeechOS] Settings token expired")}isEnabled(){return!!pc()}};function il(e,t,i,n){var s,o=arguments.length,r=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(s=e[a])&&(r=(o<3?s(r):o>3?s(t,i,r):s(t,i))||r);return o>3&&r&&Object.defineProperty(t,i,r),r}"function"==typeof SuppressedError&&SuppressedError;const nl=globalThis,sl=nl.ShadowRoot&&(void 0===nl.ShadyCSS||nl.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ol=Symbol(),rl=new WeakMap;let al=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==ol)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(sl&&void 0===e){const i=void 0!==t&&1===t.length;i&&(e=rl.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&rl.set(t,e))}return e}toString(){return this.cssText}};const cl=(e,...t)=>{const i=1===e.length?e[0]:t.reduce((t,i,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[n+1],e[0]);return new al(i,e,ol)},dl=sl?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return(e=>new al("string"==typeof e?e:e+"",void 0,ol))(t)})(e):e,{is:ll,defineProperty:ul,getOwnPropertyDescriptor:hl,getOwnPropertyNames:pl,getOwnPropertySymbols:ml,getPrototypeOf:gl}=Object,fl=globalThis,vl=fl.trustedTypes,bl=vl?vl.emptyScript:"",yl=fl.reactiveElementPolyfillSupport,kl=(e,t)=>e,Sl={toAttribute(e,t){switch(t){case Boolean:e=e?bl:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch(e){i=null}}return i}},Tl=(e,t)=>!ll(e,t),Cl={attribute:!0,type:String,converter:Sl,reflect:!1,useDefault:!1,hasChanged:Tl};Symbol.metadata??=Symbol("metadata"),fl.litPropertyMetadata??=new WeakMap;let wl=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Cl){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(e,i,t);void 0!==n&&ul(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){const{get:n,set:s}=hl(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const o=n?.call(this);s?.call(this,t),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Cl}static _$Ei(){if(this.hasOwnProperty(kl("elementProperties")))return;const e=gl(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(kl("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(kl("properties"))){const e=this.properties,t=[...pl(e),...ml(e)];for(const i of t)this.createProperty(i,e[i])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const i=this._$Eu(e,t);void 0!==i&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const e of i)t.unshift(dl(e))}else void 0!==e&&t.push(dl(e));return t}static _$Eu(e,t){const i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(sl)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const i of t){const t=document.createElement("style"),n=nl.litNonce;void 0!==n&&t.setAttribute("nonce",n),t.textContent=i.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){const i=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,i);if(void 0!==n&&!0===i.reflect){const s=(void 0!==i.converter?.toAttribute?i.converter:Sl).toAttribute(t,i.type);this._$Em=e,null==s?this.removeAttribute(n):this.setAttribute(n,s),this._$Em=null}}_$AK(e,t){const i=this.constructor,n=i._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=i.getPropertyOptions(n),s="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:Sl;this._$Em=n;const o=s.fromAttribute(t,e.type);this[n]=o??this._$Ej?.get(n)??o,this._$Em=null}}requestUpdate(e,t,i,n=!1,s){if(void 0!==e){const o=this.constructor;if(!1===n&&(s=this[e]),i??=o.getPropertyOptions(e),!((i.hasChanged??Tl)(s,t)||i.useDefault&&i.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(o._$Eu(e,i))))return;this.C(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:n,wrapped:s},o){i&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,o??t??this[e]),!0!==s||void 0!==o)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,i]of e){const{wrapped:e}=i,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,i,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};wl.elementStyles=[],wl.shadowRootOptions={mode:"open"},wl[kl("elementProperties")]=new Map,wl[kl("finalized")]=new Map,yl?.({ReactiveElement:wl}),(fl.reactiveElementVersions??=[]).push("2.1.2");const El=globalThis,xl=e=>e,Rl=El.trustedTypes,Pl=Rl?Rl.createPolicy("lit-html",{createHTML:e=>e}):void 0,Il="$lit$",Ol=`lit$${Math.random().toFixed(9).slice(2)}$`,Al="?"+Ol,_l=`<${Al}>`,Ml=document,Dl=()=>Ml.createComment(""),Nl=e=>null===e||"object"!=typeof e&&"function"!=typeof e,Ll=Array.isArray,Ul="[ \t\n\f\r]",Fl=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,jl=/-->/g,Bl=/>/g,$l=RegExp(`>|${Ul}(?:([^\\s"'>=/]+)(${Ul}*=${Ul}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),Vl=/'/g,ql=/"/g,Hl=/^(?:script|style|textarea|title)$/i,zl=(e=>(t,...i)=>({_$litType$:e,strings:t,values:i}))(1),Wl=Symbol.for("lit-noChange"),Gl=Symbol.for("lit-nothing"),Kl=new WeakMap,Jl=Ml.createTreeWalker(Ml,129);function Yl(e,t){if(!Ll(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==Pl?Pl.createHTML(t):t}const Ql=(e,t)=>{const i=e.length-1,n=[];let s,o=2===t?"<svg>":3===t?"<math>":"",r=Fl;for(let t=0;t<i;t++){const i=e[t];let a,c,d=-1,l=0;for(;l<i.length&&(r.lastIndex=l,c=r.exec(i),null!==c);)l=r.lastIndex,r===Fl?"!--"===c[1]?r=jl:void 0!==c[1]?r=Bl:void 0!==c[2]?(Hl.test(c[2])&&(s=RegExp("</"+c[2],"g")),r=$l):void 0!==c[3]&&(r=$l):r===$l?">"===c[0]?(r=s??Fl,d=-1):void 0===c[1]?d=-2:(d=r.lastIndex-c[2].length,a=c[1],r=void 0===c[3]?$l:'"'===c[3]?ql:Vl):r===ql||r===Vl?r=$l:r===jl||r===Bl?r=Fl:(r=$l,s=void 0);const u=r===$l&&e[t+1].startsWith("/>")?" ":"";o+=r===Fl?i+_l:d>=0?(n.push(a),i.slice(0,d)+Il+i.slice(d)+Ol+u):i+Ol+(-2===d?t:u)}return[Yl(e,o+(e[i]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),n]};class Xl{constructor({strings:e,_$litType$:t},i){let n;this.parts=[];let s=0,o=0;const r=e.length-1,a=this.parts,[c,d]=Ql(e,t);if(this.el=Xl.createElement(c,i),Jl.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(n=Jl.nextNode())&&a.length<r;){if(1===n.nodeType){if(n.hasAttributes())for(const e of n.getAttributeNames())if(e.endsWith(Il)){const t=d[o++],i=n.getAttribute(e).split(Ol),r=/([.?@])?(.*)/.exec(t);a.push({type:1,index:s,name:r[2],strings:i,ctor:"."===r[1]?nu:"?"===r[1]?su:"@"===r[1]?ou:iu}),n.removeAttribute(e)}else e.startsWith(Ol)&&(a.push({type:6,index:s}),n.removeAttribute(e));if(Hl.test(n.tagName)){const e=n.textContent.split(Ol),t=e.length-1;if(t>0){n.textContent=Rl?Rl.emptyScript:"";for(let i=0;i<t;i++)n.append(e[i],Dl()),Jl.nextNode(),a.push({type:2,index:++s});n.append(e[t],Dl())}}}else if(8===n.nodeType)if(n.data===Al)a.push({type:2,index:s});else{let e=-1;for(;-1!==(e=n.data.indexOf(Ol,e+1));)a.push({type:7,index:s}),e+=Ol.length-1}s++}}static createElement(e,t){const i=Ml.createElement("template");return i.innerHTML=e,i}}function Zl(e,t,i=e,n){if(t===Wl)return t;let s=void 0!==n?i._$Co?.[n]:i._$Cl;const o=Nl(t)?void 0:t._$litDirective$;return s?.constructor!==o&&(s?._$AO?.(!1),void 0===o?s=void 0:(s=new o(e),s._$AT(e,i,n)),void 0!==n?(i._$Co??=[])[n]=s:i._$Cl=s),void 0!==s&&(t=Zl(e,s._$AS(e,t.values),s,n)),t}class eu{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,n=(e?.creationScope??Ml).importNode(t,!0);Jl.currentNode=n;let s=Jl.nextNode(),o=0,r=0,a=i[0];for(;void 0!==a;){if(o===a.index){let t;2===a.type?t=new tu(s,s.nextSibling,this,e):1===a.type?t=new a.ctor(s,a.name,a.strings,this,e):6===a.type&&(t=new ru(s,this,e)),this._$AV.push(t),a=i[++r]}o!==a?.index&&(s=Jl.nextNode(),o++)}return Jl.currentNode=Ml,n}p(e){let t=0;for(const i of this._$AV)void 0!==i&&(void 0!==i.strings?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class tu{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,i,n){this.type=2,this._$AH=Gl,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=n,this._$Cv=n?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Zl(this,e,t),Nl(e)?e===Gl||null==e||""===e?(this._$AH!==Gl&&this._$AR(),this._$AH=Gl):e!==this._$AH&&e!==Wl&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>Ll(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==Gl&&Nl(this._$AH)?this._$AA.nextSibling.data=e:this.T(Ml.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:i}=e,n="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=Xl.createElement(Yl(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new eu(n,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=Kl.get(e.strings);return void 0===t&&Kl.set(e.strings,t=new Xl(e)),t}k(e){Ll(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,n=0;for(const s of e)n===t.length?t.push(i=new tu(this.O(Dl()),this.O(Dl()),this,this.options)):i=t[n],i._$AI(s),n++;n<t.length&&(this._$AR(i&&i._$AB.nextSibling,n),t.length=n)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){const t=xl(e).nextSibling;xl(e).remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}}class iu{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,n,s){this.type=1,this._$AH=Gl,this._$AN=void 0,this.element=e,this.name=t,this._$AM=n,this.options=s,i.length>2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Gl}_$AI(e,t=this,i,n){const s=this.strings;let o=!1;if(void 0===s)e=Zl(this,e,t,0),o=!Nl(e)||e!==this._$AH&&e!==Wl,o&&(this._$AH=e);else{const n=e;let r,a;for(e=s[0],r=0;r<s.length-1;r++)a=Zl(this,n[i+r],t,r),a===Wl&&(a=this._$AH[r]),o||=!Nl(a)||a!==this._$AH[r],a===Gl?e=Gl:e!==Gl&&(e+=(a??"")+s[r+1]),this._$AH[r]=a}o&&!n&&this.j(e)}j(e){e===Gl?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class nu extends iu{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Gl?void 0:e}}class su extends iu{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Gl)}}class ou extends iu{constructor(e,t,i,n,s){super(e,t,i,n,s),this.type=5}_$AI(e,t=this){if((e=Zl(this,e,t,0)??Gl)===Wl)return;const i=this._$AH,n=e===Gl&&i!==Gl||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,s=e!==Gl&&(i===Gl||n);n&&this.element.removeEventListener(this.name,this,i),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}}class ru{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){Zl(this,e)}}const au=El.litHtmlPolyfillSupport;au?.(Xl,tu),(El.litHtmlVersions??=[]).push("3.3.2");const cu=globalThis;let du=class extends wl{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,i)=>{const n=i?.renderBefore??t;let s=n._$litPart$;if(void 0===s){const e=i?.renderBefore??null;n._$litPart$=s=new tu(t.insertBefore(Dl(),e),e,void 0,i??{})}return s._$AI(e),s})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Wl}};du._$litElement$=!0,du.finalized=!0,cu.litElementHydrateSupport?.({LitElement:du});const lu=cu.litElementPolyfillSupport;lu?.({LitElement:du}),(cu.litElementVersions??=[]).push("4.2.2");const uu=e=>(t,i)=>{void 0!==i?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)},hu={attribute:!0,type:String,converter:Sl,reflect:!1,hasChanged:Tl},pu=(e=hu,t,i)=>{const{kind:n,metadata:s}=i;let o=globalThis.litPropertyMetadata.get(s);if(void 0===o&&globalThis.litPropertyMetadata.set(s,o=new Map),"setter"===n&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),"accessor"===n){const{name:n}=i;return{set(i){const s=t.get.call(this);t.set.call(this,i),this.requestUpdate(n,s,e,!0,i)},init(t){return void 0!==t&&this.C(n,void 0,e,t),t}}}if("setter"===n){const{name:n}=i;return function(i){const s=this[n];t.call(this,i),this.requestUpdate(n,s,e,!0,i)}}throw Error("Unsupported decorator location: "+n)};function mu(e){return(t,i)=>"object"==typeof i?pu(e,t,i):((e,t,i)=>{const n=t.hasOwnProperty(i);return t.constructor.createProperty(i,e),n?Object.getOwnPropertyDescriptor(t,i):void 0})(e,t,i)}function gu(e){return mu({...e,state:!0,attribute:!1})}const fu=cl`
1
+ !function(e){"use strict";function t(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(e)}var i=Object.defineProperty,n=(e,t,n)=>((e,t,n)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);let s=class{constructor(){n(this,"_locking"),n(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}};function o(e,t){if(!e)throw new Error(t)}function r(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function a(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function c(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const d=Symbol("@bufbuild/protobuf/enum-type");function l(e){const t=e[d];return o(t,"missing enum type on enum object"),t}function u(e,t,i,n){e[d]=h(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function h(e,t,i){const n=Object.create(null),s=Object.create(null),o=[];for(const e of t){const t=m(e);o.push(t),n[e.name]=t,s[e.no]=t}return{typeName:e,values:o,findName:e=>n[e],findNumber:e=>s[e]}}function p(e,t,i){const n={};for(const e of t){const t=m(e);n[t.localName]=t.no,n[t.no]=t.localName}return u(n,e,t),n}function m(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class g{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function f(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function v(e,t,i){for(let n=0;n<28;n+=7){const s=e>>>n,o=!(s>>>7==0&&0==t),r=255&(o?128|s:s);if(i.push(r),!o)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),o=255&(s?128|n:n);if(i.push(o),!s)return}i.push(t>>>31&1)}}const b=4294967296;function y(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function o(t,o){const r=Number(e.slice(t,o));s*=i,n=n*i+r,n>=b&&(s+=n/b|0,n%=b)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?T(n,s):S(n,s)}function k(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(b*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,o=i+8147497*n,r=2*n;const a=1e7;return s>=a&&(o+=Math.floor(s/a),s%=a),o>=a&&(r+=Math.floor(o/a),o%=a),r.toString()+C(o)+C(s)}function S(e,t){return{lo:0|e,hi:0|t}}function T(e,t){return t=~t,e?e=1+~e:t+=1,S(e,t)}const C=e=>{const t=String(e);return"0000000".slice(t.length)+t};function w(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function E(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const x=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>o(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>o(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),y(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),y(e)),dec:(e,t)=>function(e,t){let i=S(e,t);const n=2147483648&i.hi;n&&(i=T(i.lo,i.hi));const s=k(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>k(e,t)}}();var R,P,I;function O(e,t,i){if(t===i)return!0;if(e==R.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case R.UINT64:case R.FIXED64:case R.INT64:case R.SFIXED64:case R.SINT64:return t==i}return!1}function A(e,t){switch(e){case R.BOOL:return!1;case R.UINT64:case R.FIXED64:case R.INT64:case R.SFIXED64:case R.SINT64:return 0==t?x.zero:"0";case R.DOUBLE:case R.FLOAT:return 0;case R.BYTES:return new Uint8Array(0);case R.STRING:return"";default:return 0}}function _(e,t){switch(e){case R.BOOL:return!1===t;case R.STRING:return""===t;case R.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(R||(R={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(P||(P={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(I||(I={}));class M{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(a(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return r(e),w(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){c(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){a(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){r(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return r(e),w(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=x.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=x.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=x.enc(e);return v(t.lo,t.hi,this.buf),this}sint64(e){let t=x.enc(e),i=t.hi>>31;return v(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=x.uEnc(e);return v(t.lo,t.hi,this.buf),this}}class D{constructor(e,t){this.varint64=f,this.uint32=E,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case I.Varint:for(;128&this.buf[this.pos++];);break;case I.Bit64:this.pos+=4;case I.Bit32:this.pos+=4;break;case I.LengthDelimited:let i=this.uint32();this.pos+=i;break;case I.StartGroup:for(;;){const[e,i]=this.tag();if(i===I.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return x.dec(...this.varint64())}uint64(){return x.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,x.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return x.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return x.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function N(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return A(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let L="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),U=[];for(let e=0;e<L.length;e++)U[L[e].charCodeAt(0)]=e;U["-".charCodeAt(0)]=L.indexOf("+"),U["_".charCodeAt(0)]=L.indexOf("/");const F={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,o=0,r=0;for(let t=0;t<e.length;t++){if(i=U[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":o=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(o){case 0:r=i,o=1;break;case 1:n[s++]=r<<2|(48&i)>>4,r=i,o=2;break;case 2:n[s++]=(15&r)<<4|(60&i)>>2,r=i,o=3;break;case 3:n[s++]=(3&r)<<6|i,o=0}}if(1==o)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let o=0;o<e.length;o++)switch(t=e[o],n){case 0:i+=L[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=L[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=L[s|t>>6],i+=L[63&t],n=0}return n&&(i+=L[s],i+="=",1==n&&(i+="=")),i}};function j(e,t,i){V(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[o,r]=N(t);for(const e of s)t.runtime.bin.readField(o,n.readerFactory(e.data),t.field,e.wireType,n);return r()}function B(e,t,i,n){V(t,e);const s=t.runtime.bin.makeReadOptions(n),o=t.runtime.bin.makeWriteOptions(n);if($(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const r=o.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,r,o);const c=s.readerFactory(r.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function $(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function V(e,t){o(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function q(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!_(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function H(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?A(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function z(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(g.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function W(e,t){return z(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}R.DOUBLE,R.FLOAT,R.INT64,R.UINT64,R.INT32,R.UINT32,R.BOOL,R.STRING,R.BYTES;const G={ignoreUnknownFields:!1},K={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function J(e){return e?Object.assign(Object.assign({},G),e):G}function Y(e){return e?Object.assign(Object.assign({},K),e):K}const Q=Symbol(),X=Symbol();function Z(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function ee(e,t,i,n,s){let r=i.localName;if(i.repeated){if(o("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(t)));const a=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=ne(i.T,e,n.ignoreUnknownFields,!0);t!==X&&a.push(t);break;case"scalar":try{a.push(ie(i.T,e,i.L,!0))}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)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Z(t)));const o=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let a;try{a=te(i.K,e)}catch(e){let n="cannot decode map key for 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)}switch(i.V.kind){case"message":o[a]=i.V.T.fromJson(r,n);break;case"enum":const e=ne(i.V.T,r,n.ignoreUnknownFields,!0);e!==X&&(o[a]=e);break;case"scalar":try{o[a]=ie(i.V.T,r,P.BIGINT,!0)}catch(e){let n="cannot decode map value for 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 switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const o=i.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let a=e[r];z(a)?a.fromJson(t,n):(e[r]=a=o.fromJson(t,n),o.fieldWrapper&&!i.oneof&&(e[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=ne(i.T,t,n.ignoreUnknownFields,!1);switch(c){case Q:H(i,e);break;case X:break;default:e[r]=c}break;case"scalar":try{const n=ie(i.T,t,i.L,!1);if(n===Q)H(i,e);else e[r]=n}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)}}}function te(e,t){if(e===R.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return ie(e,t,P.BIGINT,!0).toString()}function ie(e,t,i,n){if(null===t)return n?A(e,i):Q;switch(e){case R.DOUBLE:case R.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==R.FLOAT&&c(n),n;case R.INT32:case R.FIXED32:case R.SFIXED32:case R.SINT32:case R.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==R.UINT32||e==R.FIXED32?a(s):r(s),s;case R.INT64:case R.SFIXED64:case R.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=x.parse(t);return i?o.toString():o;case R.FIXED64:case R.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const d=x.uParse(t);return i?d.toString():d;case R.BOOL:if("boolean"!=typeof t)break;return t;case R.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case R.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return F.dec(t)}throw new Error}function ne(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Q;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return X}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Z(t)))}function se(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function oe(e,t,i){if("map"==e.kind){o("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,i]of s)n[t.toString()]=ae(e.V.T,i);break;case"message":for(const[e,t]of s)n[e.toString()]=t.toJson(i);break;case"enum":const t=e.V.T;for(const[e,o]of s)n[e.toString()]=re(t,o,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){o(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(ae(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(re(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return ae(e.T,t);case"enum":return re(e.T,t,i.enumAsInteger);case"message":return W(e.T,t).toJson(i)}}function re(e,t,i){var n;if(o("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function ae(e,t){switch(e){case R.INT32:case R.SFIXED32:case R.SINT32:case R.FIXED32:case R.UINT32:return o("number"==typeof t),t;case R.FLOAT:case R.DOUBLE:return o("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case R.STRING:return o("string"==typeof t),t;case R.BOOL:return o("boolean"==typeof t),t;case R.UINT64:case R.FIXED64:case R.INT64:case R.SFIXED64:case R.SINT64:return o("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case R.BYTES:return o(t instanceof Uint8Array),F.enc(t)}}const ce=Symbol("@bufbuild/protobuf/unknown-fields"),de={readUnknownFields:!0,readerFactory:e=>new D(e)},le={writeUnknownFields:!0,writerFactory:()=>new M};function ue(e){return e?Object.assign(Object.assign({},de),e):de}function he(e){return e?Object.assign(Object.assign({},le),e):le}function pe(e,t,i,n,s){let{repeated:o,localName:r}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=r&&delete e.value,e.case=r,r="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?R.INT32:i.T;let c=fe;if("scalar"==i.kind&&i.L>0&&(c=ge),o){let i=e[r];if(n==I.LengthDelimited&&a!=R.STRING&&a!=R.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[r]=c(t,a);break;case"message":const d=i.T;o?e[r].push(me(t,new d,s,i)):z(e[r])?me(t,e[r],s,i):(e[r]=me(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[r]=d.fieldWrapper.unwrapField(e[r])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let o,r;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:o=fe(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=fe(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=me(t,new e.V.T,i,void 0)}}}void 0===o&&(o=A(e.K,P.BIGINT));"string"!=typeof o&&"number"!=typeof o&&(o=o.toString());if(void 0===r)switch(e.V.kind){case"scalar":r=A(e.V.T,P.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[o,r]}(i,t,s);e[r][l]=u}}function me(e,t,i,n){const s=t.getType().runtime.bin,o=null==n?void 0:n.delimited;return s.readMessage(t,e,o?n.no:e.uint32(),i,o),t}function ge(e,t){const i=fe(e,t);return"bigint"==typeof i?i.toString():i}function fe(e,t){switch(t){case R.STRING:return e.string();case R.BOOL:return e.bool();case R.DOUBLE:return e.double();case R.FLOAT:return e.float();case R.INT32:return e.int32();case R.INT64:return e.int64();case R.UINT64:return e.uint64();case R.FIXED64:return e.fixed64();case R.BYTES:return e.bytes();case R.FIXED32:return e.fixed32();case R.SFIXED32:return e.sfixed32();case R.SFIXED64:return e.sfixed64();case R.SINT64:return e.sint64();case R.UINT32:return e.uint32();case R.SINT32:return e.sint32()}}function ve(e,t,i,n){o(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?R.INT32:e.T;if(s)if(o(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,I.LengthDelimited).fork();let[,s]=Se(t);for(let t=0;t<n.length;t++)e[s](n[t]);e.join()}(i,r,e.no,t);else for(const n of t)ke(i,r,e.no,n);else ke(i,r,e.no,t);break;case"message":if(s){o(Array.isArray(t));for(const s of t)ye(i,n,e,s)}else ye(i,n,e,t);break;case"map":o("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))be(i,n,e,s,o)}}function be(e,t,i,n,s){e.tag(i.no,I.LengthDelimited),e.fork();let r=n;switch(i.K){case R.INT32:case R.FIXED32:case R.UINT32:case R.SFIXED32:case R.SINT32:r=Number.parseInt(n);break;case R.BOOL:o("true"==n||"false"==n),r="true"==n}switch(ke(e,i.K,1,r),i.V.kind){case"scalar":ke(e,i.V.T,2,s);break;case"enum":ke(e,R.INT32,2,s);break;case"message":o(void 0!==s),e.tag(2,I.LengthDelimited).bytes(s.toBinary(t))}e.join()}function ye(e,t,i,n){const s=W(i.T,n);i.delimited?e.tag(i.no,I.StartGroup).raw(s.toBinary(t)).tag(i.no,I.EndGroup):e.tag(i.no,I.LengthDelimited).bytes(s.toBinary(t))}function ke(e,t,i,n){o(void 0!==n);let[s,r]=Se(t);e.tag(i,s)[r](n)}function Se(e){let t=I.Varint;switch(e){case R.BYTES:case R.STRING:t=I.LengthDelimited;break;case R.DOUBLE:case R.FIXED64:case R.SFIXED64:t=I.Bit64;break;case R.FIXED32:case R.SFIXED32:case R.FLOAT:t=I.Bit32}return[t,R[e].toLowerCase()]}function Te(e){if(void 0===e)return e;if(z(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ce(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class we{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Ee(e,t){const i=Re(e);return t?i:_e(Ae(i))}const xe=Re;function Re(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const Pe=new Set(["constructor","toString","toJSON","valueOf"]),Ie=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Oe=e=>"".concat(e,"$"),Ae=e=>Ie.has(e)?Oe(e):e,_e=e=>Pe.has(e)?Oe(e):e;class Me{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Ee(e,!1)}addField(e){o(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const De=(Ne=e=>new we(e,e=>function(e){var t,i,n,s,o,r;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Ee(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:xe(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:P.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(o=d.req)&&void 0!==o&&o,e.opt=null!==(r=d.opt)&&void 0!==r&&r,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=R.BYTES&&d.T!=R.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Me(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e)),Le=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=A(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:J,makeWriteOptions:Y,readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Z(t)));n=null!=n?n:new e;const s=new Map,o=i.typeRegistry;for(const[r,a]of Object.entries(t)){const t=e.fields.findJsonName(r);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(r,'"'));s.set(t.oneof,r)}ee(n,a,t,i,e)}else{let t=!1;if((null==o?void 0:o.findExtension)&&r.startsWith("[")&&r.endsWith("]")){const s=o.findExtension(r.substring(1,r.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,o]=N(s);ee(e,a,s.field,i,s),B(n,s,o(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(r,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!q(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!se(s))continue}const i=oe(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const o=t.typeRegistry;if(null==o?void 0:o.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const r=o.findExtensionFor(i.typeName,s.no);if(r&&$(e,r)){const i=j(e,r,t),s=oe(r.field,i,t);void 0!==s&&(n[r.field.jsonName]=s)}}}catch(e){const t=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),n=e instanceof Error?e.message:String(e);throw new Error(t+(n.length>0?": ".concat(n):""))}return n},readScalar:(e,t,i)=>ie(e,t,null!=i?i:P.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||_(e,t)?ae(e,t):void 0},debug:Z},bin:{makeReadOptions:ue,makeWriteOptions:he,listUnknownFields(e){var t;return null!==(t=e[ce])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[ce]},writeUnknownFields(e,t){const i=e[ce];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[ce])||(s[ce]=[]),s[ce].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const o=e.getType(),r=s?t.len:t.pos+i;let a,c;for(;t.pos<r&&([a,c]=t.tag(),!0!==s||c!=I.EndGroup);){const i=o.fields.find(a);if(!i){const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i);continue}pe(e,t,i,c,n)}if(s&&(c!=I.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:pe,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(q(s,e))ve(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&ve(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:u,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,o=e;if(null!=o[i])switch(n.kind){case"oneof":const e=o[i].case;if(void 0===e)continue;const t=n.findField(e);let r=o[i].value;t&&"message"==t.kind&&!z(r,t.T)?r=new t.T(r):t&&"scalar"===t.kind&&t.T===R.BYTES&&(r=Ce(r)),s[i]={case:e,value:r};break;case"scalar":case"enum":let a=o[i];n.T===R.BYTES&&(a=n.repeated?a.map(Ce):Ce(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===R.BYTES)for(const[e,t]of Object.entries(o[i]))s[i][e]=Ce(t);else Object.assign(s[i],o[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(o[i])){let n=o[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=o[i].map(e=>z(e,c)?e:new c(e));else{const e=o[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=Ce(e):s[i]=e:s[i]=z(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every(e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,s[i]));case"scalar":return n.every((t,i)=>O(e.T,t,s[i]));case"enum":return n.every((e,t)=>O(R.INT32,e,s[t]))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=n,i=s;return e.T.fieldWrapper&&(void 0===t||z(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===i||z(i)||(i=e.T.fieldWrapper.wrapField(i))),e.T.equals(t,i);case"enum":return O(R.INT32,n,s);case"scalar":return O(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const o=e.findField(n.case);if(void 0===o)return!0;switch(o.kind){case"message":return o.T.equals(n.value,s.value);case"enum":return O(R.INT32,n.value,s.value);case"scalar":return O(o.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const r=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return r.every(e=>t.equals(n[e],s[e]));case"enum":return r.every(e=>O(R.INT32,n[e],s[e]));case"scalar":const i=e.V.T;return r.every(e=>O(i,n[e],s[e]))}}}),clone(e){const t=e.getType(),i=new t,n=i;for(const i of t.fields.byMember()){const t=e[i.localName];let s;if(i.repeated)s=t.map(Te);else if("map"==i.kind){s=n[i.localName];for(const[e,i]of Object.entries(t))s[e]=Te(i)}else s="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:Te(t.value)}:{case:void 0}:Te(t);n[i.localName]=s}for(const i of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,i.no,i.wireType,i.data);return i}}),{newFieldList:Ne,initFields:Le}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const o=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),r={[o]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[o];return Object.setPrototypeOf(r.prototype,new g),Object.assign(r,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new r).fromBinary(e,t),fromJson:(e,t)=>(new r).fromJson(e,t),fromJsonString:(e,t)=>(new r).fromJsonString(e,t),equals:(t,i)=>e.util.equals(r,t,i)}),r}(this,e,t,i)},makeEnum:p,makeEnumType:h,getEnumType:l,makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Ne,Le;class Ue extends g{constructor(e){super(),this.seconds=x.zero,this.nanos=0,De.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(De.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=x.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return Ue.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ue({seconds:x.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Ue).fromBinary(e,t)}static fromJson(e,t){return(new Ue).fromJson(e,t)}static fromJsonString(e,t){return(new Ue).fromJsonString(e,t)}static equals(e,t){return De.util.equals(Ue,e,t)}}Ue.runtime=De,Ue.typeName="google.protobuf.Timestamp",Ue.fields=De.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Fe=De.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ue},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:je,repeated:!0},{no:5,name:"events",kind:"message",T:$e,repeated:!0}]),je=De.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:Be,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Be=De.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ue},{no:3,name:"value",kind:"scalar",T:2}]),$e=De.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:Ue},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ue,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Ve=De.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),qe=De.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),He=De.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),ze=De.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),We=De.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ge=De.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Ke=De.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"}]),Je=De.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"}]),Ye=De.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Qe=De.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"}]),Xe=De.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:Ze,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:Mt}]),Ze=De.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),et=De.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:De.getEnumType(He),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}]),tt=De.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:De.getEnumType(it)},{no:4,name:"tracks",kind:"message",T:at,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:et},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:De.getEnumType(nt)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:De.getEnumType(Ke)},{no:18,name:"kind_details",kind:"enum",T:De.getEnumType(st),repeated:!0}]),it=De.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),nt=De.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"}]),st=De.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),ot=De.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),rt=De.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:ct,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:De.getEnumType(dt)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),at=De.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:De.getEnumType(qe)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:De.getEnumType(He)},{no:10,name:"layers",kind:"message",T:ct,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:rt,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:De.getEnumType(ot)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Mt},{no:19,name:"audio_features",kind:"enum",T:De.getEnumType(Qe),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:De.getEnumType(Ve)}]),ct=De.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:De.getEnumType(ze)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),dt=De.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"}]),lt=De.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:De.getEnumType(ut)},{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:ft,oneof:"value"},{no:3,name:"speaker",kind:"message",T:mt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:vt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:bt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Fe,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:kt,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:St,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Tt,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ct,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Ut,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Ft,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:jt,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:ht,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),ut=De.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),ht=De.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:De.getEnumType(ot)},{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}]),pt=De.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:ft,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:kt,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:St,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Tt,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Ct,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Ut,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Ft,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:jt,oneof:"value"}]),mt=De.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:gt,repeated:!0}]),gt=De.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}]),ft=De.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}]),vt=De.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),bt=De.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:yt,repeated:!0}]),yt=De.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}]),kt=De.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}]),St=De.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}]),Tt=De.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Ct=De.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:wt,oneof:"value"}]),wt=De.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}]),Et=De.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),xt=De.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:De.getEnumType(Rt)},{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}]),Rt=De.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Pt=De.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:De.getEnumType(It)},{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}]),It=De.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"}]),Ot=De.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:At},{no:2,name:"screen",kind:"message",T:At},{no:3,name:"resume_connection",kind:"enum",T:De.getEnumType(Ge)},{no:4,name:"disabled_codecs",kind:"message",T:_t},{no:5,name:"force_relay",kind:"enum",T:De.getEnumType(Ge)}]),At=De.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:De.getEnumType(Ge)}]),_t=De.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Ze,repeated:!0},{no:2,name:"publish",kind:"message",T:Ze,repeated:!0}]),Mt=De.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Dt=De.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Nt=De.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:De.getEnumType(Dt)},{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"}),Lt=De.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Ut=De.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:De.getEnumType(ot)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Nt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Lt,oneof:"content_header"}],{localName:"DataStream_Header"}),Ft=De.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"}),jt=De.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"}),Bt=De.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),$t=De.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Vt=De.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),qt=De.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Ht=De.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:ei,oneof:"message"},{no:2,name:"answer",kind:"message",T:ei,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Kt,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Gt,oneof:"message"},{no:5,name:"mute",kind:"message",T:Jt,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ii,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ni,oneof:"message"},{no:8,name:"leave",kind:"message",T:ri,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ci,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Ti,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ei,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Pi,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:di,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ii,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:si,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:oi,oneof:"message"}]),zt=De.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Yt,oneof:"message"},{no:2,name:"answer",kind:"message",T:ei,oneof:"message"},{no:3,name:"offer",kind:"message",T:ei,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Kt,oneof:"message"},{no:5,name:"update",kind:"message",T:ti,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Xt,oneof:"message"},{no:8,name:"leave",kind:"message",T:ri,oneof:"message"},{no:9,name:"mute",kind:"message",T:Jt,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ui,oneof:"message"},{no:11,name:"room_update",kind:"message",T:hi,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:mi,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:fi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:yi,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Ci,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Zt,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Qt,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Oi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Mi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Di,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Li,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:wi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:$i,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:ki,oneof:"message"}]),Wt=De.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:ct,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:De.getEnumType(dt)}]),Gt=De.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:De.getEnumType(qe)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:De.getEnumType(He)},{no:9,name:"layers",kind:"message",T:ct,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Wt,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:De.getEnumType(ot)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:De.getEnumType(Ve)},{no:17,name:"audio_features",kind:"enum",T:De.getEnumType(Qe),repeated:!0}]),Kt=De.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:De.getEnumType($t)},{no:3,name:"final",kind:"scalar",T:8}]),Jt=De.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Yt=De.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Xe},{no:2,name:"participant",kind:"message",T:tt},{no:3,name:"other_participants",kind:"message",T:tt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:li,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:Ot},{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:xt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Ze,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Qt=De.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:li,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Ot},{no:3,name:"server_info",kind:"message",T:xt},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Xt=De.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:at}]),Zt=De.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ei=De.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}}]),ti=De.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:tt,repeated:!0}]),ii=De.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:Et,repeated:!0}]),ni=De.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:De.getEnumType(ze)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),si=De.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:De.getEnumType(Qe),repeated:!0}]),oi=De.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),ri=De.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:De.getEnumType(Ke)},{no:3,name:"action",kind:"enum",T:De.getEnumType(ai)},{no:4,name:"regions",kind:"message",T:Ai}]),ai=De.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),ci=De.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:ct,repeated:!0}]),di=De.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}]),li=De.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}]),ui=De.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:gt,repeated:!0}]),hi=De.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Xe}]),pi=De.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:De.getEnumType(We)},{no:3,name:"score",kind:"scalar",T:2}]),mi=De.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:pi,repeated:!0}]),gi=De.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:De.getEnumType(Vt)}]),fi=De.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:gi,repeated:!0}]),vi=De.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:De.getEnumType(ze)},{no:2,name:"enabled",kind:"scalar",T:8}]),bi=De.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:vi,repeated:!0}]),yi=De.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:bi,repeated:!0}]),ki=De.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Bt,repeated:!0}]),Si=De.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}]),Ti=De.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Si,repeated:!0}]),Ci=De.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}]),wi=De.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Xe},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:tt},{no:4,name:"other_participants",kind:"message",T:tt,repeated:!0}]),Ei=De.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:ei},{no:2,name:"subscription",kind:"message",T:ii},{no:3,name:"publish_tracks",kind:"message",T:Xt,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ri,repeated:!0},{no:5,name:"offer",kind:"message",T:ei},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:xi,repeated:!0}]),xi=De.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Ri=De.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:De.getEnumType($t)}]),Pi=De.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:De.getEnumType(qt),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"}]),Ii=De.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Oi=De.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Ai=De.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:_i,repeated:!0}]),_i=De.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}]),Mi=De.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:De.getEnumType(Ye)}]),Di=De.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:De.getEnumType(Ni)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Kt,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Gt,oneof:"request"},{no:6,name:"mute",kind:"message",T:Jt,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:di,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:si,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:oi,oneof:"request"}]),Ni=De.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"}]),Li=De.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Ui=De.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}]),Fi=De.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Pt},{no:2,name:"connection_settings",kind:"message",T:Ui},{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:Gt,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:ei},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:De.getEnumType(Je)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ei}]),ji=De.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:De.getEnumType(Bi)},{no:2,name:"join_request",kind:"scalar",T:12}]),Bi=De.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),$i=De.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function Vi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qi,Hi={exports:{}};var zi,Wi,Gi,Ki,Ji,Yi=(qi||(qi=1,Wi=Hi.exports,Gi=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},o=null;function r(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var o=n[s];this[o]=s<i?e:this.methodFactory(o,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,o){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?r(console,n):void 0!==console.log?r(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var r,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:r},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(o!==u&&(r=m(o.getLevel())),c.call(u),o===u)for(var e in s)s[e].rebuild()},r=m(o?o.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(o=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,o.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=h),o},o.getLoggers=function(){return s},o.default=o,o},(zi=Hi).exports?zi.exports=Gi():Wi.log=Gi()),Hi.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(Ki||(Ki={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(Ji||(Ji={}));let Qi=Yi.getLogger("livekit");function Xi(e){const t=Yi.getLogger(e);return t.setDefaultLevel(Qi.getLevel()),t}Object.values(Ji).map(e=>Yi.getLogger(e)),Qi.setDefaultLevel(Ki.info);const Zi=Yi.getLogger("lk-e2ee"),en=7e3,tn=[0,300,1200,2700,4800,en,en,en,en,en];function nn(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(r,a)}c((n=n.apply(e,t||[])).next())})}function sn(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function on(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=sn(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,s){(function(e,t,i,n){Promise.resolve(n).then(function(t){e({value:t,done:i})},t)})(n,s,(t=e[i](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;var rn,an={exports:{}};var cn=function(){if(rn)return an.exports;rn=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}an.exports=s,an.exports.once=function(e,t){return new Promise(function(i,n){function s(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,s,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,o,c,d;if(r(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),c=o[t]),void 0===c)c=o[t]=i,++e._eventsCount;else if("function"==typeof c?c=o[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function s(o){n.once&&e.removeEventListener(t,s),i(o)})}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,o=this._events;if(void 0!==o)s=s&&void 0===o.error;else if(!s)return!1;if(s){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return r(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,o,a;if(r(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,o=i.length-1;o>=0;o--)if(i[o]===t||i[o].listener===t){a=i[o].listener,s=o;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,o=Object.keys(i);for(n=0;n<o.length;++n)"removeListener"!==(s=o[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},an.exports}();let dn=!0,ln=!0;function un(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function hn(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const o=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),s.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function pn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(dn=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function mn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ln=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function gn(){if("object"==typeof window){if(dn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function fn(e,t){ln&&console.warn(e+" is deprecated, please use "+t+" instead.")}function vn(e){return"[object Object]"===Object.prototype.toString.call(e)}function bn(e){return vn(e)?Object.keys(e).reduce(function(t,i){const n=vn(e[i]),s=n?bn(e[i]):e[i],o=n&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[i]:s})},{}):e}function yn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?yn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach(t=>{yn(e,e.get(t),i)})}))}function kn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const o=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)}),o.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&yn(e,i,s)})}),s}const Sn=gn;function Tn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const r=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||r)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{i=i.filter(e=>"videoinput"===e.kind);let r=i.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!r&&i.length&&t.includes("back")&&(r=i[i.length-1]),r&&(e.video.deviceId=o.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=n(e.video),Sn("chrome: "+JSON.stringify(e)),s(e)})}e.video=n(e.video)}return Sn("chrome: "+JSON.stringify(e)),s(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){s(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(o(e))})})}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(o(e))))}}}function Cn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function wn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else hn(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function En(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function xn(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>kn(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),hn(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>kn(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach(i=>{i.track===e&&(t?n=!0:t=i)}),this.getReceivers().forEach(t=>(t.track===e&&(i?n=!0:i=t),t.track===e)),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Rn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{const t=this.getSenders().find(t=>t.track===e);if(t)throw new DOMException("Track already exists.","InvalidAccessError")});const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),s.apply(this,arguments)}}function Pn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Rn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{const t=this.getSenders().find(t=>t.track===e);if(t)throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const s=this.getSenders().find(e=>e.track===t);if(s)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[i.id];if(o)o.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>o(this,e))}};e.RTCPeerConnection.prototype[t]=n[t]});const r=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)}),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),r.apply(this,arguments)):r.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function In(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]})}function On(e,t){hn(e,"negotiationneeded",e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var An=Object.freeze({__proto__:null,fixNegotiationNeeded:On,shimAddTrackRemoveTrack:Pn,shimAddTrackRemoveTrackWithNative:Rn,shimGetSendersWithDtmf:En,shimGetUserMedia:Tn,shimMediaStream:Cn,shimOnTrack:wn,shimPeerConnection:In,shimSenderReceiverGetStats:xn});function _n(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){fn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Mn(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Dn(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]});const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,o]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!s)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(s,o)}}function Nn(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ln(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),hn(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Un(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){fn("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Fn(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function jn(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function Bn(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function $n(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Vn(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var qn=Object.freeze({__proto__:null,shimAddTransceiver:jn,shimCreateAnswer:Vn,shimCreateOffer:$n,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Bn,shimGetUserMedia:_n,shimOnTrack:Mn,shimPeerConnection:Dn,shimRTCDataChannel:Fn,shimReceiverGetStats:Ln,shimRemoveStream:Un,shimSenderGetStats:Nn});function Hn(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function zn(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function Wn(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,o=t.setRemoteDescription,r=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Gn(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Kn(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Kn(e){return e&&void 0!==e.video?Object.assign({},e,{video:bn(e.video)}):e}function Jn(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(fn("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Yn(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Qn(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Xn(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Zn,es=Object.freeze({__proto__:null,shimAudioContext:Xn,shimCallbacksAPI:Wn,shimConstraints:Kn,shimCreateOfferLegacy:Qn,shimGetUserMedia:Gn,shimLocalStreamsAPI:Hn,shimRTCIceServerUrls:Jn,shimRemoteStreamsAPI:zn,shimTrackEventTransceiver:Yn}),ts={exports:{}};var is=(Zn||(Zn=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let s=3;s<n.length;s++){const o=n[s],r=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(r){const n=t.parseRtpMap(r),s=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(n.parameters=s.length?t.parseFmtp(s[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{i.headerExtensions.push(t.parseExtmap(e))});const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(e=>{s.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)});let s=0;return i.codecs.forEach(e=>{e.maxptime>s&&(s=e.maxptime)}),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),r=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=r.length>0&&r[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}}),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach(e=>{e.maxBitrate=l})),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const r=t.matchPrefix(e,"a=sctpmap:");if(r.length>0){const e=r[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const o=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(ts)),ts.exports),ns=Vi(is),ss=t({__proto__:null,default:ns},[is]);function os(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=ns.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,hn(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function rs(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||hn(e,"icecandidate",e=>{if(e.candidate){const t=ns.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function as(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=ns.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=ns.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=ns.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>s}),this._sctp=o}return i.apply(this,arguments)}}function cs(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},hn(e,"datachannel",e=>(t(e.channel,e.target),e))}function ds(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function ls(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function us(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function hs(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var ps=Object.freeze({__proto__:null,removeExtmapAllowMixed:ls,shimAddIceCandidateNullOrEmpty:us,shimConnectionState:ds,shimMaxMessageSize:as,shimParameterlessSetLocalDescription:hs,shimRTCIceCandidate:os,shimRTCIceCandidateRelayProtocol:rs,shimSendThrowTypeError:cs});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=gn,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=parseInt(un(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(un(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(un(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=un(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),s={browserDetails:n,commonShim:ps,extractVersion:un,disableLog:pn,disableWarnings:mn,sdp:ss};switch(n.browser){case"chrome":if(!An||!In||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=An,us(e,n),hs(e),Tn(e,n),Cn(e),In(e,n),wn(e),Pn(e,n),En(e),xn(e),On(e,n),os(e),rs(e),ds(e),as(e,n),cs(e),ls(e,n);break;case"firefox":if(!qn||!Dn||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=qn,us(e,n),hs(e),_n(e,n),Dn(e,n),Mn(e),Un(e),Nn(e),Ln(e),Fn(e),jn(e),Bn(e),$n(e),Vn(e),os(e),ds(e),as(e,n),cs(e);break;case"safari":if(!es||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=es,us(e,n),hs(e),Jn(e),Qn(e),Wn(e),Hn(e),zn(e),Yn(e),Gn(e),Xn(e),os(e),rs(e),as(e,n),cs(e),ls(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class ms extends Promise{constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}const gs=/version\/(\d+(\.?_?\d+)+)/i;let fs;function vs(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const i=navigator.userAgent.toLowerCase();if(void 0===fs||t){const e=bs.find(e=>{let{test:t}=e;return t.test(i)});fs=null==e?void 0:e.describe(i)}return fs}const bs=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:ys(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ks(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:ys(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ks(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:ys(gs,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:ks(e)})}];function ys(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function ks(e){return e.includes("mac os")?ys(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class Ss extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var Ts,Cs,ws,Es,xs,Rs,Ps;!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(Ts||(Ts={}));class Is extends Ss{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=Ts[t]}static notAllowed(e,t,i){return new Is(e,Ts.NotAllowed,t,i)}static timeout(e){return new Is(e,Ts.Timeout)}static leaveRequest(e,t){return new Is(e,Ts.LeaveRequest,void 0,t)}static internal(e,t){return new Is(e,Ts.InternalError,void 0,t)}static cancelled(e){return new Is(e,Ts.Cancelled)}static serverUnreachable(e,t){return new Is(e,Ts.ServerUnreachable,t)}static websocket(e,t,i){return new Is(e,Ts.WebSocket,t,i)}static serviceNotFound(e,t){return new Is(e,Ts.ServiceNotFound,void 0,t)}}class Os extends Ss{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class As extends Ss{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class _s extends Ss{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Ms extends Ss{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Ds extends Ss{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Ns extends Ss{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Ls extends Ss{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:Ni[t]}}!function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(Cs||(Cs={}));class Us extends Ss{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=Cs[t]}}class Fs extends Ss{constructor(e){super(18,e),this.name="SignalReconnectError"}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(ws||(ws={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(ws||(ws={}));class js{}js.setTimeout=function(){return setTimeout(...arguments)},js.setInterval=function(){return setInterval(...arguments)},js.clearTimeout=function(){return clearTimeout(...arguments)},js.clearInterval=function(){return clearInterval(...arguments)},function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"}(Es||(Es={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(xs||(xs={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"}(Rs||(Rs={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(Ps||(Ps={}));class Bs{constructor(e,t,i,n,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const $s=["vp8","h264"],Vs=["vp8","h264","vp9","av1","h265"];const qs=function(e){return!!$s.find(t=>t===e)};var Hs,zs;!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(Hs||(Hs={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(zs||(zs={}));const Ws={h90:new Bs(160,90,9e4,20),h180:new Bs(320,180,16e4,20),h216:new Bs(384,216,18e4,20),h360:new Bs(640,360,45e4,20),h540:new Bs(960,540,8e5,25),h720:new Bs(1280,720,17e5,30),h1080:new Bs(1920,1080,3e6,30),h1440:new Bs(2560,1440,5e6,30),h2160:new Bs(3840,2160,8e6,30)},Gs={h120:new Bs(160,120,7e4,20),h180:new Bs(240,180,125e3,20),h240:new Bs(320,240,14e4,20),h360:new Bs(480,360,33e4,20),h480:new Bs(640,480,5e5,20),h540:new Bs(720,540,6e5,25),h720:new Bs(960,720,13e5,30),h1080:new Bs(1440,1080,23e5,30),h1440:new Bs(1920,1440,38e5,30)},Ks={h360fps3:new Bs(640,360,2e5,3,"medium"),h360fps15:new Bs(640,360,4e5,15,"medium"),h720fps5:new Bs(1280,720,8e5,5,"medium"),h720fps15:new Bs(1280,720,15e5,15,"medium"),h720fps30:new Bs(1280,720,2e6,30,"medium"),h1080fps15:new Bs(1920,1080,25e5,15,"medium"),h1080fps30:new Bs(1920,1080,5e6,30,"medium"),original:new Bs(0,0,7e6,30,"medium")};function Js(e,t,i){var n,s,o,r;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=oo(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(Ys(h.audio,t),null!==(n=(o=h.audio).deviceId)&&void 0!==n||(o.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(Ys(h.video,i),null!==(s=(r=h.video).deviceId)&&void 0!==s||(r.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function Ys(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function Qs(e){var t,i,n,s;const o={};if(e.video)if("object"==typeof e.video){const i={},s=i,r=e.video;Object.keys(r).forEach(e=>{if("resolution"===e)Ys(s,r.resolution);else s[e]=r[e]}),o.video=i,null!==(t=(n=o.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else o.video=!!e.video&&{deviceId:{ideal:"default"}};else o.video=!1;return e.audio?"object"==typeof e.audio?(o.audio=e.audio,null!==(i=(s=o.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):o.audio={deviceId:{ideal:"default"}}:o.audio=!1,o}function Xs(e){return nn(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Zs();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield mo(t),n.getByteTimeDomainData(o);const r=o.some(e=>128!==e&&0!==e);return i.close(),!r}return!1}()})}function Zs(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>nn(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}});i.addEventListener("statechange",()=>{var t;"closed"===i.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return i}}function eo(e){return"audioinput"===e?lo.Source.Microphone:"videoinput"===e?lo.Source.Camera:lo.Source.Unknown}function to(e){return e===lo.Source.Microphone?"audioinput":e===lo.Source.Camera?"videoinput":void 0}function io(e){return e.split("/")[1].toLowerCase()}function no(e){const t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new Xt({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function so(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?so(e.track):{})}}function oo(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function ro(e,t){return e.width*e.height<t.width*t.height}const ao=[];var co;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(co||(co={}));class lo extends cn.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=lo.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=Xi(null!==(n=i.loggerName)&&void 0!==n?n:Ji.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=lo.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),so(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===lo.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===lo.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(ao.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&ao.splice(ao.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),uo(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?Ps.AudioPlaybackStarted:Ps.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?Ps.AudioPlaybackFailed:Ps.VideoPlaybackFailed,t):"AbortError"===t.name?Qi.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Qi.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(Ps.ElementAttached,e),e}detach(e){try{if(e){ho(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Ps.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(e=>{ho(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Ps.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Xi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ao.forEach(e=>{e.parentElement||(t=!1)}),t&&ao.push(e)}}handleAppVisibilityChanged(){return nn(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==lo.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){wo()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){wo()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function uo(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),So()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(So()||yo())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function ho(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t,i,n;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(n=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return qe.AUDIO;case t.Video:return qe.VIDEO;default:return qe.DATA}},e.kindFromProto=function(e){switch(e){case qe.AUDIO:return t.Audio;case qe.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return He.CAMERA;case i.Microphone:return He.MICROPHONE;case i.ScreenShare:return He.SCREEN_SHARE;case i.ScreenShareAudio:return He.SCREEN_SHARE_AUDIO;default:return He.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case He.CAMERA:return i.Camera;case He.MICROPHONE:return i.Microphone;case He.SCREEN_SHARE:return i.ScreenShare;case He.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Vt.ACTIVE:return n.Active;case Vt.PAUSED:return n.Paused;default:return n.Unknown}}}(lo||(lo={}));const po="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function mo(e){return new ms(t=>js.setTimeout(t,e))}function go(){return"addTransceiver"in RTCPeerConnection.prototype}function fo(){return"addTrack"in RTCPeerConnection.prototype}function vo(e){return"av1"===e||"vp9"===e}function bo(e){return!(!document||To())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function yo(){var e;return"Firefox"===(null===(e=vs())||void 0===e?void 0:e.name)}function ko(){const e=vs();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function So(){var e;return"Safari"===(null===(e=vs())||void 0===e?void 0:e.name)}function To(){const e=vs();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function Co(){var e,t;return!!wo()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function wo(){return"undefined"!=typeof document}function Eo(){return"ReactNative"==navigator.product}function xo(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Ro(e){return xo(e)?e.hostname.split(".")[0]:null}function Po(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Io(){if(!Eo())return;let e=Po();return e?e.platform:void 0}function Oo(){if(wo())return window.devicePixelRatio;if(Eo()){let e=Po();if(e)return e.devicePixelRatio}return 1}function Ao(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let e=0;e<s;++e){const t=parseInt(i[e],10),o=parseInt(n[e],10);if(t>o)return 1;if(t<o)return-1;if(e===s-1&&t===o)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function _o(e){for(const t of e)t.target.handleResize(t)}function Mo(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Do=null;const No=()=>(Do||(Do=new ResizeObserver(_o)),Do);let Lo=null;const Uo=()=>(Lo||(Lo=new IntersectionObserver(Mo,{root:null,rootMargin:"0px"})),Lo);function Fo(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const o=s.getContext("2d");null==o||o.fillRect(0,0,s.width,s.height),n&&o&&(o.beginPath(),o.arc(e/2,t/2,50,0,2*Math.PI,!0),o.closePath(),o.fillStyle="grey",o.fill());const r=s.captureStream(),[a]=r.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let jo;function Bo(){if(!jo){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[jo]=n.stream.getAudioTracks(),!jo)throw Error("Could not get empty media stream audio track");jo.enabled=!1}return jo.clone()}class $o{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>nn(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)})}}function Vo(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function qo(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Ho(e){switch(e.reason){case Ts.LeaveRequest:return e.context;case Ts.Cancelled:return Ke.CLIENT_INITIATED;case Ts.NotAllowed:return Ke.USER_REJECTED;case Ts.ServerUnreachable:return Ke.JOIN_FAILURE;default:return Ke.UNKNOWN_REASON}}function zo(e){return void 0!==e?Number(e):void 0}function Wo(e){return void 0!==e?BigInt(e):void 0}function Go(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Ko(e){return!!e&&e.kind==lo.Kind.Audio}function Jo(e){return!!e&&e.kind==lo.Kind.Video}function Yo(e){return Go(e)&&Jo(e)}function Qo(e){return Go(e)&&Ko(e)}function Xo(e){return!!e&&!e.isLocal}function Zo(e){return!!e&&!e.isLocal}function er(e){return Xo(e)&&Jo(e)}function tr(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach((e,t)=>{i.searchParams.set(t,e)}),nr(i,"rtc")}(e,t);return i?n:nr(n,"v1")}function ir(e){return e.endsWith("/")?e:"".concat(e,"/")}function nr(e,t){return e.pathname="".concat(ir(e.pathname)).concat(t),e}function sr(e){if("string"==typeof e)return zt.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return zt.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const or="lk_e2ee";var rr,ar,cr,dr,lr;function ur(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||hr()}function hr(){return void 0!==window.RTCRtpScriptTransform}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(rr||(rr={})),function(e){e.KeyRatcheted="keyRatcheted"}(ar||(ar={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(cr||(cr={})),function(e){e.Error="cryptorError"}(dr||(dr={}));cn.EventEmitter;!function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(lr||(lr={}));class pr extends cn.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":if(Qi.error(s.error.message),s.uuid){const e=this.decryptDataRequests.get(s.uuid);if(null==e?void 0:e.reject){e.reject(s.error);break}const t=this.encryptDataRequests.get(s.uuid);if(null==t?void 0:t.reject){t.reject(s.error);break}}this.emit(cr.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(cr.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(cr.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(rr.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const e=this.decryptDataRequests.get(s.uuid);(null==e?void 0:e.resolve)&&e.resolve(s);break;case"encryptDataResponse":const n=this.encryptDataRequests.get(s.uuid);(null==n?void 0:n.resolve)&&n.resolve(s)}},this.onWorkerError=e=>{Qi.error("e2ee worker encountered an error:",{error:e.error}),this.emit(cr.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!ur())throw new Os("tried to setup end-to-end encryption on an unsupported browser");if(Qi.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Zi.getLevel()}};this.worker&&(Qi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Qi.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Qi.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(Rs.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(Es.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ot.NONE,t.identity)),e.on(Es.ConnectionStateChanged,t=>{t===Xa.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==ot.NONE,e.identity)})})}).on(Es.TrackUnsubscribed,(e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)}).on(Es.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(Es.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(xs.LocalSenderCreated,(e,t)=>nn(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(xs.LocalTrackPublished,e=>{if(!Jo(e.track)||!To())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:io(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(rr.SetKey,e=>this.postKey(e)).on(rr.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return nn(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new $o;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise})}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:i,keyIndex:n}},r=new $o;return r.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,r),this.worker.postMessage(o),r.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(o)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?io(i.mimeType):void 0)}}setupE2EESender(e,t){Go(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Qi.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return nn(this,void 0,void 0,function*(){if(this.worker){if(hr()&&!ko()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(or in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,o=e.readableStream;if(!s||!o){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,o=t.readable}const r={kind:"decode",data:{readableStream:o,writableStream:s,trackId:t,codec:n,participantIdentity:i,isReuse:or in e}};this.worker.postMessage(r,[o,s])}e[or]=!0}})}handleSender(e,t,i){var n;if(!(or in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(hr()&&!ko()){Qi.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{Qi.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(s,[n.readable,n.writable])}e[or]=!0}}}class mr{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new mr),this._instance}addFailedConnectionAttempt(e){var t;const i=Ro(new URL(e));if(!i)return;let n=null!==(t=this.failedConnectionAttempts.get(i))&&void 0!==t?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,mo(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){const t=new URL(e),i=t&&Ro(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Ro(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}mr._instance=null;const gr="default";class fr{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new fr),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return nn(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=fr.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Qi.debug("awaiting getUserMedia promise");try{e?yield fr.userMediaPromiseMap.get(e):yield Promise.all(fr.userMediaPromiseMap.values())}catch(e){Qi.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!So()||!t.hasDeviceInUse(e))){const t=0===s.filter(t=>t.kind===e).length||s.some(t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n});if(t){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach(e=>{e.stop()})}}return t._previousDevices=s,e&&(s=s.filter(t=>t.kind===e)),s}()})}normalizeDeviceId(e,t,i){return nn(this,void 0,void 0,function*(){if(t!==gr)return t;const n=yield this.getDevices(e),s=n.find(e=>e.deviceId===gr);if(!s)return void Qi.warn("could not reliably determine default device");const o=n.find(e=>e.deviceId!==gr&&e.groupId===(null!=i?i:s.groupId));if(o)return null==o?void 0:o.deviceId;Qi.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?fr.userMediaPromiseMap.has(e):fr.userMediaPromiseMap.size>0}}var vr;fr.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],fr.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(vr||(vr={}));class br{constructor(){this.pendingTasks=new Map,this.taskMutex=new s,this.nextTaskIndex=0}run(e){return nn(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:vr.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=vr.RUNNING,yield e()}finally{t.status=vr.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return nn(this,void 0,void 0,function*(){return this.run(()=>nn(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class yr{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;if(null===(i=t.signal)||void 0===i?void 0:i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const s=new WebSocket(e,null!==(n=t.protocols)&&void 0!==n?n:[]);s.binaryType="arraybuffer",this.ws=s;const o=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return s.close(e,t)};this.opened=new ms((e,t)=>{const i=()=>{t(Is.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{e({readable:new ReadableStream({start(e){s.onmessage=t=>{let{data:i}=t;return e.enqueue(i)},s.onerror=t=>e.error(t)},cancel:o}),writable:new WritableStream({write(e){s.send(e)},abort(){s.close()},close:o}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",i)},s.addEventListener("error",i)}),this.closed=new ms((e,t)=>{const i=()=>nn(this,void 0,void 0,function*(){const i=new ms(e=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",t=>{e(t)},{once:!0})}),n=yield ms.race([mo(250),i]);n?e(n):t(Is.websocket("Encountered unspecified websocket error without a timely close event"))});s.onclose=t=>{let{code:n,reason:o}=t;e({closeCode:n,reason:o}),s.removeEventListener("error",i)},s.addEventListener("error",i)}),t.signal&&(t.signal.onabort=()=>s.close()),this.close=o}}const kr=["syncState","trickle","offer","answer","simulate","leave"];var Sr;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(Sr||(Sr={}));class Tr{get currentState(){return this.state}get isDisconnected(){return this.state===Sr.DISCONNECTING||this.state===Sr.DISCONNECTED}get isEstablishingConnection(){return this.state===Sr.CONNECTING||this.state===Sr.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Sr.DISCONNECTED,this.log=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=Xi(null!==(i=t.loggerName)&&void 0!==i?i:Ji.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new br,this.queuedRequests=[],this.closingLock=new s,this.connectionLock=new s,this.state=Sr.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return nn(this,arguments,void 0,function(e,t,i,n){var s=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){s.state=Sr.CONNECTING,s.options=i;return yield s.connect(e,t,i,n,o)}()})}reconnect(e,t,i,n){return nn(this,void 0,void 0,function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=Sr.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath)})}connect(e,t,i,n){return nn(this,arguments,void 0,function(e,t,i,n){var s=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){const r=yield s.connectionLock.lock();s.connectOptions=i,s.useV0SignalPath=o;const a=function(){var e;const t=new Pt({sdk:It.JS,protocol:16,version:"2.17.0"});return Eo()&&(t.os=null!==(e=Io())&&void 0!==e?e:""),t}(),c=o?function(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",Eo()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return s}(t,a,i):function(e,t,i){const n=new URLSearchParams;n.set("access_token",e);const s=new Fi({clientInfo:t,connectionSettings:new Ui({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0});i.reconnectReason&&(s.reconnectReason=i.reconnectReason);const o=new ji({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(o.toBinary()))),n}(t,a,i),d=tr(e,c,o).toString(),l=(u=d,nr(new URL(qo(u)),"validate")).toString();var u;return new Promise((e,t)=>nn(s,void 0,void 0,function*(){var s,o;try{let r=!1;const a=e=>nn(this,void 0,void 0,function*(){if(r)return;r=!0;const i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;const i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(i)).catch(e=>{this.log.error(e),this.close()}):this.close(),c(),t(Is.cancelled(i))});null==n||n.addEventListener("abort",a);const c=()=>{clearTimeout(u),null==n||n.removeEventListener("abort",a)},u=setTimeout(()=>{a(Is.timeout("room connection has timed out (signal)"))},i.websocketTimeout),h=(e,t)=>{this.handleSignalConnected(e,u,t)},p=new URL(d);p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(p),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new yr(d);try{this.ws.closed.then(e=>{var i;this.isEstablishingConnection&&t(Is.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state})),this.state===Sr.CONNECTED&&this.handleOnClose(null!==(i=e.reason)&&void 0!==i?i:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(Is.internal("Websocket error during a (re)connection attempt: ".concat(e)))});const n=yield this.ws.opened.catch(e=>nn(this,void 0,void 0,function*(){if(this.state!==Sr.CONNECTED){this.state=Sr.DISCONNECTED,clearTimeout(u);const i=yield this.handleConnectionError(e,l);return void t(i)}this.handleWSError(e),t(e)}));if(clearTimeout(u),!n)return;const r=n.readable.getReader();this.streamWriter=n.writable.getWriter();const a=yield r.read();if(r.releaseLock(),!a.value)throw Is.internal("no message received as first message");const c=sr(a.value),d=this.validateFirstMessage(c,null!==(s=i.reconnect)&&void 0!==s&&s);if(!d.isValid)return void t(d.error);"join"===(null===(o=c.message)||void 0===o?void 0:o.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})));h(n,d.shouldProcessFirstMessage?c:void 0),e(d.response)}catch(e){t(e)}finally{c()}}finally{r()}}))}()})}startReadingLoop(e,t){return nn(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield mo(this.signalLatency));const{done:t,value:i}=yield e.read();if(t)break;const n=sr(i);this.handleSignalResponse(n)}})}close(){return nn(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([Sr.DISCONNECTING||Sr.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Sr.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,mo(250)])}}catch(t){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=Sr.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:wr(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:wr(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Kt({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Jt({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return nn(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new di({requestId:s,metadata:e,name:t,attributes:n})}),s}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new ci({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Ti({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:x.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ii({timestamp:x.parse(Date.now()),rtt:x.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new si({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ri({reason:Ke.CLIENT_INITIATED,action:ai.DISCONNECT})})}sendRequest(e){return nn(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=kr.indexOf(e.case)>=0;return Qi.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Sr.RECONNECTING)return void t.queuedRequests.push(()=>nn(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield mo(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new Ht({message:e});try{t.useJSON?yield t.streamWriter.write(s.toJsonString()):yield t.streamWriter.write(s.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=Cr(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const e=Cr(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),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 e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return nn(this,void 0,void 0,function*(){if(this.state===Sr.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=js.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&&js.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=js.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&&js.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=Sr.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,s,o,r;return"join"===(null===(i=e.message)||void 0===i?void 0:i.case)?{isValid:!0,response:e.message.value}:this.state===Sr.RECONNECTING&&"leave"!==(null===(n=e.message)||void 0===n?void 0:n.case)?"reconnect"===(null===(s=e.message)||void 0===s?void 0:s.case)?{isValid:!0,response:e.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===(o=e.message)||void 0===o?void 0:o.case)?{isValid:!1,error:Is.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:Is.internal("Unexpected first message")}:{isValid:!1,error:Is.internal("did not receive join response, got ".concat(null===(r=e.message)||void 0===r?void 0:r.case," instead"))}}handleConnectionError(e,t){return nn(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return Is.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const e=yield i.text();return Is.notAllowed(e,i.status)}return e instanceof Is?e:Is.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(e){return e instanceof Is?e:Is.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}})}}function Cr(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function wr(e,t){return new ei({sdp:e.sdp,type:e.type,id:t})}class Er{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class xr{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[n,s]of i.entries())t.push(e(s,n,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var Rr,Pr,Ir,Or,Ar,_r={},Mr={},Dr={exports:{}};function Nr(){if(Rr)return Dr.exports;Rr=1;var e=Dr.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),Dr.exports}function Lr(){return Pr||(Pr=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(i[n[o]]=t(e[o+1]))}(n.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},n=Nr(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],r=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach(function(e){var t=e[0],s=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),r=o[o.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,r,s)}}),t.media=o,t};var o=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}})})}}(Mr)),Mr}function Ur(){if(Or)return Ir;Or=1;var e=Nr(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var r=t.names[o];t.name?s.push(n[t.name][r]):s.push(n[t.names[o]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return Ir=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var r=i.outerOrder||s,a=i.innerOrder||o,c=[];return r.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})}),t.media.forEach(function(t){c.push(n("m",e.m[0],t)),a.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})})}),c.join("\r\n")+"\r\n"},Ir}var Fr=function(){if(Ar)return _r;Ar=1;var e=Lr(),t=Ur(),i=Nr();return _r.grammar=i,_r.write=t,_r.parse=e.parse,_r.parseParams=e.parseParams,_r.parseFmtpConfig=e.parseFmtpConfig,_r.parsePayloads=e.parsePayloads,_r.parseRemoteCandidates=e.parseRemoteCandidates,_r.parseImageAttributes=e.parseImageAttributes,_r.parseSimulcastStreamList=e.parseSimulcastStreamList,_r}();function jr(e,t,i){var n,s,o;void 0===t&&(t=50),void 0===i&&(i={});var r=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[];function u(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),i=this;return new Promise(function(n,s){var c=r&&void 0===o;if(void 0!==o&&clearTimeout(o),o=setTimeout(function(){if(o=void 0,d=Date.now(),!r){var n=e.apply(i,t);a&&a(n),l.forEach(function(e){return(0,e.resolve)(n)}),l=[]}},u()),c){var h=e.apply(i,t);return a&&a(h),n(h)}l.push({resolve:n,reject:s})})};return h.cancel=function(e){void 0!==o&&clearTimeout(o),l.forEach(function(t){return(0,t.reject)(e)}),l=[]},h}const Br="negotiationStarted",$r="negotiationComplete",Vr="rtpVideoPayloadTypes";class qr extends cn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Qi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=jr(e=>nn(this,void 0,void 0,function*(){this.emit(Br);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Xi(null!==(i=t.loggerName)&&void 0!==i?i:Ji.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new s}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return nn(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return nn(this,void 0,void 0,function*(){var i;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Fr.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let o=0;return s.media.forEach(e=>{var t;const s=Wr(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(o=e.payload,!0)),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some(e=>e.payload===o&&"nack"===e.type))&&n.push(s),e.fmtp.some(e=>e.payload===o&&(e.config.includes("sprop-stereo=1")&&i.push(s),!0)))}),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const t=Fr.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach(e=>{const t=Wr(e.mid);"audio"===e.type&&this.trackBitrates.some(i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;let s=!1;for(const t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),s=!0;break}return s||i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0})}),n=Fr.write(t)}if(yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit($r),e.sdp)){Fr.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(Vr,e.rtp)})}return!0})}createAndSendOffer(e){return nn(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=this.latestOfferId+1;this.latestOfferId=i;const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=Fr.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(s.media.forEach(e=>{zr(e),"audio"===e.type?Hr(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i)return!0;if(vo(t.codec)&&!So()&&this.ensureVideoDDExtensionForSVC(e,s),!vo(t.codec))return!0;const n=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,Fr.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return nn(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Fr.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach(e=>{zr(e),"audio"===e.type&&Hr(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Fr.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Ms("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Ms("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return nn(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0})}setMungedSDP(e,t,i){return nn(this,void 0,void 0,function*(){if(t){const n=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let n="unknown error";t instanceof Error?n=t.message:"string"==typeof t&&(n=t);const s={error:n,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Ds(n)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some(e=>e.uri===po))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:po})}}}function Hr(e,t,i){const n=Wr(e.mid);let s=0;e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),s>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some(e=>e.payload===s&&"nack"===e.type)&&e.rtcpFb.push({payload:s,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some(e=>e.payload===s&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function zr(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function Wr(e){return"number"==typeof e?e.toFixed(0):e}const Gr="vp8",Kr={audioPreset:zs.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ks.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Gr,backupCodec:!0,preConnectBuffer:!1},Jr={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Yr={deviceId:{ideal:"default"},resolution:Ws.h720.resolution},Qr={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:tn}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Xr={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Zr;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(Zr||(Zr={}));class ea{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var n;this.peerConnectionTimeout=Xr.peerConnectionTimeout,this.log=Qi,this.updateState=()=>{var e,t;const i=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>"connected"===e)?this.state=Zr.CONNECTED:n.some(e=>"failed"===e)?this.state=Zr.FAILED:n.some(e=>"connecting"===e)?this.state=Zr.CONNECTING:n.every(e=>"closed"===e)?this.state=Zr.CLOSED:n.some(e=>"closed"===e)?this.state=Zr.CLOSING:n.every(e=>"new"===e)&&(this.state=Zr.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(Zr[i]," to ").concat(Zr[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.log=Xi(null!==(n=i.loggerName)&&void 0!==n?n:Ji.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new qr(e,i),this._mode=t,"publisher-only"!==t&&(this.subscriber=new qr(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,$t.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,$t.PUBLISHER)},this.publisher.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=Zr.NEW,this.connectionLock=new s,this.remoteOfferLock=new s}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return nn(this,void 0,void 0,function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return nn(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return nn(this,void 0,void 0,function*(){var i;t===$t.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return nn(this,void 0,void 0,function*(){var i,n,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(i=this.subscriber)||void 0===i?void 0:i.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{if(!(yield null===(n=this.subscriber)||void 0===n?void 0:n.setRemoteDescription(e,t)))return;return yield null===(s=this.subscriber)||void 0===s?void 0:s.createAndSetAnswer()}finally{o()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null===(i=this.subscriber)||void 0===i||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return nn(this,void 0,void 0,function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map(i=>this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return nn(this,void 0,void 0,function*(){return new ms((t,i)=>nn(this,void 0,void 0,function*(){const n=setTimeout(()=>{i(new Ds("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(n),i(new Ds("negotiation aborted"))}),this.publisher.once(Br,()=>{e.signal.aborted||this.publisher.once($r,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(n),e instanceof Error?i(e):i(new Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e);return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===$t.PUBLISHER||e===$t.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return nn(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,s)=>nn(i,void 0,void 0,function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),js.clearTimeout(o),s(Is.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const o=js.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),s(Is.internal("could not establish pc connection"))},n);for(;this.state!==Zr.CONNECTED;)if(yield mo(50),null==t?void 0:t.signal.aborted)return void s(Is.cancelled("room connection has been cancelled"));js.clearTimeout(o),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class ta{static fetchRegionSettings(e,t,i){return nn(this,void 0,void 0,function*(){const n=yield ta.fetchLock.lock();try{const n=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){const e=function(e){var t;const i=e.get("Cache-Control");if(i){const e=null===(t=i.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers),t=e?1e3*e:5e3;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===n.status?Is.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):Is.internal("Could not fetch region settings: ".concat(n.statusText))}catch(e){throw e instanceof Is?e:(null==i?void 0:i.aborted)?Is.cancelled("Region fetching was aborted"):Is.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{n()}})}static scheduleRefetch(e,t,i){return nn(this,void 0,void 0,function*(){const n=ta.settingsTimeouts.get(e.hostname);clearTimeout(n),ta.settingsTimeouts.set(e.hostname,setTimeout(()=>nn(this,void 0,void 0,function*(){try{const i=yield ta.fetchRegionSettings(e,t);ta.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof Is&&n.reason===Ts.NotAllowed)return void Qi.debug("token is not valid, cancelling auto region refresh");Qi.debug("auto refetching of region settings failed",{error:n}),ta.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){ta.cache.set(e.hostname,i),ta.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=ta.settingsTimeouts.get(e);t&&(clearTimeout(t),ta.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=ta.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const t=ta.connectionTrackers.get(e);t&&0===t.connectionCount&&(Qi.debug("stopping region refetch after disconnect delay",{hostname:e}),ta.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){const t=ta.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=ta.connectionTrackers.get(e);t||(t={connectionCount:0},ta.connectionTrackers.set(e,t)),t.connectionCount++,ta.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=ta.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&ta.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return xo(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return nn(this,void 0,void 0,function*(){return ta.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return nn(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=ta.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),ta.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(i.length>0){const e=i[0];return this.attemptedRegions.push(e),Qi.debug("next region: ".concat(e.region)),e.url}return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){ta.updateCachedRegionSettings(this.serverUrl,this.token,e)}}ta.cache=new Map,ta.settingsTimeouts=new Map,ta.connectionTrackers=new Map,ta.fetchLock=new s;class ia extends Error{constructor(e,t,i){super(t),this.code=e,this.message=sa(t,ia.MAX_MESSAGE_BYTES),this.data=i?sa(i,ia.MAX_DATA_BYTES):void 0}static fromProto(e){return new ia(e.code,e.message,e.data)}toProto(){return new wt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ia(ia.ErrorCode[e],ia.ErrorMessage[e],t)}}ia.MAX_MESSAGE_BYTES=256,ia.MAX_DATA_BYTES=15360,ia.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},ia.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};function na(e){return(new TextEncoder).encode(e).length}function sa(e,t){if(na(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const o=Math.floor((i+n+1)/2);s.encode(e.slice(0,o)).length<=t?i=o:n=o-1}return e.slice(0,i)}const oa=2e3;function ra(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}const aa="undefined"!=typeof MediaRecorder;const ca=aa?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class da extends ca{constructor(e,t){if(!aa)throw new Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([e.mediaStreamTrack]),t);const s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),null==n||n.close(),n=void 0},o=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>nn(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();i=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");i=t.data.byteArray}void 0!==n&&e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",o)}}class la extends lo{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=jr(()=>nn(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>nn(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(Ps.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new s,this.pauseUpstreamLock=new s,this.trackChangeLock=new s,this.trackChangeLock.lock().then(t=>nn(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==lo.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return nn(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{ho(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(uo(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,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:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{uo(null!=n?n:e,t)}))})}waitForDimensions(){return nn(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===lo.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=vs())||void 0===i?void 0:i.os)&&(yield mo(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield mo(50)}throw new As("unable to get track dimensions after timeout")}()})}setDeviceId(e){return nn(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Vo(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Vo(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return nn(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===lo.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===lo.Kind.Audio?"audioinput":"videoinput";return t?fr.getInstance().normalizeDeviceId(s,i,n):i}()})}mute(){return nn(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return nn(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return nn(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 t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return nn(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===lo.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||Object.assign({deviceId:t},n),this.attachedElements.forEach(e=>{ho(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===lo.Kind.Video&&(yield o.applyConstraints(n)),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o),this._constraints=e,this.emit(Ps.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Ps.Muted:Ps.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return nn(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Co()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return nn(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(Ps.UpstreamPaused,this);const t=vs();if("Safari"===(null==t?void 0:t.name)&&Ao(t.version,"12.0")<0)throw new Os("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return nn(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(Ps.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return nn(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()})}setProcessor(e){return nn(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),o={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(o),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(uo(t._mediaStreamTrack,s),s.muted=!0,s.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{s.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(ho(t._mediaStreamTrack,e),uo(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(Ps.TrackProcessorUpdate,t.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return nn(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}}()})}internalStopProcessor(){return nn(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Ps.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(aa)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new da(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}else this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class ua extends la{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,lo.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>nn(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=ra(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Ps.AudioTrackFeatureUpdate,this,Qe.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Ps.AudioTrackFeatureUpdate,this,Qe.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return nn(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===lo.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return nn(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Vo(this._constraints.deviceId);return this.source!==lo.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return nn(this,void 0,void 0,function*(){let t;if(e){const i=Qs({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return nn(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){wo()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},oa)))}setProcessor(e){return nn(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Eo()&&!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(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(Ps.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return nn(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return nn(this,void 0,void 0,function*(){const e=yield Xs(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(Ps.AudioSilenceDetected)),e})}}const ha=Object.values(Ws),pa=Object.values(Gs),ma=Object.values(Ks),ga=[Ws.h180,Ws.h360],fa=[Gs.h180,Gs.h360],va=["q","h","f"];function ba(e,t,i,n){var s,o;let r=null==n?void 0:n.videoEncoding;e&&(r=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!r&&!a&&!c||!t||!i)return[{}];r||(r=function(e,t,i,n){const s=function(e,t,i){if(e)return ma;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return ha;return pa}(e,t,i);let{encoding:o}=s[0];const r=Math.max(t,i);for(let e=0;e<s.length;e+=1){const t=s[e];if(o=t.encoding,t.width>=r)break}if(n)switch(n){case"av1":case"h265":o=Object.assign({},o),o.maxBitrate=.7*o.maxBitrate;break;case"vp9":o=Object.assign({},o),o.maxBitrate=.85*o.maxBitrate}return o}(e,t,i,d),Qi.debug("using video encoding",r));const l=r.maxFramerate,u=new Bs(t,i,r.maxBitrate,r.maxFramerate,r.priority);if(c&&vo(d)){const e=new Ta(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=vs();if(To()||Eo()||"Chrome"===(null==i?void 0:i.name)&&Ao(null==i?void 0:i.version,"113")<0){const n="h"==e.suffix?2:3,s=function(e){return e||(e=vs()),"Safari"===(null==e?void 0:e.name)&&Ao(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&Ao(e.osVersion,"18.3")>0}(i);for(let i=0;i<e.spatial;i+=1)t.push({rid:va[2-i],maxBitrate:r.maxBitrate/Math.pow(n,i),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,i):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:r.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),Qi.debug("using svc encoding",{encodings:t}),t}if(!a)return[r];let h,p=[];if(p=e?null!==(s=Sa(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:ya(e,u):null!==(o=Sa(null==n?void 0:n.videoSimulcastLayers))&&void 0!==o?o:ya(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return ka(t,i,[e,h,u],l);if(n>=480)return ka(t,i,[e,u],l)}return ka(t,i,[u])}function ya(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map(e=>{var t,n;return new Bs(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)});var i;const{width:n,height:s}=t,o=n>s?n/s:s/n;return Math.abs(o-16/9)<Math.abs(o-4/3)?ga:fa}function ka(e,t,i,n){const s=[];if(i.forEach((i,o)=>{if(o>=va.length)return;const r=Math.min(e,t),a={rid:va[o],scaleResolutionDownBy:Math.max(1,r/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=yo()||0===o;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)}),Eo()&&"ios"===Io()){let e;s.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;s.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,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(e)),i.maxFramerate=e)})}return s}function Sa(e){if(e)return e.sort((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class Ta{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Ca extends la{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,lo.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>nn(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(Ps.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=ra(t,s)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new s}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!wo())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},oa))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return nn(this,void 0,void 0,function*(){var t,i,n,s,o;yield e.pauseUpstream.call(this);try{for(var r,a=!0,c=on(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(null)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return nn(this,void 0,void 0,function*(){var t,i,n,s,o;yield e.resumeUpstream.call(this);try{for(var r,a=!0,c=on(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(e.mediaStreamTrack)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return nn(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==lo.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return nn(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==lo.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return nn(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},o=i.get(e.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)}),t})}setPublishingQuality(e){const t=[];for(let i=co.LOW;i<=co.HIGH;i+=1)t.push(new vi({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(vo(this.codec),t)}restartTrack(e){return nn(this,void 0,void 0,function*(){var t,i,n,s,o;let r;if(e){const t=Qs({video:e});"boolean"!=typeof t.video&&(r=t.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var a,c=!0,d=on(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(o=e.sender.transport)||void 0===o?void 0:o.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){i={error:e}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return nn(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,o,r,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=on(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(e){o={error:e}}finally{try{u||s||!(r=h.return)||(yield r.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return nn(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return nn(this,void 0,void 0,function*(){var t,i,n,s,o,r,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(vo(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=on(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield wa(t.sender,t.encodings,e.qualities,this.senderLock,vo(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(vo(e.codec),e.qualities)}}catch(e){o={error:e}}finally{try{t||s||!(r=i.return)||(yield r.call(i))}finally{if(o)throw o.error}}return c})}setPublishingLayers(e,t){return nn(this,void 0,void 0,function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield wa(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return nn(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&vo(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return nn(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Co()&&this.isInBackground&&this.source===lo.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function wa(e,t,i,n,s,o,r){return nn(this,void 0,void 0,function*(){const a=yield n.lock();o.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void o.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(s){i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0)}a.forEach((e,n)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=Ea(a),l=i.find(e=>e.quality===d);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,o.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),yo()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})}c&&(n.encodings=a,o.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}})}function Ea(e){switch(e){case"f":default:return co.HIGH;case"h":return co.MEDIUM;case"q":return co.LOW}}function xa(e,t,i,n){if(!i)return[new ct({quality:co.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new Ta(n),o=[],r="h"==s.suffix?1.5:2,a="h"==s.suffix?2:3;for(let n=0;n<s.spatial;n+=1)o.push(new ct({quality:Math.min(co.HIGH,s.spatial-1)-n,width:Math.ceil(e/Math.pow(r,n)),height:Math.ceil(t/Math.pow(r,n)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,n)):0,ssrc:0}));return o}return i.map(i=>{var n,s,o;const r=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=Ea(null!==(s=i.rid)&&void 0!==s?s:"");return new ct({quality:a,width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:null!==(o=i.maxBitrate)&&void 0!==o?o:0,ssrc:0})})}const Ra="_lossy",Pa="_reliable",Ia="leave-reconnect";var Oa;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(Oa||(Oa={}));class Aa extends cn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Xr.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Oa.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 Er,this.reliableReceivedState=new xr(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>nn(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===Pa)t.reliableDCSub=i;else{if(i.label!==Ra)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>nn(this,void 0,void 0,function*(){var t,i,n,s,o;const r=yield this.dataProcessLock.lock();try{let r;if(e.data instanceof ArrayBuffer)r=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));r=yield e.data.arrayBuffer()}const a=lt.fromBinary(new Uint8Array(r));if(a.sequence>0&&""!==a.participantSid){const e=this.reliableReceivedState.get(a.participantSid);if(e&&a.sequence<=e)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}if("speaker"===(null===(t=a.value)||void 0===t?void 0:t.case))this.emit(Rs.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 e=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),t=pt.fromBinary(e.payload),i=new lt({value:t.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&_a(i,i.value.value),this.emit(Rs.DataPacketReceived,i,a.value.value.encryptionType)}else"user"===(null===(o=a.value)||void 0===o?void 0:o.case)&&_a(a,a.value.value),this.emit(Rs.DataPacketReceived,a,ot.NONE)}finally{r()}}),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?ut.LOSSY:ut.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(Rs.Disconnected),this.close()},n=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==s?(e===Ia&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=js.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),s)):i(n)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===Oa.Connected&&e();const i=()=>{this.off(Rs.Disconnected,n),e()},n=()=>{this.off(Rs.Restarted,i),t()};this.once(Rs.Restarted,i),this.once(Rs.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{if(e===ut.RELIABLE){const t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Rs.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>nn(this,void 0,void 0,function*(){if(!this.url)return;(yield fetch(qo(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===Sr.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Sr.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Je.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>nn(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(qo(this.url),{method:"HEAD"}),mo(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Xi(null!==(t=e.loggerName)&&void 0!==t?t:Ji.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Tr(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new s,this.dataProcessLock=new s,this.dcBufferStatus=new Map([[ut.LOSSY,!0],[ut.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(Rs.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Rs.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Rs.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Rs.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Rs.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Rs.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Rs.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Rs.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,o;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(o=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===o?void 0:o.identity,pID:this.participantSid}}join(e,t,i,n){return nn(this,arguments,void 0,function(e,t,i,n){var s=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){s.url=e,s.token=t,s.signalOpts=i,s.maxJoinAttempts=i.maxRetries;try{s.joinAttempts+=1,s.setupSignalClientCallbacks();const r=yield s.client.join(e,t,i,n,o);return s._isClosed=!1,s.latestJoinResponse=r,s.subscriberPrimary=r.subscriberPrimary,s.pcManager||(yield s.configure(r,!o)),s.subscriberPrimary&&!r.fastPublish||s.negotiate().catch(e=>{Qi.error(e,s.logContext)}),s.registerOnLineListener(),s.clientConfiguration=r.clientConfiguration,s.emit(Rs.SignalConnected,r),r}catch(r){if(r instanceof Is)if(r.reason===Ts.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(e,t,i,n,o)}else if(r.reason===Ts.ServiceNotFound)return s.log.warn("Initial connection failed: ".concat(r.message," – Retrying")),s.join(e,t,i,n,!0);throw r}}()})}close(){return nn(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Rs.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return nn(this,void 0,void 0,function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Er,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 nn(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new As("a track with the same ID has already been published");return new Promise((t,i)=>{const n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(Is.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return nn(this,void 0,void 0,function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return nn(this,void 0,void 0,function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==Zr.NEW)return;this.participantSid=null===(i=e.participant)||void 0===i?void 0:i.sid;const s=this.makeRTCConfiguration(e);var o;this.pcManager=new ea(s,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(Rs.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>nn(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===Zr.CONNECTED){const t=this.pcState===Oa.New;this.pcState=Oa.Connected,t&&this.emit(Rs.Connected,e)}else t===Zr.FAILED&&(this.pcState!==Oa.Connected&&this.pcState!==Oa.Reconnecting||(this.pcState=Oa.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?Je.RR_SUBSCRIBER_FAILED:Je.RR_PUBLISHER_FAILED)));const s=this.client.isDisconnected||this.client.currentState===Sr.RECONNECTING,o=[Zr.FAILED,Zr.CLOSING,Zr.CLOSED].includes(t);s&&o&&!this._isClosed&&this.emit(Rs.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(Rs.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(o=null===(n=e.serverInfo)||void 0===n?void 0:n.protocol)&&o>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>nn(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>nn(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Rs.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Rs.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Rs.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Rs.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(Rs.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const n={direction:"recvonly"};for(let i=0;i<e.numAudios;i++)null===(t=this.pcManager)||void 0===t||t.addPublisherTransceiverOfKind("audio",n);for(let t=0;t<e.numVideos;t++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("video",n);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",Je.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:e.regions})),e.action){case ai.DISCONNECT:this.emit(Rs.Disconnected,null==e?void 0:e.reason),this.close();break;case ai.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Ia);break;case ai.RESUME:this.handleDisconnect(Ia)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach(e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ge.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ra,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Pa,{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 e=this.dataChannelForKind(ut.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,8192),262144)}},1e3))}createSender(e,t,i){return nn(this,void 0,void 0,function*(){if(go()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(fo()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new Ms("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return nn(this,void 0,void 0,function*(){if(go())return this.createSimulcastTransceiverSender(e,t,i,n);if(fo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ms("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return nn(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ms("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Jo(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};i&&(s.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,n){return nn(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ms("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return nn(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ms("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return nn(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)Qi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Ge.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:Zr.NEW)!==Zr.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof Ms?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof Fs||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",Je.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(Rs.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return nn(this,void 0,void 0,function*(){var t,i,n;try{if(!this.url||!this.token)throw new Ms("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Rs.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 Fs;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(e){if(e instanceof Is&&e.reason===Ts.NotAllowed)throw new Ms("could not reconnect, token might be expired");throw new Fs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Rs.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Sr.CONNECTED)throw new Fs("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(Rs.Restarted)}catch(e){const t=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),e}})}resumeConnection(e){return nn(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Ms("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ms("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Rs.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t="";if(e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof Is&&e.reason===Ts.NotAllowed)throw new Ms("could not reconnect, token might be expired");if(e instanceof Is&&e.reason===Ts.LeaveRequest)throw e;throw new Fs(t)}if(this.emit(Rs.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Sr.CONNECTED)throw new Fs("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(Rs.Resumed)})}waitForPCInitialConnection(e,t){return nn(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ms("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return nn(this,void 0,void 0,function*(){this.pcState=Oa.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield mo(2e3),!this.pcManager)throw new Ms("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Oa.Connected}catch(e){throw this.pcState=Oa.Disconnected,Is.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,n){return nn(this,void 0,void 0,function*(){const s=new lt({destinationIdentities:[e],kind:ut.RELIABLE,value:{case:"rpcResponse",value:new Ct({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,ut.RELIABLE)})}publishRpcAck(e,t){return nn(this,void 0,void 0,function*(){const i=new lt({destinationIdentities:[e],kind:ut.RELIABLE,value:{case:"rpcAck",value:new Tt({requestId:t})}});yield this.sendDataPacket(i,ut.RELIABLE)})}sendDataPacket(e,t){return nn(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=function(e){var t,i,n,s,o;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"speaker"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"transcription"!==(null===(s=e.value)||void 0===s?void 0:s.case)&&"encryptedPacket"!==(null===(o=e.value)||void 0===o?void 0:o.case))return new pt({value:e.value})}(e);if(t){const i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new ht({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===ut.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===ut.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t))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(t)})}resendReliableMessagesForResume(e){return nn(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(ut.RELIABLE);const t=this.dataChannelForKind(ut.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(ut.RELIABLE)})}waitForBufferStatusLow(e){return new ms((t,i)=>nn(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i(new Ms("engine closed"));for(this.once(Rs.Closing,n);!this.dcBufferStatus.get(e);)yield mo(10);this.off(Rs.Closing,n),t()}}))}ensureDataTransportConnected(e){return nn(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new Ms("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw Is.internal("".concat(o," connection not set"));let r=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),r=!0),r||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(r=!0),r&&t.negotiate().catch(e=>{Qi.error(e,t.logContext)});const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield mo(50)}throw Is.internal("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()))}()})}ensurePublisherConnected(e){return nn(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===Zr.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return nn(this,void 0,void 0,function*(){return new ms((e,t)=>nn(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new Ds("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new Ds("cannot negotiate on closed engine")),this.on(Rs.Closing,n),this.pcManager.publisher.once(Vr,e=>{const t=new Map;e.forEach(e=>{const i=e.codec.toLowerCase();var n;n=i,Vs.includes(n)&&t.set(e.payload,i)}),this.emit(Rs.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(e){e instanceof Ds&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Je.RR_UNKNOWN),e instanceof Error?t(e):t(new Error(String(e)))}finally{this.off(Rs.Closing,n)}}))})}dataChannelForKind(e,t){if(t){if(e===ut.LOSSY)return this.lossyDCSub;if(e===ut.RELIABLE)return this.reliableDCSub}else{if(e===ut.LOSSY)return this.lossyDC;if(e===ut.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n,s,o;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const r=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),c=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),d=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getLocalDescription(),l=null===(o=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===o||o,u=new Array,h=new Array;e.forEach(e=>{e.isDesired!==l&&u.push(e.trackSid),e.isEnabled||h.push(e.trackSid)}),this.client.sendSyncState(new Ei({answer:"publisher-only"===this.pcManager.mode?a?wr({sdp:a.sdp,type:a.type}):void 0:d?wr({sdp:d.sdp,type:d.type}):void 0,offer:"publisher-only"===this.pcManager.mode?r?wr({sdp:r.sdp,type:r.type}):void 0:c?wr({sdp:c.sdp,type:c.type}):void 0,subscription:new ii({trackSids:u,subscribe:!l,participantTracks:[]}),publishTracks:no(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:h,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new xi({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Ri({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(ut.LOSSY),$t.PUBLISHER),t(this.dataChannelForKind(ut.RELIABLE),$t.PUBLISHER),t(this.dataChannelForKind(ut.LOSSY,!0),$t.SUBSCRIBER),t(this.dataChannelForKind(ut.RELIABLE,!0),$t.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&js.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){wo()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){wo()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(i){const e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===i});if(e)return e[1]}}}function _a(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}class Ma{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new Us("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Cs.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Us("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Cs.LengthExceeded)}}constructor(e,t,i,n){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class Da extends Ma{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new $o,i=null,n=null;if(this.signal){const e=this.signal;n=()=>{var i;null===(i=t.reject)||void 0===i||i.call(t,e.reason)},e.addEventListener("abort",n),i=e}const s=()=>{e.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>nn(this,void 0,void 0,function*(){var i,n;try{const{done:s,value:o}=yield Promise.race([e.read(),t.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(o),{done:!1,value:o.content})}catch(e){throw s(),e}}),return(){return nn(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return nn(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,o;let r=new Set;const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=on(a);!(i=(c=yield l.next()).done);d=!0){o=c.value,d=!1;const e=o;r.add(e)}}catch(e){n={error:e}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return Array.from(r)}()})}}class Na extends Ma{constructor(e,t,i,n){super(e,t,i,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=zo(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new $o,n=null,s=null;if(this.signal){const e=this.signal;s=()=>{var t;null===(t=i.reject)||void 0===t||t.call(i,e.reason)},e.addEventListener("abort",s),n=e}const o=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>nn(this,void 0,void 0,function*(){var n,s;try{const{done:o,value:r}=yield Promise.race([e.read(),i.promise,null!==(s=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==s?s:new Promise(()=>{})]);if(o)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(r);try{e=t.decode(r.content)}catch(e){throw new Us("Cannot decode datastream chunk ".concat(r.chunkIndex," as text: ").concat(e),Cs.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw o(),e}}),return(){return nn(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return nn(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,o;let r="";const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=on(a);!(i=(c=yield l.next()).done);d=!0){o=c.value,d=!1;r+=o}}catch(e){n={error:e}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return r}()})}}class La{constructor(){this.log=Qi,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Us('A text stream handler for topic "'.concat(e,'" has already been set.'),Cs.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Us('A byte stream handler for topic "'.concat(e,'" has already been set.'),Cs.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,n,s;const o=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),r=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(o.length>0||r.length>0){const a=new Us("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Cs.AbnormalEnd);for(const[e,n]of r)null===(i=(t=n.outOfBandFailureRejectingFuture).reject)||void 0===i||i.call(t,a),this.byteStreamControllers.delete(e);for(const[e,t]of o)null===(s=(n=t.outOfBandFailureRejectingFuture).reject)||void 0===s||s.call(n,a),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return nn(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return nn(this,void 0,void 0,function*(){var n;if("byteHeader"===e.contentHeader.case){const s=this.byteStreamHandlers.get(e.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let o;const r=new $o;r.promise.catch(e=>{this.log.error(e)});const a={id:e.streamId,name:null!==(n=e.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:zo(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(o=i,this.textStreamControllers.has(e.streamId))throw new Us("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Cs.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:r})}});s(new Da(a,c,zo(e.totalLength),r),{identity:t})}else if("textHeader"===e.contentHeader.case){const n=this.textStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let s;const o=new $o;o.promise.catch(e=>{this.log.error(e)});const r={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i},a=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(e.streamId))throw new Us("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Cs.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:r,controller:s,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});n(new Na(r,a,zo(e.totalLength),o),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Us("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Cs.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new Us("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),Cs.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Us("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Cs.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new Us("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),Cs.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Ua{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return nn(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)})}}class Fa extends Ua{}class ja extends Ua{}class Ba{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return nn(this,void 0,void 0,function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,o=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map(()=>crypto.randomUUID()),r=new Array(o?o.length+1:1).fill(0),a=(e,i)=>{var n;r[i]=e;const s=r.reduce((e,t)=>e+t,0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:o,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&o&&(yield Promise.all(t.attachments.map((e,i)=>nn(this,void 0,void 0,function*(){return this._sendFile(o[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))),c.info})}streamText(e){return nn(this,void 0,void 0,function*(){var t,i,n;const s=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),o={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null===(n=this.engine.e2eeManager)||void 0===n?void 0:n.isDataChannelEncryptionEnabled)?ot.GCM:ot.NONE},r=new Ut({streamId:s,mimeType:o.mimeType,topic:o.topic,timestamp:Wo(o.timestamp),totalLength:Wo(null==e?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new Nt({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?Dt.UPDATE:Dt.CREATE})}}),a=null==e?void 0:e.destinationIdentities,c=new lt({destinationIdentities:a,value:{case:"streamHeader",value:r}});yield this.engine.sendDataPacket(c,ut.RELIABLE);let d=0;const l=this.engine,u=new WritableStream({write(e){return nn(this,void 0,void 0,function*(){for(const t of function(e,t){const i=[];let n=(new TextEncoder).encode(e);for(;n.length>t;){let e=t;for(;e>0;){const t=n[e];if(void 0!==t&&128!=(192&t))break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,15e3)){const e=new Ft({content:t,streamId:s,chunkIndex:Wo(d)}),i=new lt({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(i,ut.RELIABLE),d+=1}})},close(){return nn(this,void 0,void 0,function*(){const e=new jt({streamId:s}),t=new lt({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield l.sendDataPacket(t,ut.RELIABLE)})},abort(e){console.log("Sink error:",e)}});let h=()=>nn(this,void 0,void 0,function*(){yield p.close()});l.once(Rs.Closing,h);const p=new Fa(u,o,()=>this.engine.off(Rs.Closing,h));return p})}sendFile(e,t){return nn(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return nn(this,void 0,void 0,function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:e,value:t}=yield o.read();if(e)break;yield s.write(t)}return yield s.close(),s.info})}streamBytes(e){return nn(this,void 0,void 0,function*(){var t,i,n,o,r,a;const c=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),d=null==e?void 0:e.destinationIdentities,l={id:c,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(o=null==e?void 0:e.name)&&void 0!==o?o:"unknown",encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?ot.GCM:ot.NONE},u=new Ut({totalLength:Wo(null!==(a=l.size)&&void 0!==a?a:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:Wo(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new Lt({name:l.name})}}),h=new lt({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,ut.RELIABLE);let p=0;const m=new s,g=this.engine,f=this.log,v=new WritableStream({write(e){return nn(this,void 0,void 0,function*(){const t=yield m.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3),n=new lt({destinationIdentities:d,value:{case:"streamChunk",value:new Ft({content:t,streamId:c,chunkIndex:Wo(p)})}});yield g.sendDataPacket(n,ut.RELIABLE),p+=1,i+=t.byteLength}}finally{t()}})},close(){return nn(this,void 0,void 0,function*(){const e=new jt({streamId:c}),t=new lt({destinationIdentities:d,value:{case:"streamTrailer",value:e}});yield g.sendDataPacket(t,ut.RELIABLE)})},abort(e){f.error("Sink error:",e)}});return new ja(v,l)})}}class $a extends lo{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Ps.Muted:Ps.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Ps.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return nn(this,void 0,void 0,function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),oa)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(Ps.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Va extends $a{constructor(e,t,i,n,s,o){super(e,t,lo.Kind.Audio,i,o),this.monitorReceiver=()=>nn(this,void 0,void 0,function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ra(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Eo()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Eo())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return nn(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(bo(t))return t.setSinkId(e)}))})}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&bo(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(Ps.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(Ps.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return nn(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})}),e})}}class qa extends $a{constructor(e,t,i,n,s){super(e,t,lo.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>nn(this,void 0,void 0,function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ra(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=jr(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===lo.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?ho(this._mediaStreamTrack,t):uo(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){const t=new Ha(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter(t=>t===e);for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return nn(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach(e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)}),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(t=>t.element===e);for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return nn(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const n=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),s=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,o=this.elementInfos.some(e=>e.pictureInPicture),r=this.elementInfos.some(e=>e.visible)&&!s||o;(this.lastVisible!==r||e)&&(!r&&Date.now()-n<100?js.setTimeout(()=>{this.updateVisibility()},100):(this.lastVisible=r,this.emit(Ps.VisibilityChanged,r,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,o=e.height()*s;t+o>i+n&&(i=t,n=o)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Ps.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return Oo();if(!t){return Oo()>2?2:1}return t}}class Ha{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=za(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=za(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=za(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Wa(e),this.isPiP=wo()&&za(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Wa(this.element),this.isPiP=za(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Uo().observe(this.element),No().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=Uo())||void 0===e||e.unobserve(this.element),null===(t=No())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function za(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Wa(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Wa(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const o=e.offsetWidth,r=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+r>i.pageYOffset&&s+o>i.pageXOffset&&!a&&"none"!==c}class Ga extends cn.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=ot.NONE,this.log=Qi,this.handleMuted=()=>{this.emit(Ps.Muted)},this.handleUnmuted=()=>{this.emit(Ps.Unmuted)},this.log=Xi(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:Ji.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=lo.Source.Unknown}setTrack(e){this.track&&(this.track.off(Ps.Muted,this.handleMuted),this.track.off(Ps.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Ps.Muted,this.handleMuted),e.on(Ps.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),so(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ot.NONE}get audioTrack(){if(Ko(this.track))return this.track}get videoTrack(){if(Jo(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=lo.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===lo.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}!function(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(Ga||(Ga={}));class Ka extends Ga{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Ps.Ended)},this.handleCpuConstrained=()=>{this.track&&Jo(this.track)&&this.emit(Ps.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(Ps.Ended,this.handleTrackEnded),this.track.off(Ps.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(Ps.Ended,this.handleTrackEnded),e.on(Ps.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 nn(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()})}unmute(){return nn(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()})}pauseUpstream(){return nn(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()})}resumeUpstream(){return nn(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ko(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Qe.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Qe.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Qe.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Qe.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(Qe.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Qe.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function Ja(e,t){return nn(this,void 0,void 0,function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:o}=oo(e);let r=o.audio,a=o.video;if(n&&"object"==typeof o.audio&&(o.audio.processor=n),s&&"object"==typeof o.video&&(o.video.processor=s),e.audio&&"object"==typeof o.audio&&"string"==typeof o.audio.deviceId){const e=o.audio.deviceId;o.audio.deviceId={exact:e},i=!0,r=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&"object"==typeof o.video&&"string"==typeof o.video.deviceId){const e=o.video.deviceId;o.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}!0===o.audio?o.audio={deviceId:"default"}:"object"==typeof o.audio&&null!==o.audio&&(o.audio=Object.assign(Object.assign({},o.audio),{deviceId:o.audio.deviceId||"default"})),!0===o.video?o.video={deviceId:"default"}:"object"!=typeof o.video||o.video.deviceId||(o.video.deviceId="default");const c=Js(o,Jr,Yr),d=Qs(c),l=navigator.mediaDevices.getUserMedia(d);o.audio&&(fr.userMediaPromiseMap.set("audioinput",l),l.catch(()=>fr.userMediaPromiseMap.delete("audioinput"))),o.video&&(fr.userMediaPromiseMap.set("videoinput",l),l.catch(()=>fr.userMediaPromiseMap.delete("videoinput")));try{const e=yield l;return yield Promise.all(e.getTracks().map(i=>nn(this,void 0,void 0,function*(){const o="audio"===i.kind;let r,a=o?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=o?d.audio:d.video;"boolean"!=typeof l&&(r=l);const u=i.getSettings().deviceId;(null==r?void 0:r.deviceId)&&Vo(r.deviceId)!==u?r.deviceId=u:r||(r={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new ua(e,t,!1,void 0,i);case"video":return new Ca(e,t,!1,i);default:throw new As("unsupported track type: ".concat(e.kind))}}(i,r,t);return h.kind===lo.Kind.Video?h.source=lo.Source.Camera:h.kind===lo.Kind.Audio&&(h.source=lo.Source.Microphone),h.mediaStream=e,Ko(h)&&n?yield h.setProcessor(n):Jo(h)&&s&&(yield h.setProcessor(s)),h})))}catch(n){if(!i)throw n;return Ja(Object.assign(Object.assign({},e),{audio:r,video:a}),t)}})}function Ya(e){return nn(this,void 0,void 0,function*(){return(yield Ja({audio:null==e||e,video:!1}))[0]})}var Qa,Xa;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(Qa||(Qa={}));class Za extends cn.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===nt.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===it.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,o){let r=arguments.length>6&&void 0!==arguments[6]?arguments[6]:nt.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Qa.Unknown,this.log=Qi,this.log=Xi(null!==(a=null==o?void 0:o.loggerName)&&void 0!==a?a:Ji.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=r,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new $o,this.once(xs.Active,()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(lo.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(lo.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(lo.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===it.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==it.ACTIVE&&this.emit(xs.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(xs.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(xs.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const o of n)e[o]!==t[o]&&(s[o]=null!==(i=t[o])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(xs.AttributesChanged,t)}setPermissions(e){var t,i,n,s,o,r;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null===(r=this.permissions)||void 0===r?void 0:r.canSubscribeMetrics);return this.permissions=e,c&&this.emit(xs.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(xs.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case We.EXCELLENT:return Qa.Excellent;case We.GOOD:return Qa.Good;case We.POOR:return Qa.Poor;case We.LOST:return Qa.Lost;default:return Qa.Unknown}}(e),t!==this._connectionQuality&&this.emit(xs.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Ko(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(Ps.Muted,()=>{this.emit(xs.TrackMuted,e)}),e.on(Ps.Unmuted,()=>{this.emit(xs.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case lo.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case lo.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class ec extends Za{constructor(e,t,i,n,s,o){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=ot.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new $o)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,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===(o=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===o||o.call(s,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new $o),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Ni.OK&&s.reject(new Ls(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=ia.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Si({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),so(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),so(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),so(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),so(t))),this.emit(xs.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>nn(this,void 0,void 0,function*(){var t,i,n,s,o;if(!(null===(o=this.roomOptions)||void 0===o?void 0:o.dynacast))return;const r=this.videoTrackPublications.get(e.trackSid);if(!r)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!r.videoTrack)return;const a=yield r.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=on(a);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;qs(e)&&(this.log.debug("publish ".concat(e," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),so(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,e,r.options))}}catch(e){i={error:e}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>nn(this,void 0,void 0,function*(){if(e.source===lo.Source.ScreenShare||e.source===lo.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),so(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Qo(e)||Yo(e))try{if(wo())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===lo.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),so(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),so(e))),Qo(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),so(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==ot.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(Rs.RemoteMute,(e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(Rs.Connected,this.handleReconnected).on(Rs.SignalConnected,this.handleSignalConnected).on(Rs.SignalRestarted,this.handleReconnected).on(Rs.SignalResumed,this.handleReconnected).on(Rs.Restarting,this.handleReconnecting).on(Rs.Resuming,this.handleReconnecting).on(Rs.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Rs.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Rs.Closing,this.handleClosing).on(Rs.SignalRequestResponse,this.handleSignalRequestResponse).on(Rs.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return nn(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return nn(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return nn(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return nn(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new ms((e,o)=>nn(t,void 0,void 0,function*(){var t,r;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(r=null!=n?n:this.name)&&void 0!==r?r:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{o(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]})))return this.pendingSignalRequests.delete(c),void e();yield mo(50)}o(new Ls("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error?o(e):o(new Error(String(e)))}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(lo.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(lo.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(lo.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return nn(this,void 0,void 0,function*(){this.encryptionType=e?ot.GCM:ot.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,n){return nn(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t)if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case lo.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case lo.Source.Microphone:t=yield this.createTracks({audio:null===(o=i)||void 0===o||o});break;case lo.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new As(e)}}catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(xs.MediaDevicesError,i,to(e)),this.pendingPublishing.delete(e),i}for(const n of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===lo.Source.Microphone&&Ko(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{const e=[];for(const i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),so(i))),e.push(this.publishTrack(i,n));const i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e)&&(r=yield this.waitForPendingPublicationOfSource(e),r||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),r&&r.track)if(e===lo.Source.ScreenShare){r=yield this.unpublishTrack(r.track);const e=this.getTrackPublication(lo.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r})}enableCameraAndMicrophone(){return nn(this,void 0,void 0,function*(){if(!this.pendingPublishing.has(lo.Source.Camera)&&!this.pendingPublishing.has(lo.Source.Microphone)){this.pendingPublishing.add(lo.Source.Camera),this.pendingPublishing.add(lo.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(lo.Source.Camera),this.pendingPublishing.delete(lo.Source.Microphone)}}})}createTracks(e){return nn(this,void 0,void 0,function*(){var t,i;null!=e||(e={});const n=Js(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const e=yield Ja(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return e.map(e=>(Ko(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=lo.Source.Microphone,this.emit(xs.AudioStreamAcquired)),Jo(e)&&(this.cameraError=void 0,e.source=lo.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return nn(this,void 0,void 0,function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Os("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=vs();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&Ao(e.osVersion,"17")>=0}()||(e.resolution=Ks.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=So()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new As("no video track found");const s=new Ca(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=lo.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(xs.AudioStreamAcquired);const e=new ua(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=lo.Source.ScreenShareAudio,o.push(e)}return o})}publishTrack(e,t){return nn(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return nn(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,o,r,a;let c,d;if(Qo(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),Go(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case lo.Source.Microphone:t="audioinput";break;case lo.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new ua(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new Ca(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new As("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(d=t)}),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),so(d))),d;const l=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),u="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,h=null!==(o=l.forceStereo)&&void 0!==o?o:u;h&&(void 0===l.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),so(e))),void 0===l.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=l.dtx)&&void 0!==r||(l.dtx=!1),null!==(a=l.red)&&void 0!==a||(l.red=!1)),!function(){const e=vs(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Ao(e.osVersion,t)>=0)||"Safari"===e.name&&Ao(e.version,t)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const p=new Promise((t,n)=>nn(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Sr.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:so(e)}));let i=!1;const s=setTimeout(()=>{i=!0,e.stop(),n(new Ns("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(s),i)return;const o=yield this.publish(e,l,h);t(o)}else try{const i=yield this.publish(e,l,h);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new $o),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),so(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map(e=>function(e){switch(e){case He.CAMERA:return lo.Source.Camera;case He.MICROPHONE:return lo.Source.Microphone;case He.SCREEN_SHARE:return lo.Source.ScreenShare;case He.SCREEN_SHARE_AUDIO:return lo.Source.ScreenShareAudio;default:return lo.Source.Unknown}}(e)).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),so(e))),!1)}publish(e,t,i){return nn(this,void 0,void 0,function*(){var n,s,o,r,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new Ns("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>Go(e)&&t.source===e.source)&&e.source!==lo.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),so(e))),t.stopMicTrackOnMute&&Ko(e)&&(e.stopOnMute=!0),e.source===lo.Source.ScreenShare&&yo()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(So()||yo())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(yo())return!1;if(So()){const e=vs();if((null==e?void 0:e.version)&&Ao(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&Ao(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/vp9"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=Gr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===io(e.mime))||(t.videoCodec=io(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Ps.Muted,this.onTrackMuted),e.on(Ps.Unmuted,this.onTrackUnmuted),e.on(Ps.Ended,this.handleTrackEnded),e.on(Ps.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Ps.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Ps.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(n=t.dtx)||void 0===n||n),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(Qe.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(Qe.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(Qe.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(Qe.TF_STEREO),g&&m.push(Qe.TF_NO_DTX),Qo(e)&&e.hasPreConnectBuffer&&m.push(Qe.TF_PRECONNECT_BUFFER);const v=new Gt({cid:e.mediaStreamTrack.id,name:t.name,type:lo.kindToProto(e.kind),muted:e.isMuted,source:lo.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m});let b;if(e.kind===lo.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(t){const n=null!==(r=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==r?r:Ws.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),so(e)),{dims:i}))}v.width=i.width,v.height=i.height,Yo(e)&&(vo(p)&&(e.source===lo.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),so(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),v.simulcastCodecs=[new Wt({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:Gr}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===ot.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new Wt({codec:t.backupCodec.codec,cid:""})))),b=ba(e.source===lo.Source.ScreenShare,v.width,v.height,t),v.layers=xa(v.width,v.height,b,vo(t.videoCodec))}else e.kind===lo.Kind.Audio&&(b=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ms("cannot publish track when not connected");const y=()=>nn(this,void 0,void 0,function*(){var i,n,s;if(!this.engine.pcManager)throw new Ms("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(xs.LocalSenderCreated,e.sender,e),Yo(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===lo.Source.ScreenShare||e.constraints.height&&Vo(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),b)if(yo()&&e.kind===lo.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=b[0])||void 0===n?void 0:n.maxBitrate)?b[0].maxBitrate/1e3:0})}else e.codec&&vo(e.codec)&&(null===(s=b[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let k;const S=new Promise((t,i)=>nn(this,void 0,void 0,function*(){var n;try{k=yield this.engine.addTrack(v),t(k)}catch(t){e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),so(e)),{error:t}))})),i(t)}}));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([S,y()]);k=e[0]}else{let i;if(k=yield S,k.codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===lo.Kind.Video){const n=io(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),so(e)),{codec:n})),t.videoCodec=n,b=ba(e.source===lo.Source.ScreenShare,v.width,v.height,t))}yield y()}const T=new Ka(e.kind,k,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(T.on(Ps.CpuConstrained,e=>this.onTrackCpuConstrained(e,T)),T.options=t,e.sid=k.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:k})),Yo(e)?e.startMonitor(this.engine.client):Qo(e)&&e.startMonitor(),this.addTrackPublication(T),this.emit(xs.LocalTrackPublished,T),Qo(e)&&k.audioFeatures.includes(Qe.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();if(this.on(xs.LocalTrackSubscribed,t=>{if(t.trackSid===k.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),so(e))),e.stopPreConnectBuffer()}}),t){const n=new Promise((n,s)=>nn(this,void 0,void 0,function*(){var o,r,a,c,d,l;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),so(e)));const m=setTimeout(()=>{s(new Error("agent not active within 10 seconds"))},1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),so(e)));const v=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:T.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=on(t);!(o=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){r={error:e}}finally{try{h||o||!(a=p.return)||(yield a.call(p))}finally{if(r)throw r.error}}yield v.close(),n()}catch(e){s(e)}}));n.then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),so(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),so(e)),{error:t}))})}}return T})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return nn(this,void 0,void 0,function*(){var n;if(this.encryptionType!==ot.NONE)return;let s;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(s=t)}),!s)throw new As("track is not published");if(!Yo(e))throw new As("track is not a video track");const o=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),r=function(e,t,i){var n,s,o,r;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Qi.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(o=a.height)&&void 0!==o?o:null===(r=e.dimensions)||void 0===r?void 0:r.height;return e.source===lo.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),ba(e.source===lo.Source.ScreenShare,c,d,i)}(e,t,o);if(!r)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),so(e)));const a=e.addSimulcastTrack(t,r);if(!a)return;const c=new Gt({cid:a.mediaStreamTrack.id,type:lo.kindToProto(e.kind),muted:e.isMuted,source:lo.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=xa(c.width,c.height,r),!this.engine||this.engine.isClosed)throw new Ms("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>nn(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,o,r),yield this.engine.negotiate()}))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:r,trackInfo:d}))})}unpublishTrack(e,t){return nn(this,void 0,void 0,function*(){var i,n;if(Go(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),so(e))),yield t)}const s=this.getPublicationForTrack(e),o=s?so(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));(e=s.track).off(Ps.Muted,this.onTrackMuted),e.off(Ps.Unmuted,this.onTrackUnmuted),e.off(Ps.Ended,this.handleTrackEnded),e.off(Ps.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Ps.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Ps.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let r=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Zr.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",r=!0);if(this.engine.removeTrack(a)&&(r=!0),Yo(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(r=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:e}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case lo.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case lo.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(xs.LocalTrackUnpublished,s),s.setTrack(void 0),r&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return nn(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return nn(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new ms((n,s)=>nn(t,void 0,void 0,function*(){try{const t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>nn(this,void 0,void 0,function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===lo.Source.ScreenShare||t.source===lo.Source.ScreenShareAudio||!Qo(t)&&!Yo(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),n()}catch(e){e instanceof Error?s(e):s(new Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return nn(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?ut.RELIABLE:ut.LOSSY,s=i.destinationIdentities,o=i.topic;let r=new ft({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:o});const a=new lt({kind:n,value:{case:"user",value:r}});yield t.engine.sendDataPacket(a,n)}()})}publishDtmf(e,t){return nn(this,void 0,void 0,function*(){const i=new lt({kind:ut.RELIABLE,value:{case:"sipDtmf",value:new vt({code:e,digit:t})}});yield this.engine.sendDataPacket(i,ut.RELIABLE)})}sendChatMessage(e,t){return nn(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new lt({value:{case:"chatMessage",value:new kt(Object.assign(Object.assign({},i),{timestamp:x.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,ut.RELIABLE),this.emit(xs.ChatMessage,i),i})}editChatMessage(e,t){return nn(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new lt({value:{case:"chatMessage",value:new kt(Object.assign(Object.assign({},i),{timestamp:x.parse(i.timestamp),editTimestamp:x.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,ut.RELIABLE),this.emit(xs.ChatMessage,i),i})}sendText(e,t){return nn(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return nn(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return nn(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return nn(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:n,responseTimeout:s=15e3}=e;return new ms((e,o)=>nn(this,void 0,void 0,function*(){var r,a,c,d;if(na(n)>15360)return void o(ia.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(r=this.engine.latestJoinResponse)||void 0===r?void 0:r.serverInfo)||void 0===a?void 0:a.version)&&Ao(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(ia.builtIn("UNSUPPORTED_SERVER"));const l=Math.max(s,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(t,u,i,n,l);const h=setTimeout(()=>{this.pendingAcks.delete(u),o(ia.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)},7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:t});const p=setTimeout(()=>{this.pendingResponses.delete(u),o(ia.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(u,{resolve:(t,i)=>{clearTimeout(p),this.pendingAcks.has(u)&&(this.log.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),i?o(i):e(null!=t?t:"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return nn(this,void 0,void 0,function*(){const o=new lt({destinationIdentities:[e],kind:ut.RELIABLE,value:{case:"rpcRequest",value:new St({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,ut.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,ia.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),so(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}}),!0)}setActiveAgent(e){var t,i,n,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(s=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new $o),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(Qo(n)||Yo(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return nn(this,void 0,void 0,function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield mo(20)}})}}class tc extends Ga{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Ps.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new ii({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Et({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Ps.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Ga.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ga.SubscriptionStatus.Subscribed:Ga.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ga.PermissionStatus.Allowed:Ga.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.requestedDisabled!==!e&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)===e.height||(er(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&er(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:co.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(Ps.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Ps.VisibilityChanged,this.handleVisibilityChange),n.off(Ps.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Ps.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Ps.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Ps.VisibilityChanged,this.handleVisibilityChange),e.on(Ps.Ended,this.handleEnded),this.emit(Ps.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Ps.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Ps.Muted:Ps.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Ps.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Ps.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return er(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ni({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===lo.Kind.Video){let s=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(s){ro(this.videoDimensionsAdaptiveStream,s)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(t=this.trackInfo,i=this.requestedMaxQuality,null===(n=t.layers)||void 0===n?void 0:n.find(e=>e.quality===i));e&&ro(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream;s?(e.width=Math.ceil(s.width),e.height=Math.ceil(s.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:co.HIGH})),e.quality=co.HIGH)}var t,i,n;this.emit(Ps.UpdateSettings,e)}}class ic extends Za{static fromParticipantInfo(e,t,i){return new ic(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,o,r){super(t,i||"",n,s,o,r,arguments.length>7&&void 0!==arguments[7]?arguments[7]:nt.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Ps.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),so(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(Ps.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(Ps.SubscriptionPermissionChanged,t=>{this.emit(xs.TrackSubscriptionPermissionChanged,e,t)}),e.on(Ps.SubscriptionStatusChanged,t=>{this.emit(xs.TrackSubscriptionStatusChanged,e,t)}),e.on(Ps.Subscribed,t=>{this.emit(xs.TrackSubscribed,t,e)}),e.on(Ps.Unsubscribed,t=>{this.emit(xs.TrackUnsubscribed,t,e)}),e.on(Ps.SubscriptionFailed,t=>{this.emit(xs.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:lo.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:lo.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,o){let r=this.getTrackPublicationBySid(t);if(r||t.startsWith("TR")||this.trackPublications.forEach(t=>{r||e.kind!==t.kind.toString()||(r=t)}),!r)return 0===o?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(xs.TrackSubscriptionFailed,t)):(void 0===o&&(o=20),void setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,s,o-1)},150));if("ended"===e.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),so(r))),void this.emit(xs.TrackSubscriptionFailed,t);let a;return a="video"===e.kind?new qa(e,t,n,s):new Va(e,t,n,this.audioContext,this.audioOutput),a.source=r.source,a.isMuted=r.isMuted,a.setMediaStream(i),a.start(),r.setTrack(a),this.volumeMap.has(r.source)&&Xo(a)&&Ko(a)&&a.setVolume(this.volumeMap.get(r.source)),r}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,s;let o=this.getTrackPublicationBySid(e.sid);if(o)o.updateInfo(e);else{const t=lo.kindFromProto(e.type);if(!t)return;o=new tc(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),o.updateInfo(e),i.set(e.sid,o);const r=Array.from(this.trackPublications.values()).find(e=>e.source===(null==o?void 0:o.source));r&&o.source!==lo.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:so(r),newTrack:so(o)})),this.addTrackPublication(o)}t.set(e.sid,o)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),so(e))),this.unpublishTrack(e.trackSid,!0))}),i.forEach(e=>{this.emit(xs.TrackPublished,e)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case lo.Kind.Audio:this.audioTrackPublications.delete(e);break;case lo.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(xs.TrackUnpublished,i)}setAudioOutput(e){return nn(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var n;Ko(i.track)&&Xo(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(Xa||(Xa={}));class nc extends cn.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,o,r;if(super(),t=this,this.state=Xa.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=(e,t,i)=>nn(this,void 0,void 0,function*(){var n;if("undefined"==typeof RTCPeerConnection||!go()&&!fo())throw Eo()?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===Xa.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(Xa.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==ir(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),xo(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new ta(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));const o=(n,r,a)=>nn(this,void 0,void 0,function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{if(yield mr.getInstance().getBackOffPromise(e),l.signal.aborted)throw Is.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=a?a:e,t,i,l),this.abortController=void 0,n()}catch(t){if(this.regionUrlProvider&&t instanceof Is&&t.reason!==Ts.Cancelled&&t.reason!==Ts.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof Is&&(401===e.status||e.reason===Ts.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void r(e)}[Ts.InternalError,Ts.ServerUnreachable,Ts.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),mr.getInstance().addFailedConnectionAttempt(e)),i&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield o(n,r,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ho(t)),r(t))}else{let e=Ke.UNKNOWN_REASON;t instanceof Is&&(e=Ho(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),r(t)}}}),r=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new $o((e,t)=>{o(e,t,r)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,s,o)=>nn(this,void 0,void 0,function*(){var r,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},o.signal,!s.singlePeerConnection);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null===(r=d.room)||void 0===r?void 0:r.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new _s("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d}),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>nn(this,void 0,void 0,function*(){var s,o;this.state===Xa.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Xr),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Es.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=n.signal.aborted?Is.cancelled("Signal connection aborted"):Is.serverUnreachable("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof Is&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:e})),t}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),Is.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}wo()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),wo()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Xa.Connected),this.emit(Es.Connected),mr.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return nn(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s;const o=yield e.disconnectLock.lock();try{if(e.state===Xa.Disconnected)return void e.log.debug("already disconnected",e.logContext);if(e.log.info("disconnect from room",Object.assign({},e.logContext)),e.state===Xa.Connecting||e.state===Xa.Reconnecting||e.isResuming){const t="Abort connection attempt due to user initiated disconnect";e.log.warn(t,e.logContext),null===(i=e.abortController)||void 0===i||i.abort(t),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,Is.cancelled("Client initiated disconnect")),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,Ke.CLIENT_INITIATED),e.engine=void 0}finally{o()}}()})},this.onPageLeave=()=>nn(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>nn(this,void 0,void 0,function*(){const e=[],t=vs();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=Bo();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(Es.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>nn(this,void 0,void 0,function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Xa.Reconnecting)&&this.emit(Es.Reconnecting)},this.handleSignalRestarted=e=>nn(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(Xa.Connected),this.emit(Es.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===it.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(Es.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach(e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});const i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(Es.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=lo.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(xs.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Es.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i,n)=>{this.emit(Es.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(xs.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit(Es.SipDTMFReceived,t,e),null==e||e.emit(xs.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map(e=>{let{id:i,text:n,language:s,startTime:o,endTime:r,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(r.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}})}(t,this.transcriptionReceivedTimes);null==n||n.emit(Ps.TranscriptionReceived,s),null==i||i.emit(xs.TranscriptionReceived,s,n),this.emit(Es.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(Es.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(Es.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Es.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Es.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Es.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Es.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>nn(this,void 0,void 0,function*(){var e;"iOS"!==(null===(e=vs())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit(Es.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Es.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Es.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(Es.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Es.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Es.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Es.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Es.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>nn(this,void 0,void 0,function*(){var t,i,n,s,o,r;if(null===(t=e.track)||void 0===t||t.on(Ps.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(Ps.Restarted,this.onLocalTrackRestarted),null===(o=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===o||o.call(s,this),this.emit(Es.LocalTrackPublished,e,this.localParticipant),Qo(e.track)){(yield e.track.checkForSilence())&&this.emit(Es.LocalAudioSilenceDetected,e)}const a=yield null===(r=e.track)||void 0===r?void 0:r.getDeviceId(!1),c=to(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(Es.ActiveDeviceChanged,c,a))}),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(Ps.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(Ps.Restarted,this.onLocalTrackRestarted),this.emit(Es.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>nn(this,void 0,void 0,function*(){const t=yield e.getDeviceId(!1),i=to(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(Es.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(Es.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(Es.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Es.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Es.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Qr),e),this.log=Xi(null!==(i=this.options.loggerName)&&void 0!==i?i:Ji.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Jr),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Yr),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Kr),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new La,this.outgoingDataStreamManager=new Ba(this.engine,this.log),this.disconnectLock=new s,this.localParticipant=new ec("","",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",Vo(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Vo(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Vo(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),wo()){const e=new AbortController;null===(r=null===(o=navigator.mediaDevices)||void 0===o?void 0:o.addEventListener)||void 0===r||r.call(o,"devicechange",this.handleDeviceChange,{signal:e.signal}),nc.cleanupRegistry&&nc.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return nn(this,void 0,void 0,function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)})}setupE2EE(){var e;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new pr(i,t),this.e2eeManager.on(cr.ParticipantEncryptionStatusChanged,(e,t)=>{(function(e){return e.isLocal})(t)&&(this.isE2EEEnabled=e),this.emit(Es.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(cr.EncryptionError,(e,t)=>{const i=t?this.getParticipantByIdentity(t):void 0;this.emit(Es.EncryptionError,e,i)}),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return this.state===Xa.Disconnected?ms.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?ms.resolve(this.roomInfo.sid):new ms((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(Rs.RoomUpdate,i),e(t.sid))};this.engine.on(Rs.RoomUpdate,i),this.once(Es.Disconnected,()=>{this.engine.off(Rs.RoomUpdate,i),t(new Ms("Room disconnected before room server id was available"))})})}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Aa(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Rs.ParticipantUpdate,this.handleParticipantUpdates).on(Rs.RoomUpdate,this.handleRoomUpdate).on(Rs.SpeakersChanged,this.handleSpeakersChanged).on(Rs.StreamStateChanged,this.handleStreamStateUpdate).on(Rs.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Rs.SubscriptionError,this.handleSubscriptionError).on(Rs.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Rs.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(Rs.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(Rs.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Rs.DataPacketReceived,this.handleDataPacket).on(Rs.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Xa.SignalReconnecting)&&this.emit(Es.SignalReconnecting)}).on(Rs.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Xa.Connected)&&this.emit(Es.Reconnected)}).on(Rs.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Xa.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(Rs.Restarting,this.handleRestarting).on(Rs.SignalRestarted,this.handleSignalRestarted).on(Rs.Offline,()=>{this.setAndEmitConnectionState(Xa.Reconnecting)&&this.emit(Es.Reconnecting)}).on(Rs.DCBufferStatusChanged,(e,t)=>{this.emit(Es.DCBufferStatusChanged,e,t)}).on(Rs.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});t?(this.localParticipant.emit(xs.LocalTrackSubscribed,t),this.emitWhenConnected(Es.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)}).on(Rs.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(Es.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return fr.getInstance().getDevices(e,t)}prepareConnection(e,t){return nn(this,void 0,void 0,function*(){if(this.state===Xa.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(xo(new URL(e))&&t){this.regionUrlProvider=new ta(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Xa.Disconnected&&(this.regionUrl=i,yield fetch(qo(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(qo(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return nn(this,void 0,void 0,function*(){let i,n=()=>nn(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Pi({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Pi({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Pi({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Pi({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=()=>nn(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new Pi({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>nn(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new Pi({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 Pi({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>nn(this,void 0,void 0,function*(){const e=this.engine.client.onLeave;e&&e(new ri({reason:Ke.CLIENT_INITIATED,action:ai.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Pi({scenario:{case:"subscriberBandwidth",value:Wo(t)}});break;case"leave-full-reconnect":i=new Pi({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return nn(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,o,r,a,c,d,l;let u=!0,h=!1;const p=n?{exact:t}:t;if("audioinput"===e){h=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===lo.Source.Microphone);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}const o=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&o&&(h=!0)}else if("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;const t=null!==(o=i.getActiveDevice(e))&&void 0!==o?o:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===lo.Source.Camera);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}const s=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&s&&(h=!0)}else if("audiooutput"===e){if(h=!0,!bo()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!==(r=yield fr.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==r?r:""),null!==(a=(l=i.options).audioOutput)&&void 0!==a||(l.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return h&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(Es.ActiveDeviceChanged,e,t)),u}()})}setupLocalParticipantEvents(){this.localParticipant.on(xs.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(xs.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(xs.AttributesChanged,this.onLocalAttributesChanged).on(xs.TrackMuted,this.onLocalTrackMuted).on(xs.TrackUnmuted,this.onLocalTrackUnmuted).on(xs.LocalTrackPublished,this.onLocalTrackPublished).on(xs.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(xs.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(xs.MediaDevicesError,this.onMediaDevicesError).on(xs.AudioStreamAcquired,this.startAudio).on(xs.ChatMessage,this.onLocalChatMessageSent).on(xs.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Xa.Connecting||this.state===Xa.Reconnecting){const n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,i),s()},s=()=>{this.off(Es.Reconnected,n),this.off(Es.Connected,n),this.off(Es.Disconnected,s)};return this.once(Es.Reconnected,n),this.once(Es.Connected,n),void this.once(Es.Disconnected,s)}if(this.state===Xa.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let o=n[1],r=e.id;if(o&&o.startsWith("TR")&&(r=o),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find(e=>e.sid===s);if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);if(!r.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s),this.logContext);r=e}let c;r.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(o,", trackId: ").concat(r),Object.assign(Object.assign({},this.logContext),{rpID:s,streamId:o,trackId:r})),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=a.addSubscribedMediaTrack(e,r,t,i,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit(Es.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i,n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Xa.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()}),this.localParticipant.off(xs.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(xs.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(xs.AttributesChanged,this.onLocalAttributesChanged).off(xs.TrackMuted,this.onLocalTrackMuted).off(xs.TrackUnmuted,this.onLocalTrackUnmuted).off(xs.LocalTrackPublished,this.onLocalTrackPublished).off(xs.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(xs.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(xs.MediaDevicesError,this.onMediaDevicesError).off(xs.AudioStreamAcquired,this.startAudio).off(xs.ChatMessage,this.onLocalChatMessageSent).off(xs.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),wo()&&(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(Xa.Disconnected),this.emit(Es.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(Es.ParticipantDisconnected,t),t.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,n,s,o){return nn(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==o)return void(yield this.engine.publishRpcResponse(e,t,null,ia.builtIn("UNSUPPORTED_VERSION")));const r=this.rpcHandlers.get(i);if(!r)return void(yield this.engine.publishRpcResponse(e,t,null,ia.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const o=yield r({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});na(o)>15360?(a=ia.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=o}catch(e){e instanceof ia?a=e:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),a=ia.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}selectDefaultDevices(){return nn(this,void 0,void 0,function*(){var e,t,i;const n=fr.getInstance().previousDevices,s=yield fr.getInstance().getDevices(void 0,!1),o=vs();if("Chrome"===(null==o?void 0:o.name)&&"iOS"!==o.os)for(let e of s){const t=n.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(Es.ActiveDeviceChanged,e.kind,e.deviceId)}const r=["audiooutput","audioinput","videoinput"];for(let o of r){const r=eo(o),a=this.localParticipant.getTrackPublication(r);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter(e=>e.kind===o),d=this.getActiveDevice(o);d===(null===(t=n.filter(e=>e.kind===o)[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(o,c[0].deviceId):"audioinput"===o&&!To()||"videoinput"===o||!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(o))||"audiooutput"===o&&To()||(yield this.switchActiveDevice(o,c[0].deviceId))}})}acquireAudioContext(){return nn(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=Zs())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),mo(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Es.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?ic.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new ic(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);if(t){i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity)}return i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Es.ParticipantConnected,i),i.on(xs.TrackPublished,e=>{this.emitWhenConnected(Es.TrackPublished,e,i)}).on(xs.TrackSubscribed,(e,t)=>{e.kind===lo.Kind.Audio?(e.on(Ps.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Ps.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===lo.Kind.Video&&(e.on(Ps.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Ps.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Es.TrackSubscribed,e,t,i)}).on(xs.TrackUnpublished,e=>{this.emit(Es.TrackUnpublished,e,i)}).on(xs.TrackUnsubscribed,(e,t)=>{this.emit(Es.TrackUnsubscribed,e,t,i)}).on(xs.TrackMuted,e=>{this.emitWhenConnected(Es.TrackMuted,e,i)}).on(xs.TrackUnmuted,e=>{this.emitWhenConnected(Es.TrackUnmuted,e,i)}).on(xs.ParticipantMetadataChanged,e=>{this.emitWhenConnected(Es.ParticipantMetadataChanged,e,i)}).on(xs.ParticipantNameChanged,e=>{this.emitWhenConnected(Es.ParticipantNameChanged,e,i)}).on(xs.AttributesChanged,e=>{this.emitWhenConnected(Es.ParticipantAttributesChanged,e,i)}).on(xs.ConnectionQualityChanged,e=>{this.emitWhenConnected(Es.ConnectionQualityChanged,e,i)}).on(xs.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(Es.ParticipantPermissionsChanged,e,i)}).on(xs.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(Es.TrackSubscriptionStatusChanged,e,t,i)}).on(xs.TrackSubscriptionFailed,(e,t)=>{this.emit(Es.TrackSubscriptionFailed,e,i,t)}).on(xs.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(Es.TrackSubscriptionPermissionChanged,e,t,i)}).on(xs.Active,()=>{this.emitWhenConnected(Es.ParticipantActive,i),i.kind===nt.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Zo(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=js.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ke.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&js.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Es.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===Xa.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Xa.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return nn(this,void 0,void 0,function*(){var t,i,n,s;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Xe({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 tt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Es.SignalConnected),this.emit(Es.Connected),this.setAndEmitConnectionState(Xa.Connected),o.video){const e=new Ka(lo.Kind.Video,new at({source:He.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:qe.AUDIO,name:"video-dummy"}),new Ca(o.useRealTracks&&(null===(t=window.navigator.mediaDevices)||void 0===t?void 0:t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Fo(160*(null!==(i=r.aspectRatios[0])&&void 0!==i?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(xs.LocalTrackPublished,e)}if(o.audio){const e=new Ka(lo.Kind.Audio,new at({source:He.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:qe.AUDIO}),new ua(o.useRealTracks&&(null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Bo(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(xs.LocalTrackPublished,e)}for(let e=0;e<r.count-1;e+=1){let t=new tt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:it.ACTIVE,tracks:[],joinedAt:x.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(r.video){const n=Fo(160*(null!==(s=r.aspectRatios[e%r.aspectRatios.length])&&void 0!==s?s:1),160,!1,!0),o=new at({source:He.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:qe.AUDIO});i.addSubscribedMediaTrack(n,o.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(r.audio){const e=Bo(),n=new at({source:He.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:qe.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==Es.ActiveSpeakersChanged&&e!==Es.TranscriptionReceived){const t=sc(i).filter(e=>void 0!==e);e!==Es.TrackSubscribed&&e!==Es.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function sc(e){return e.map(e=>{if(e)return Array.isArray(e)?sc(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e})}var oc;nc.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(oc||(oc={}));cn.EventEmitter;cn.EventEmitter;function rc(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}new TextEncoder,new TextDecoder;class ac extends Error{constructor(e,t){var i;super(e,t),rc(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}rc(ac,"code","ERR_JOSE_GENERIC");rc(class extends ac{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),rc(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),rc(this,"claim",void 0),rc(this,"reason",void 0),rc(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");rc(class extends ac{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),rc(this,"code","ERR_JWT_EXPIRED"),rc(this,"claim",void 0),rc(this,"reason",void 0),rc(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_EXPIRED");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");rc(class extends ac{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),rc(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");rc(class extends ac{constructor(){super(...arguments),rc(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");rc(class extends ac{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),rc(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");rc(class extends ac{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),rc(this,Symbol.asyncIterator,void 0),rc(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");rc(class extends ac{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),rc(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");rc(class extends ac{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),rc(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const cc="undefined"!=typeof process&&process.env?.SPEECHOS_HOST||"https://app.speechos.ai",dc={apiKey:"",userId:"",host:cc,debug:!1,webSocketFactory:void 0,settingsToken:void 0};let lc={...dc};function uc(){return{...lc}}function hc(e){lc=function(e){if(!e.apiKey)throw new Error("SpeechOS requires an apiKey. Get one from your team dashboard at /a/.");return{apiKey:e.apiKey,userId:e.userId??dc.userId,host:e.host??dc.host,debug:e.debug??dc.debug,webSocketFactory:e.webSocketFactory??dc.webSocketFactory,settingsToken:e.settingsToken??dc.settingsToken}}(e)}function pc(){return lc.settingsToken}const mc="speechos_anonymous_id";const gc=new class{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{const i=this.listeners.get(e);i&&(i.delete(t),0===i.size&&this.listeners.delete(e))}}once(e,t){const i=this.on(e,e=>{i(),t(e)});return i}emit(e,t){const i=this.listeners.get(e);i&&i.forEach(i=>{try{i(t)}catch(t){console.error(`Error in event listener for "${String(e)}":`,t)}})}clear(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){return this.listeners.get(e)?.size??0}},fc={isVisible:!1,isExpanded:!1,isConnected:!1,isMicEnabled:!1,activeAction:null,focusedElement:null,recordingState:"idle",errorMessage:null};const vc=new class{state;subscribers=new Set;snapshot;constructor(e){this.state={...e},this.snapshot=Object.freeze({...this.state})}getState(){return this.snapshot}setState(e){const t=this.snapshot;this.state={...this.state,...e},this.snapshot=Object.freeze({...this.state}),this.subscribers.forEach(e=>{try{e(this.snapshot,t)}catch(e){console.error("Error in state change callback:",e)}}),gc.emit("state:change",{state:this.snapshot})}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}reset(){const e=this.snapshot;this.state={...fc},this.snapshot=Object.freeze({...this.state}),this.subscribers.forEach(t=>{try{t(this.snapshot,e)}catch(e){console.error("Error in state change callback:",e)}}),gc.emit("state:change",{state:this.snapshot})}show(){this.setState({isVisible:!0}),gc.emit("widget:show",void 0)}hide(){this.setState({isVisible:!1,isExpanded:!1,activeAction:null}),gc.emit("widget:hide",void 0)}toggleExpanded(){this.setState({isExpanded:!this.state.isExpanded})}setFocusedElement(e){this.setState({focusedElement:e})}setActiveAction(e){this.setState({activeAction:e})}setRecordingState(e){this.setState({recordingState:e})}setConnected(e){this.setState({isConnected:e})}setMicEnabled(e){this.setState({isMicEnabled:e})}startRecording(){this.setState({recordingState:"connecting",isExpanded:!1})}stopRecording(){this.setState({recordingState:"processing",isMicEnabled:!1})}completeRecording(){this.setState({recordingState:"idle",activeAction:null,isConnected:!1,isMicEnabled:!1,isExpanded:!1})}cancelRecording(){this.setState({recordingState:"idle",activeAction:null,errorMessage:null,isConnected:!1,isMicEnabled:!1})}setError(e){this.setState({recordingState:"error",errorMessage:e})}clearError(){this.setState({recordingState:"idle",errorMessage:null})}}(fc),bc=24e4;var yc=class{promise;_resolve;_reject;_timeoutId=null;_settled=!1;constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}setTimeout(e,t,i,n){this._timeoutId=setTimeout(()=>{this._settled||(console.error(`[SpeechOS] Error: ${t} (${i})`),gc.emit("error",{code:i,message:t,source:n}),this.reject(new Error(t)))},e)}resolve(e){this._settled||(this._settled=!0,this.clearTimeout(),this._resolve(e))}reject(e){this._settled||(this._settled=!0,this.clearTimeout(),this._reject(e))}clearTimeout(){null!==this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=null)}get isSettled(){return this._settled}};const kc=new class{room=null;tokenData=null;micTrack=null;cachedTokenData=null;tokenCacheTimestamp=null;tokenPrefetchPromise=null;tokenRefreshTimer=null;autoRefreshEnabled=!1;pendingTranscript=null;pendingEditText=null;pendingCommand=null;pendingTrackSubscribed=null;editOriginalText=null;sessionSettings={};isCachedTokenValid(){if(!this.cachedTokenData||!this.tokenCacheTimestamp)return!1;return Date.now()-this.tokenCacheTimestamp<bc}async prefetchToken(){const e=uc();return this.isCachedTokenValid()&&this.cachedTokenData?(e.debug&&console.log("[SpeechOS] Using cached token (prefetch hit)"),this.cachedTokenData):this.tokenPrefetchPromise?(e.debug&&console.log("[SpeechOS] Prefetch already in progress, awaiting..."),this.tokenPrefetchPromise):(e.debug&&console.log("[SpeechOS] Starting token prefetch..."),this.tokenPrefetchPromise=this.fetchTokenFromServer().then(e=>(this.cachedTokenData=e,this.tokenCacheTimestamp=Date.now(),this.tokenPrefetchPromise=null,e)).catch(e=>{throw this.tokenPrefetchPromise=null,e}),this.tokenPrefetchPromise)}async fetchToken(){const e=uc();if(this.isCachedTokenValid()&&this.cachedTokenData)return e.debug&&console.log("[SpeechOS] Using cached token"),this.tokenData=this.cachedTokenData,this.cachedTokenData;if(this.tokenPrefetchPromise){e.debug&&console.log("[SpeechOS] Waiting for prefetch to complete...");const t=await this.tokenPrefetchPromise;return this.tokenData=t,t}const t=await this.fetchTokenFromServer();return this.cachedTokenData=t,this.tokenCacheTimestamp=Date.now(),this.tokenData=t,t}async fetchTokenFromServer(){const e=uc(),t=`${e.host}/livekit/api/token/`,i=this.sessionSettings,n=i.inputLanguageCode??"en-US",s=i.outputLanguageCode??"en-US",o=i.smartFormat??!0,r=i.vocabulary??[],a=i.snippets??[];e.debug&&(console.log("[SpeechOS] Fetching LiveKit token from:",t),console.log("[SpeechOS] Session settings:",{inputLanguage:n,outputLanguage:s,smartFormat:o,snippetsCount:a.length,vocabularyCount:r.length}));const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...e.apiKey?{Authorization:`Api-Key ${e.apiKey}`}:{}},body:JSON.stringify({user_id:e.userId||null,input_language:n,output_language:s,smart_format:o,custom_vocabulary:r,custom_snippets:a})});if(!c.ok)throw new Error(`Failed to fetch LiveKit token: ${c.status} ${c.statusText}`);const d=await c.json();return e.debug&&console.log("[SpeechOS] LiveKit token received:",{room:d.room,identity:d.identity,ws_url:d.ws_url}),d}async connect(){const e=uc();if(await this.fetchToken(),!this.tokenData)throw new Error("No token available for LiveKit connection");return this.room=new nc({adaptiveStream:!0,dynacast:!0}),this.setupRoomEvents(),e.debug&&console.log("[SpeechOS] Connecting to LiveKit room:",this.tokenData.room),await this.room.connect(this.tokenData.ws_url,this.tokenData.token),vc.setConnected(!0),e.debug&&console.log("[SpeechOS] Connected to LiveKit room:",this.room.name),this.room}async waitUntilReady(){if(!this.room||"connected"!==this.room.state)throw new Error("Not connected to room");return this.pendingTrackSubscribed||(this.pendingTrackSubscribed=new yc,this.pendingTrackSubscribed.setTimeout(15e3,"Connection timed out - agent not available","connection_timeout","connection")),this.pendingTrackSubscribed.promise}setupRoomEvents(){if(!this.room)return;const e=uc();this.room.on(Es.Connected,()=>{e.debug&&console.log("[SpeechOS] Room connected"),vc.setConnected(!0)}),this.room.on(Es.Disconnected,t=>{e.debug&&console.log("[SpeechOS] Room disconnected:",t),vc.setConnected(!1),vc.setMicEnabled(!1)}),this.room.on(Es.ParticipantConnected,t=>{e.debug&&console.log("[SpeechOS] Participant connected:",t.identity)}),this.room.on(Es.LocalTrackSubscribed,t=>{e.debug&&console.log("[SpeechOS] LocalTrackSubscribed event fired:",t.trackSid),this.pendingTrackSubscribed&&(this.pendingTrackSubscribed.resolve(),this.pendingTrackSubscribed=null)}),this.room.on(Es.LocalTrackPublished,t=>{e.debug&&console.log("[SpeechOS] LocalTrackPublished:",t.trackSid,t.source)}),this.room.on(Es.DataReceived,(e,t)=>{this.handleDataMessage(e,t)})}handleDataMessage(e,t){const i=uc();try{const t=JSON.parse((new TextDecoder).decode(e));if(i.debug&&console.log("[SpeechOS] Data received:",t),"transcript"===t.type){const e=t.transcript||"";i.debug&&console.log("[SpeechOS] Transcript received:",e),gc.emit("transcription:complete",{text:e}),this.pendingTranscript&&(this.pendingTranscript.resolve(e),this.pendingTranscript=null)}else if("edited_text"===t.type){const e=t.text||"";i.debug&&console.log("[SpeechOS] Edited text received:",e),gc.emit("edit:complete",{text:e,originalText:this.editOriginalText||""}),this.pendingEditText&&(this.pendingEditText.resolve(e),this.pendingEditText=null),this.editOriginalText=null}else if("command_result"===t.type){const e=t.command||null;i.debug&&console.log("[SpeechOS] Command result received:",e),gc.emit("command:complete",{command:e}),this.pendingCommand&&(this.pendingCommand.resolve(e),this.pendingCommand=null)}else if("error"===t.type){const e=t,n=e.code||"server_error",s=e.message||"A server error occurred";console.error(`[SpeechOS] Error: ${s} (${n})`),i.debug&&e.details&&console.error("[SpeechOS] Error details:",e.details),gc.emit("error",{code:n,message:s,source:"server"});const o=new Error(s);this.pendingTranscript&&(this.pendingTranscript.reject(o),this.pendingTranscript=null),this.pendingEditText&&(this.pendingEditText.reject(o),this.pendingEditText=null),this.pendingCommand&&(this.pendingCommand.reject(o),this.pendingCommand=null)}}catch(e){console.error("[SpeechOS] Failed to parse data message:",e)}}async enableMicrophone(){if(!this.room||"connected"!==this.room.state)throw new Error("Not connected to room");const e=uc();if(!this.micTrack){e.debug&&console.log("[SpeechOS] Creating microphone track...");const t=this.sessionSettings.audioDeviceId,i={echoCancellation:!0,noiseSuppression:!0};t&&(i.deviceId={exact:t},e.debug&&console.log("[SpeechOS] Using audio device:",t));try{this.micTrack=await Ya(i)}catch(e){if(!(t&&e instanceof Error))throw e;console.warn("[SpeechOS] Selected audio device unavailable, falling back to default:",e.message),this.micTrack=await Ya({echoCancellation:!0,noiseSuppression:!0})}this.logMicrophoneInfo()}this.room.localParticipant.getTrackPublication(lo.Source.Microphone)||(await this.room.localParticipant.publishTrack(this.micTrack,{source:lo.Source.Microphone}),vc.setMicEnabled(!0),e.debug&&console.log("[SpeechOS] Microphone track published"))}logMicrophoneInfo(){if(!this.micTrack)return;const e=uc(),t=this.micTrack.mediaStreamTrack,i=t.getSettings();console.log("[SpeechOS] Microphone active:",{deviceId:i.deviceId||"unknown",label:t.label||"Unknown device",sampleRate:i.sampleRate,channelCount:i.channelCount,echoCancellation:i.echoCancellation,noiseSuppression:i.noiseSuppression}),e.debug&&console.log("[SpeechOS] Full audio track settings:",i)}async disableMicrophone(){const e=uc();if(this.micTrack){if(e.debug&&console.log("[SpeechOS] Disabling microphone track..."),"connected"===this.room?.state)try{await this.room.localParticipant.unpublishTrack(this.micTrack),e.debug&&console.log("[SpeechOS] Microphone track unpublished")}catch(e){console.warn("[SpeechOS] Error unpublishing track:",e)}this.micTrack.stop(),this.micTrack.detach(),this.micTrack=null,vc.setMicEnabled(!1),e.debug&&console.log("[SpeechOS] Microphone track stopped and detached")}}async sendDataMessage(e){if(!this.room||"connected"!==this.room.state)throw new Error("Not connected to room");const t=(new TextEncoder).encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0,topic:"speechos"})}async startVoiceSession(e){const t=uc();if(t.debug&&console.log("[SpeechOS] Starting voice session..."),this.sessionSettings=e?.settings||{},await this.fetchToken(),!this.tokenData)throw new Error("No token available for LiveKit connection");this.pendingTrackSubscribed=new yc,this.pendingTrackSubscribed.setTimeout(15e3,"Connection timed out - agent not available","connection_timeout","connection"),this.room=new nc({adaptiveStream:!0,dynacast:!0}),this.setupRoomEvents(),t.debug&&console.log("[SpeechOS] Connecting to LiveKit room:",this.tokenData.room,"at",this.tokenData.ws_url),await this.room.connect(this.tokenData.ws_url,this.tokenData.token),t.debug&&console.log("[SpeechOS] Connected, enabling microphone with preConnectBuffer..."),await this.enableMicrophoneWithPreConnectBuffer(),e?.onMicReady&&e.onMicReady(),vc.setConnected(!0),t.debug&&console.log("[SpeechOS] Voice session ready - microphone active"),this.waitForAgentSubscription()}waitForAgentSubscription(){const e=uc();this.pendingTrackSubscribed&&this.pendingTrackSubscribed.promise.then(()=>{e.debug&&console.log("[SpeechOS] Agent subscribed to audio track - full duplex established"),this.pendingTrackSubscribed=null}).catch(e=>{console.warn("[SpeechOS] Agent subscription timeout:",e.message),this.pendingTrackSubscribed=null})}async enableMicrophoneWithPreConnectBuffer(){if(!this.room)throw new Error("Room not initialized");const e=uc(),t=this.sessionSettings.audioDeviceId,i={echoCancellation:!0,noiseSuppression:!0};t&&(i.deviceId={exact:t},e.debug&&console.log("[SpeechOS] Using audio device:",t));try{await this.room.localParticipant.setMicrophoneEnabled(!0,i,{preConnectBuffer:!0}),vc.setMicEnabled(!0);const t=this.room.localParticipant.getTrackPublication(lo.Source.Microphone);t?.track&&(this.micTrack=t.track,this.logMicrophoneInfo()),e.debug&&console.log("[SpeechOS] Microphone enabled with pre-connect buffer - audio is being captured")}catch(e){if(!(t&&e instanceof Error))throw e;console.warn("[SpeechOS] Selected audio device unavailable, falling back to default:",e.message),await this.room.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0},{preConnectBuffer:!0}),vc.setMicEnabled(!0)}}async stopVoiceSession(){const e=uc(),t=this.sessionSettings,i=t.inputLanguageCode??"en-US",n=t.outputLanguageCode??"en-US";console.log("[SpeechOS] Dictate command:",{inputLanguage:i,outputLanguage:n}),e.debug&&console.log("[SpeechOS] Stopping voice session, requesting transcript..."),await this.disableMicrophone(),e.debug&&console.log("[SpeechOS] Requesting transcript from agent..."),this.pendingTranscript=new yc,this.pendingTranscript.setTimeout(1e4,"Transcription timed out. Please try again.","transcription_timeout","timeout"),await this.sendDataMessage({type:"request_transcript"});const s=await this.pendingTranscript.promise;return this.pendingTranscript=null,s}async stopAndGetTranscript(){return this.stopVoiceSession()}async requestEditText(e){const t=uc(),i=this.sessionSettings,n=i.inputLanguageCode??"en-US",s=i.outputLanguageCode??"en-US";console.log("[SpeechOS] Edit command:",{inputLanguage:n,outputLanguage:s,originalTextLength:e.length}),t.debug&&console.log("[SpeechOS] Requesting text edit..."),this.editOriginalText=e,await this.disableMicrophone(),t.debug&&console.log("[SpeechOS] Sending edit_text request to agent..."),this.pendingEditText=new yc,this.pendingEditText.setTimeout(15e3,"Edit request timed out. Please try again.","edit_timeout","timeout"),await this.sendDataMessage({type:"edit_text",text:e});const o=await this.pendingEditText.promise;return this.pendingEditText=null,o}async stopAndEdit(e){return this.requestEditText(e)}async requestCommand(e){const t=uc(),i=this.sessionSettings.inputLanguageCode??"en-US";console.log("[SpeechOS] Command request:",{inputLanguage:i,commandCount:e.length}),t.debug&&console.log("[SpeechOS] Requesting command match..."),await this.disableMicrophone(),t.debug&&console.log("[SpeechOS] Sending execute_command request to agent..."),this.pendingCommand=new yc,this.pendingCommand.setTimeout(15e3,"Command request timed out. Please try again.","command_timeout","timeout"),await this.sendDataMessage({type:"execute_command",commands:e});const n=await this.pendingCommand.promise;return this.pendingCommand=null,n}async stopAndCommand(e){return this.requestCommand(e)}async disconnect(){const e=uc();e.debug&&console.log("[SpeechOS] Disconnecting from room..."),await this.disableMicrophone(),this.room&&(this.room.removeAllListeners(),await this.room.disconnect(),this.room=null,vc.setConnected(!1),e.debug&&console.log("[SpeechOS] Room disconnected and cleaned up")),this.pendingTranscript&&(this.pendingTranscript.reject(new Error("Disconnected")),this.pendingTranscript=null),this.pendingEditText&&(this.pendingEditText.reject(new Error("Disconnected")),this.pendingEditText=null),this.pendingCommand&&(this.pendingCommand.reject(new Error("Disconnected")),this.pendingCommand=null),this.pendingTrackSubscribed&&(this.pendingTrackSubscribed.reject(new Error("Disconnected")),this.pendingTrackSubscribed=null),this.tokenData=null,this.editOriginalText=null,this.sessionSettings={},e.debug&&console.log("[SpeechOS] Session state cleared")}invalidateTokenCache(){uc().debug&&console.log("[SpeechOS] Token cache invalidated"),this.cachedTokenData=null,this.tokenCacheTimestamp=null}startAutoRefresh(){const e=uc();this.autoRefreshEnabled=!0,e.debug&&console.log("[SpeechOS] Token auto-refresh enabled"),this.invalidateTokenCache(),this.prefetchToken().then(()=>{this.scheduleTokenRefresh()}).catch(t=>{e.debug&&console.warn("[SpeechOS] Failed to prefetch token after command:",t),this.autoRefreshEnabled&&(this.tokenRefreshTimer=setTimeout(()=>{this.performAutoRefresh()},5e3))})}stopAutoRefresh(){const e=uc();this.autoRefreshEnabled=!1,this.tokenRefreshTimer&&(clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null),e.debug&&console.log("[SpeechOS] Token auto-refresh disabled")}scheduleTokenRefresh(){if(!this.autoRefreshEnabled)return;this.tokenRefreshTimer&&(clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null);const e=uc();let t;if(this.tokenCacheTimestamp){const e=Date.now()-this.tokenCacheTimestamp,i=bc-e;t=Math.max(0,i-3e4)}else t=0;e.debug&&console.log(`[SpeechOS] Scheduling token refresh in ${Math.round(t/1e3)}s`),this.tokenRefreshTimer=setTimeout(()=>{this.performAutoRefresh()},t)}async performAutoRefresh(){if(!this.autoRefreshEnabled)return;const e=uc();if(this.isCachedTokenValid())return e.debug&&console.log("[SpeechOS] Token still valid on refresh check, rescheduling"),void this.scheduleTokenRefresh();e.debug&&console.log("[SpeechOS] Auto-refreshing token...");try{const t=await this.fetchTokenFromServer();this.cachedTokenData=t,this.tokenCacheTimestamp=Date.now(),e.debug&&console.log("[SpeechOS] Token auto-refreshed successfully"),this.scheduleTokenRefresh()}catch(e){console.warn("[SpeechOS] Token auto-refresh failed:",e),this.autoRefreshEnabled&&(this.tokenRefreshTimer=setTimeout(()=>{this.performAutoRefresh()},3e4))}}getRoom(){return this.room}getTokenData(){return this.tokenData}isConnected(){return"connected"===this.room?.state}isMicrophoneEnabled(){return null!==this.micTrack}};function Sc(){const e=navigator.userAgent.toLowerCase(),t=navigator.vendor?.toLowerCase()||"",i=e.includes("safari")&&!e.includes("chrome")&&!e.includes("chromium"),n=t.includes("apple");return i&&n}function Tc(){return Sc()?MediaRecorder.isTypeSupported("audio/mp4")?{mimeType:"audio/mp4",format:"mp4",needsEncodingParams:!1}:{mimeType:"",format:"mp4",needsEncodingParams:!0}:MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?{mimeType:"audio/webm;codecs=opus",format:"webm",needsEncodingParams:!1}:MediaRecorder.isTypeSupported("audio/webm")?{mimeType:"audio/webm",format:"webm",needsEncodingParams:!1}:MediaRecorder.isTypeSupported("audio/mp4")?{mimeType:"audio/mp4",format:"mp4",needsEncodingParams:!1}:{mimeType:"",format:"webm",needsEncodingParams:!0}}gc.on("settings:changed",()=>{kc.invalidateTokenCache()});var Cc=class e{mediaStream=null;recorder=null;buffer=[];isReady=!1;isRecording=!1;onChunk;audioFormat;deviceId;static TIME_SLICE_MS=100;static SAFARI_TIME_SLICE_MS=1e3;constructor(e,t){this.onChunk=e,this.audioFormat=Tc(),this.deviceId=t}getTimeSlice(){return Sc()?e.SAFARI_TIME_SLICE_MS:e.TIME_SLICE_MS}getTimeSliceMs(){return this.getTimeSlice()}getFormat(){return this.audioFormat}async start(){const e=uc();if(this.isRecording)return void(e.debug&&console.log("[SpeechOS] AudioCapture already recording"));this.buffer=[],this.isReady=!1;const t={audio:{echoCancellation:!0,noiseSuppression:!0,...this.deviceId?{deviceId:{exact:this.deviceId}}:{}}};e.debug&&(console.log("[SpeechOS] AudioCapture starting with format:",this.audioFormat.mimeType),console.log("[SpeechOS] Detected Safari:",Sc()),this.deviceId&&console.log("[SpeechOS] Using audio device:",this.deviceId));try{this.mediaStream=await navigator.mediaDevices.getUserMedia(t);const i={};this.audioFormat.mimeType&&(i.mimeType=this.audioFormat.mimeType),this.recorder=new MediaRecorder(this.mediaStream,i),this.recorder.ondataavailable=e=>{e.data&&e.data.size>0&&this.handleChunk(e.data)},this.recorder.onerror=e=>{console.error("[SpeechOS] MediaRecorder error:",e)};const n=this.getTimeSlice();this.recorder.start(n),this.isRecording=!0,e.debug&&console.log(`[SpeechOS] AudioCapture started with ${n}ms timeslice, buffering until ready`)}catch(e){if(!(this.deviceId&&e instanceof Error))throw e;{console.warn("[SpeechOS] Selected device unavailable, trying default:",e.message),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});const t={};this.audioFormat.mimeType&&(t.mimeType=this.audioFormat.mimeType),this.recorder=new MediaRecorder(this.mediaStream,t),this.recorder.ondataavailable=e=>{e.data&&e.data.size>0&&this.handleChunk(e.data)},this.recorder.start(this.getTimeSlice()),this.isRecording=!0}}}handleChunk(e){this.isReady?this.onChunk(e):this.buffer.push(e)}setReady(){const e=uc();if(this.isReady)return;const t=this.buffer;this.buffer=[];for(const e of t)this.onChunk(e);this.isReady=!0,e.debug&&console.log(`[SpeechOS] AudioCapture ready, flushed ${t.length} buffered chunks`)}async stop(){const e=uc(),t=Sc();if(this.recorder&&"inactive"!==this.recorder.state){if("recording"===this.recorder.state)try{const t=new Promise(t=>{const i=n=>{this.recorder?.removeEventListener("dataavailable",i),e.debug&&console.log(`[SpeechOS] requestData flush received: ${n.data.size} bytes`),t()};this.recorder?.addEventListener("dataavailable",i)});this.recorder.requestData(),e.debug&&console.log("[SpeechOS] Requested data flush before stop"),await t}catch(t){e.debug&&console.log("[SpeechOS] requestData() not supported or failed:",t)}const i=new Promise(t=>{this.recorder?this.recorder.onstop=()=>{e.debug&&console.log("[SpeechOS] MediaRecorder onstop fired"),t()}:t()});this.recorder.stop(),await i,t&&(e.debug&&console.log("[SpeechOS] Safari: waiting 2s for encoding pipeline to flush"),await new Promise(e=>setTimeout(e,2e3)))}if(this.mediaStream){for(const e of this.mediaStream.getTracks())e.stop();this.mediaStream=null}this.recorder=null,this.isRecording=!1,this.isReady=!1,this.buffer=[],e.debug&&console.log("[SpeechOS] AudioCapture stopped")}get recording(){return this.isRecording}get ready(){return this.isReady}get bufferedChunks(){return this.buffer.length}};const wc=15e3;var Ec=class{promise;_resolve;_reject;_timeoutId=null;_settled=!1;constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}setTimeout(e,t,i,n){this._timeoutId=setTimeout(()=>{this._settled||(console.error(`[SpeechOS] Error: ${t} (${i})`),gc.emit("error",{code:i,message:t,source:n}),this.reject(new Error(t)))},e)}resolve(e){this._settled||(this._settled=!0,this.clearTimeout(),this._resolve(e))}reject(e){this._settled||(this._settled=!0,this.clearTimeout(),this._reject(e))}clearTimeout(){null!==this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=null)}get isSettled(){return this._settled}};const xc=new class{ws=null;audioCapture=null;sessionId=null;pendingAuth=null;pendingTranscript=null;pendingEditText=null;pendingCommand=null;pendingAudioSends=new Set;editOriginalText=null;lastInputText=void 0;sessionAction="dictate";sessionInputText="";sessionCommands=[];sessionSettings={};getWebSocketUrl(){return`${(uc().host||"https://app.speechos.ai").replace(/^http/,"ws")}/ws/voice/`}async startVoiceSession(e){const t=uc();var i,n;this.sessionAction=e?.action||"dictate",this.sessionInputText=e?.inputText||"",this.sessionCommands=e?.commands||[],this.sessionSettings=e?.settings||{},"edit"===this.sessionAction&&(this.editOriginalText=this.sessionInputText),t.debug&&console.log("[SpeechOS] Starting WebSocket voice session..."),this.audioCapture=(i=e=>{this.sendAudioChunk(e)},n=this.sessionSettings.audioDeviceId,new Cc(i,n)),await this.audioCapture.start(),e?.onMicReady&&e.onMicReady(),vc.setMicEnabled(!0);const s=this.getWebSocketUrl();t.debug&&console.log("[SpeechOS] Connecting to WebSocket:",s),this.pendingAuth=new Ec,this.pendingAuth.setTimeout(wc,"Connection timed out","connection_timeout","connection");const o=t.webSocketFactory??(e=>new WebSocket(e));this.ws=o(s),this.ws.onopen=()=>{t.debug&&console.log("[SpeechOS] WebSocket connected, authenticating..."),this.authenticate()},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onerror=e=>{const t=3===this.ws?.readyState,i=t?"connection_blocked":"websocket_error",n=t?"This site's CSP blocks the extension. Try embedded mode instead.":"WebSocket connection error";console.error("[SpeechOS] WebSocket error:",e,{isConnectionBlocked:t}),gc.emit("error",{code:i,message:n,source:"connection"}),this.pendingAuth&&this.pendingAuth.reject(new Error(n))},this.ws.onclose=e=>{t.debug&&console.log("[SpeechOS] WebSocket closed:",e.code,e.reason),vc.setConnected(!1)},await this.pendingAuth.promise,this.pendingAuth=null,this.audioCapture&&this.audioCapture.setReady(),vc.setConnected(!0),t.debug&&console.log("[SpeechOS] WebSocket voice session ready")}authenticate(){const e=uc(),t=Tc(),i=this.sessionSettings,n=function(){if("undefined"==typeof localStorage)return crypto.randomUUID();let e=localStorage.getItem(mc);return e||(e=crypto.randomUUID(),localStorage.setItem(mc,e)),e}(),s={type:"auth",api_key:e.apiKey,user_id:e.userId||null,anonymous_id:n,input_language:i.inputLanguageCode??"en-US",output_language:i.outputLanguageCode??"en-US",smart_format:i.smartFormat??!0,custom_vocabulary:i.vocabulary??[],custom_snippets:i.snippets??[],audio_format:t.format,action:this.sessionAction,input_text:this.sessionInputText,commands:this.sessionCommands};e.debug&&console.log("[SpeechOS] Sending auth message with action:",this.sessionAction),this.ws?.send(JSON.stringify(s))}sendAudioChunk(e){const t=this.doSendAudioChunk(e);this.pendingAudioSends.add(t),t.finally(()=>{this.pendingAudioSends.delete(t)})}async doSendAudioChunk(e){if(this.ws&&1===this.ws.readyState){const t=await e.arrayBuffer();this.ws.send(t)}}handleMessage(e){const t=uc();try{const i=JSON.parse(e);switch(t.debug&&console.log("[SpeechOS] WebSocket message:",i),i.type){case"ready":this.handleReady(i);break;case"transcription":this.handleIntermediateTranscription(i);break;case"transcript":this.handleFinalTranscript(i);break;case"edited_text":this.handleEditedText(i);break;case"command_result":this.handleCommandResult(i);break;case"error":this.handleError(i);break;default:t.debug&&console.log("[SpeechOS] Unknown message type:",i.type)}}catch(e){console.error("[SpeechOS] Failed to parse message:",e)}}handleReady(e){const t=uc();this.sessionId=e.session_id,t.debug&&console.log("[SpeechOS] Session ready:",this.sessionId),this.pendingAuth&&this.pendingAuth.resolve()}handleIntermediateTranscription(e){const t=uc();gc.emit("transcription:interim",{transcript:e.transcript,isFinal:e.is_final}),t.debug&&console.log("[SpeechOS] Intermediate transcription:",e.transcript,"final:",e.is_final)}handleFinalTranscript(e){const t=e.transcript||"";gc.emit("transcription:complete",{text:t}),this.pendingTranscript&&(this.pendingTranscript.resolve(t),this.pendingTranscript=null)}handleEditedText(e){const t=e.text||"";gc.emit("edit:complete",{text:t,originalText:this.editOriginalText||""}),this.pendingEditText&&(this.pendingEditText.resolve(t),this.pendingEditText=null),this.editOriginalText=null}handleCommandResult(e){const t=e.command||null;this.lastInputText=e.transcript,gc.emit("command:complete",{command:t}),this.pendingCommand&&(this.pendingCommand.resolve(t),this.pendingCommand=null)}handleError(e){const t=e.code||"server_error",i=e.message||"A server error occurred";console.error(`[SpeechOS] Error: ${i} (${t})`),gc.emit("error",{code:t,message:i,source:"server"});const n=new Error(i);this.pendingAuth&&(this.pendingAuth.reject(n),this.pendingAuth=null),this.pendingTranscript&&(this.pendingTranscript.reject(n),this.pendingTranscript=null),this.pendingEditText&&(this.pendingEditText.reject(n),this.pendingEditText=null),this.pendingCommand&&(this.pendingCommand.reject(n),this.pendingCommand=null)}async stopVoiceSession(){uc().debug&&console.log("[SpeechOS] Stopping voice session, requesting transcript..."),await this.stopAudioCapture(),this.pendingTranscript=new Ec,this.pendingTranscript.setTimeout(wc,"Transcription timed out. Please try again.","transcription_timeout","timeout"),this.sendMessage({type:"request_transcript"});const e=await this.pendingTranscript.promise;return this.pendingTranscript=null,e}async requestEditText(e){uc().debug&&console.log("[SpeechOS] Requesting text edit..."),await this.stopAudioCapture(),this.pendingEditText=new Ec,this.pendingEditText.setTimeout(wc,"Edit request timed out. Please try again.","edit_timeout","timeout"),this.sendMessage({type:"edit_text"});const t=await this.pendingEditText.promise;return this.pendingEditText=null,t}async requestCommand(e){uc().debug&&console.log("[SpeechOS] Requesting command match..."),await this.stopAudioCapture(),this.pendingCommand=new Ec,this.pendingCommand.setTimeout(wc,"Command request timed out. Please try again.","command_timeout","timeout"),this.sendMessage({type:"execute_command"});const t=await this.pendingCommand.promise;return this.pendingCommand=null,t}async stopAudioCapture(){const e=uc(),t=Date.now();e.debug&&console.log("[SpeechOS] stopAudioCapture: starting..."),this.audioCapture&&(await this.audioCapture.stop(),this.audioCapture=null,e.debug&&console.log(`[SpeechOS] stopAudioCapture: recorder stopped after ${Date.now()-t}ms`)),vc.setMicEnabled(!1),this.pendingAudioSends.size>0?(e.debug&&console.log(`[SpeechOS] stopAudioCapture: waiting for ${this.pendingAudioSends.size} pending audio sends...`),await Promise.all(this.pendingAudioSends),e.debug&&console.log(`[SpeechOS] stopAudioCapture: all sends complete after ${Date.now()-t}ms`)):e.debug&&console.log("[SpeechOS] stopAudioCapture: no pending sends"),await this.waitForBufferDrain(),e.debug&&console.log(`[SpeechOS] stopAudioCapture: complete after ${Date.now()-t}ms`)}async waitForBufferDrain(){if(!this.ws||1!==this.ws.readyState)return;const e=uc(),t=Date.now();for(;this.ws.bufferedAmount>0;){if(Date.now()-t>5e3){console.warn(`[SpeechOS] Buffer drain timeout, ${this.ws.bufferedAmount} bytes still pending`);break}await new Promise(e=>setTimeout(e,50))}e.debug&&console.log(`[SpeechOS] Buffer drained in ${Date.now()-t}ms`)}sendMessage(e){this.ws&&1===this.ws.readyState&&this.ws.send(JSON.stringify(e))}async disconnect(){const e=uc();e.debug&&console.log("[SpeechOS] Disconnecting WebSocket..."),await this.stopAudioCapture(),this.ws&&(this.ws.close(),this.ws=null);const t=new Error("Disconnected");this.pendingAuth&&(this.pendingAuth.reject(t),this.pendingAuth=null),this.pendingTranscript&&(this.pendingTranscript.reject(t),this.pendingTranscript=null),this.pendingEditText&&(this.pendingEditText.reject(t),this.pendingEditText=null),this.pendingCommand&&(this.pendingCommand.reject(t),this.pendingCommand=null),this.sessionId=null,this.editOriginalText=null,this.lastInputText=void 0,this.sessionSettings={},vc.setConnected(!1),vc.setMicEnabled(!1),e.debug&&console.log("[SpeechOS] WebSocket disconnected")}isConnected(){return null!==this.ws&&1===this.ws.readyState}getLastInputText(){return this.lastInputText}},Rc={startVoiceSession:e=>xc.startVoiceSession(e),stopVoiceSession:()=>xc.stopVoiceSession(),requestEditText:e=>xc.requestEditText(e),requestCommand:e=>xc.requestCommand(e),disconnect:()=>xc.disconnect(),isConnected:()=>xc.isConnected(),getLastInputText:()=>xc.getLastInputText(),prefetchToken:()=>Promise.resolve({}),startAutoRefresh:()=>{},stopAutoRefresh:()=>{},invalidateTokenCache:()=>{}};function Pc(){return Rc}const Ic={commands:[],zIndex:999999,alwaysVisible:!1,useExternalSettings:!1};let Oc={...Ic};function Ac(e){Oc=function(e){const t={commands:e.commands??Ic.commands,zIndex:e.zIndex??Ic.zIndex,alwaysVisible:e.alwaysVisible??Ic.alwaysVisible,useExternalSettings:e.useExternalSettings??Ic.useExternalSettings};return("number"!=typeof t.zIndex||t.zIndex<0)&&(console.warn(`Invalid zIndex "${t.zIndex}". Using default ${Ic.zIndex}.`),t.zIndex=Ic.zIndex),t}(e)}function _c(){return{...Oc}}function Mc(){Oc={...Ic}}function Dc(){return Oc.alwaysVisible}function Nc(){return Oc.useExternalSettings}function Lc(e){if(!(e&&e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();if("input"===t||"textarea"===t){if("input"===t){const t=e.type.toLowerCase();if(["checkbox","radio","submit","button","reset","file","hidden"].includes(t))return!1}return!0}return!(!e.isContentEditable&&"true"!==e.getAttribute("contenteditable"))}class Uc{constructor(){this.isActive=!1,this.focusHandler=null,this.blurHandler=null,this.touchHandler=null,this.mouseDownHandler=null,this.isWidgetBeingInteracted=!1}start(){if(this.isActive)return void console.warn("FormDetector is already active");this.focusHandler=e=>{const t=e.target;Lc(t)&&(console.log("[SpeechOS] FormDetector: focus on form field",{element:t,tagName:t?.tagName}),vc.setFocusedElement(t),vc.show(),gc.emit("form:focus",{element:t}))},this.blurHandler=e=>{if(Lc(e.target)){if(this.isWidgetBeingInteracted)return void console.log("[SpeechOS] blurHandler: widget being interacted, skipping");const t=e.relatedTarget,i=document.querySelector("speechos-widget"),n=Lc(t),s=i&&(i.contains(t)||i.shadowRoot?.contains(t)||t===i),o=Boolean(t?.closest("[data-speechos-no-close]"));if(n||s||o)return void console.log("[SpeechOS] blurHandler: early return, not hiding");setTimeout(()=>{if(this.isWidgetBeingInteracted)return;const e=document.activeElement,t=i&&(i.contains(e)||i.shadowRoot?.contains(e)),n=Boolean(e?.closest("[data-speechos-no-close]"));Lc(e)||t||n||(vc.setFocusedElement(null),Dc()||vc.hide(),gc.emit("form:blur",{element:null}))},150)}};const e=(e,t)=>{const i=document.querySelector("speechos-widget");return i&&(t.includes(i)||i.contains(e)||i.shadowRoot?.contains(e))||!1};this.touchHandler=t=>{const i=t.target,n=t.composedPath?t.composedPath():[];e(i,n)&&(this.isWidgetBeingInteracted=!0,setTimeout(()=>{this.isWidgetBeingInteracted=!1},300))},this.mouseDownHandler=t=>{const i=t.target,n=t.composedPath?t.composedPath():[];e(i,n)&&(this.isWidgetBeingInteracted=!0,setTimeout(()=>{this.isWidgetBeingInteracted=!1},300))},document.addEventListener("focusin",this.focusHandler,!0),document.addEventListener("focusout",this.blurHandler,!0),document.addEventListener("touchstart",this.touchHandler,!0),document.addEventListener("mousedown",this.mouseDownHandler,!0),this.isActive=!0;const t=document.activeElement;Lc(t)&&(console.log("[SpeechOS] FormDetector: found initially focused form field",{element:t,tagName:t?.tagName}),vc.setFocusedElement(t),vc.show(),gc.emit("form:focus",{element:t}))}stop(){this.isActive&&(this.focusHandler&&(document.removeEventListener("focusin",this.focusHandler,!0),this.focusHandler=null),this.blurHandler&&(document.removeEventListener("focusout",this.blurHandler,!0),this.blurHandler=null),this.touchHandler&&(document.removeEventListener("touchstart",this.touchHandler,!0),this.touchHandler=null),this.mouseDownHandler&&(document.removeEventListener("mousedown",this.mouseDownHandler,!0),this.mouseDownHandler=null),this.isWidgetBeingInteracted=!1,vc.setFocusedElement(null),Dc()||vc.hide(),this.isActive=!1)}get active(){return this.isActive}}const Fc=new Uc;function jc(e){if("textarea"===e.tagName.toLowerCase())return!0;return["text","search","url","tel","password"].includes(e.type||"text")}class Bc{getSelection(e){const t=e.tagName.toLowerCase();if("input"===t||"textarea"===t){const t=e;if(jc(t)){const e=t.selectionStart,i=t.selectionEnd;return{start:e,end:i,text:null!==e&&null!==i&&e!==i?t.value.substring(e,i):""}}{const e=t.value.length;return{start:e,end:e,text:""}}}if(e.isContentEditable){const e=window.getSelection();if(e&&e.rangeCount>0){const t=e.toString();return{start:0,end:t.length,text:t}}return{start:null,end:null,text:""}}return{start:null,end:null,text:""}}getContent(e,t){const i=e.tagName.toLowerCase();if("input"===i||"textarea"===i){const i=e.value;if(t){const e=t.start??0,n=t.end??i.length;if(e!==n)return i.substring(e,n)}return i}if(e.isContentEditable){const t=window.getSelection();return t&&t.toString().length>0?t.toString():e.textContent||""}return""}insertText(e,t,i){const n=e.tagName.toLowerCase();if("input"===n||"textarea"===n){const n=e,s=i?.start??n.value.length,o=i?.end??n.value.length,r=n.value.substring(0,s),a=n.value.substring(o);if(n.value=r+t+a,jc(n)){const e=s+t.length;n.setSelectionRange(e,e)}n.dispatchEvent(new Event("input",{bubbles:!0})),n.focus(),vc.setFocusedElement(n)}else if(e.isContentEditable){e.focus(),vc.setFocusedElement(e);const i=document.createTextNode(t);e.appendChild(i);const n=window.getSelection();if(n){const e=document.createRange();e.selectNodeContents(i),e.collapse(!1),n.removeAllRanges(),n.addRange(e)}e.dispatchEvent(new Event("input",{bubbles:!0}))}gc.emit("transcription:inserted",{text:t,element:e})}replaceContent(e,t,i){const n=e.tagName.toLowerCase();if("input"===n||"textarea"===n){const n=e;if(n.focus(),jc(n)){const e=i?.start??0,s=i?.end??n.value.length;e!==s?n.setSelectionRange(e,s):n.setSelectionRange(0,n.value.length),document.execCommand("insertText",!1,t)}else n.value=t,n.dispatchEvent(new Event("input",{bubbles:!0}));vc.setFocusedElement(n)}else if(e.isContentEditable){e.focus(),vc.setFocusedElement(e);if(!(null!==i?.start&&null!==i?.end&&i?.start!==i?.end)){const t=window.getSelection(),i=document.createRange();i.selectNodeContents(e),t?.removeAllRanges(),t?.addRange(i)}document.execCommand("insertText",!1,t)}}}const $c=new Bc;let Vc=$c;function qc(e){Vc=e}function Hc(){Vc=$c}const zc="speechos_language_settings";let Wc=null;const Gc=[{name:"Belarusian",code:"be",variants:["be"]},{name:"Bengali",code:"bn",variants:["bn"]},{name:"Bosnian",code:"bs",variants:["bs"]},{name:"Bulgarian",code:"bg",variants:["bg"]},{name:"Catalan",code:"ca",variants:["ca"]},{name:"Croatian",code:"hr",variants:["hr"]},{name:"Czech",code:"cs",variants:["cs"]},{name:"Danish",code:"da",variants:["da","da-DK"]},{name:"Dutch",code:"nl",variants:["nl"]},{name:"English (Australia)",code:"en-AU",variants:["en-AU"]},{name:"English (India)",code:"en-IN",variants:["en-IN"]},{name:"English (New Zealand)",code:"en-NZ",variants:["en-NZ"]},{name:"English (UK)",code:"en-GB",variants:["en-GB"]},{name:"English (US)",code:"en-US",variants:["en","en-US"]},{name:"Estonian",code:"et",variants:["et"]},{name:"Finnish",code:"fi",variants:["fi"]},{name:"Flemish",code:"nl-BE",variants:["nl-BE"]},{name:"French",code:"fr",variants:["fr","fr-CA"]},{name:"German",code:"de",variants:["de"]},{name:"German (Switzerland)",code:"de-CH",variants:["de-CH"]},{name:"Greek",code:"el",variants:["el"]},{name:"Hindi",code:"hi",variants:["hi"]},{name:"Hungarian",code:"hu",variants:["hu"]},{name:"Indonesian",code:"id",variants:["id"]},{name:"Italian",code:"it",variants:["it"]},{name:"Japanese",code:"ja",variants:["ja"]},{name:"Kannada",code:"kn",variants:["kn"]},{name:"Korean",code:"ko",variants:["ko","ko-KR"]},{name:"Latvian",code:"lv",variants:["lv"]},{name:"Lithuanian",code:"lt",variants:["lt"]},{name:"Macedonian",code:"mk",variants:["mk"]},{name:"Malay",code:"ms",variants:["ms"]},{name:"Marathi",code:"mr",variants:["mr"]},{name:"Norwegian",code:"no",variants:["no"]},{name:"Polish",code:"pl",variants:["pl"]},{name:"Portuguese",code:"pt",variants:["pt","pt-BR","pt-PT"]},{name:"Romanian",code:"ro",variants:["ro"]},{name:"Russian",code:"ru",variants:["ru"]},{name:"Serbian",code:"sr",variants:["sr"]},{name:"Slovak",code:"sk",variants:["sk"]},{name:"Slovenian",code:"sl",variants:["sl"]},{name:"Spanish",code:"es",variants:["es","es-419"]},{name:"Swedish",code:"sv",variants:["sv","sv-SE"]},{name:"Tagalog",code:"tl",variants:["tl"]},{name:"Tamil",code:"ta",variants:["ta"]},{name:"Telugu",code:"te",variants:["te"]},{name:"Turkish",code:"tr",variants:["tr"]},{name:"Ukrainian",code:"uk",variants:["uk"]},{name:"Vietnamese",code:"vi",variants:["vi"]}],Kc={inputLanguageCode:"en-US",outputLanguageCode:"en-US",smartFormat:!0};function Jc(){if(null!==Wc)return{...Wc};try{const e=localStorage.getItem(zc);return e?{...Kc,...JSON.parse(e)}:{...Kc}}catch{return{...Kc}}}function Yc(e){Wc={...Kc,...e}}function Qc(e){Wc=e;try{localStorage.setItem(zc,JSON.stringify(e))}catch{}}function Xc(){return Jc().inputLanguageCode}function Zc(e){const t=Jc();t.inputLanguageCode!==e&&(t.inputLanguageCode=e,Qc(t),gc.emit("settings:changed",{setting:"language"}))}function ed(){return Jc().outputLanguageCode}function td(e){const t=Jc();t.outputLanguageCode!==e&&(t.outputLanguageCode=e,Qc(t),gc.emit("settings:changed",{setting:"language"}))}function id(e){return Gc.find(t=>t.code===e||t.variants.includes(e))}function nd(){const e=id(Xc());return e?.name||"English"}function sd(){const e=id(ed());return e?.name||"English"}function od(){return Jc().smartFormat}function rd(e){const t=Jc();t.smartFormat!==e&&(t.smartFormat=e,Qc(t),gc.emit("settings:changed",{setting:"smartFormat"}))}function ad(){return Xc()}function cd(e){Zc(e)}function dd(){return nd()}function ld(){Wc=null;try{localStorage.removeItem(zc)}catch{}}const ud={getLanguageSettings:Jc,setLanguageSettings:Yc,getInputLanguageCode:Xc,setInputLanguageCode:Zc,getOutputLanguageCode:ed,setOutputLanguageCode:td,getLanguageByCode:id,getInputLanguageName:nd,getOutputLanguageName:sd,getSmartFormatEnabled:od,setSmartFormatEnabled:rd,resetLanguageSettings:ld,resetMemoryCache:function(){Wc=null},SUPPORTED_LANGUAGES:Gc,getLanguageCode:ad,setLanguageCode:cd,getLanguageName:dd},hd="speechos_snippets",pd=25;let md=null;function gd(){if(null!==md)return[...md].sort((e,t)=>t.createdAt-e.createdAt);try{const e=localStorage.getItem(hd);if(!e)return[];return JSON.parse(e).sort((e,t)=>t.createdAt-e.createdAt)}catch{return[]}}function fd(e){md=e.slice(0,pd)}function vd(e){md=e;try{localStorage.setItem(hd,JSON.stringify(e))}catch{}}function bd(e,t,i){const n=e.trim();if(!n)return{field:"trigger",message:"Trigger phrase is required."};if(n.length>30)return{field:"trigger",message:"Trigger must be 30 characters or less."};const s=t.find(e=>e.trigger.toLowerCase()===n.toLowerCase()&&e.id!==i);return s?{field:"trigger",message:"This trigger phrase already exists."}:null}function yd(e){const t=e.trim();return t?t.length>300?{field:"expansion",message:"Expansion must be 300 characters or less."}:null:{field:"expansion",message:"Expansion text is required."}}function kd(e,t){const i=gd();if(i.length>=pd)return{success:!1,error:{field:"limit",message:"You've reached the 25 snippet limit. Delete unused snippets to add more."}};const n=bd(e,i);if(n)return{success:!1,error:n};const s=yd(t);if(s)return{success:!1,error:s};const o={id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,trigger:e.trim(),expansion:t.trim(),createdAt:Date.now()};return i.unshift(o),vd(i),gc.emit("settings:changed",{setting:"snippets"}),{success:!0,snippet:o}}function Sd(e,t,i){const n=gd(),s=n.findIndex(t=>t.id===e);if(-1===s)return{success:!1,error:{field:"trigger",message:"Snippet not found."}};const o=bd(t,n,e);if(o)return{success:!1,error:o};const r=yd(i);return r?{success:!1,error:r}:(n[s]={...n[s],trigger:t.trim(),expansion:i.trim()},vd(n),gc.emit("settings:changed",{setting:"snippets"}),{success:!0,snippet:n[s]})}function Td(e){const t=gd().filter(t=>t.id!==e);vd(t),gc.emit("settings:changed",{setting:"snippets"})}function Cd(){md=[];try{localStorage.removeItem(hd)}catch{}gc.emit("settings:changed",{setting:"snippets"})}function wd(){return{current:gd().length,max:pd}}function Ed(){return gd().length>=pd}const xd={getSnippets:gd,setSnippets:fd,addSnippet:kd,updateSnippet:Sd,deleteSnippet:Td,clearSnippets:Cd,getSnippetCount:wd,isAtSnippetLimit:Ed,resetMemoryCache:function(){md=null},MAX_SNIPPETS:pd,MAX_TRIGGER_LENGTH:30,MAX_EXPANSION_LENGTH:300},Rd="speechos_vocabulary",Pd=50;let Id=null;function Od(){if(null!==Id)return[...Id].sort((e,t)=>t.createdAt-e.createdAt);try{const e=localStorage.getItem(Rd);if(!e)return[];return JSON.parse(e).sort((e,t)=>t.createdAt-e.createdAt)}catch{return[]}}function Ad(e){Id=e.slice(0,Pd)}function _d(e){Id=e;try{localStorage.setItem(Rd,JSON.stringify(e))}catch{}}function Md(e){const t=Od();if(t.length>=Pd)return{success:!1,error:{field:"limit",message:"You've reached the 50 term limit. Remove unused terms to add more."}};const i=function(e,t){const i=e.trim();if(!i)return{field:"term",message:"Term is required."};if(i.length>50)return{field:"term",message:"Term must be 50 characters or less."};const n=t.find(e=>e.term.toLowerCase()===i.toLowerCase());return n?{field:"term",message:"This term is already in your vocabulary."}:null}(e,t);if(i)return{success:!1,error:i};const n={id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,term:e.trim(),createdAt:Date.now()};return t.unshift(n),_d(t),gc.emit("settings:changed",{setting:"vocabulary"}),{success:!0,term:n}}function Dd(e){const t=Od().filter(t=>t.id!==e);_d(t),gc.emit("settings:changed",{setting:"vocabulary"})}function Nd(){Id=[];try{localStorage.removeItem(Rd)}catch{}gc.emit("settings:changed",{setting:"vocabulary"})}function Ld(){return{current:Od().length,max:Pd}}function Ud(){return Od().length>=Pd}const Fd={getVocabulary:Od,setVocabulary:Ad,addTerm:Md,deleteTerm:Dd,clearVocabulary:Nd,getVocabularyCount:Ld,isAtVocabularyLimit:Ud,resetMemoryCache:function(){Id=null},MAX_TERMS:Pd,MAX_TERM_LENGTH:50},jd="speechos_audio_settings",Bd={deviceId:""};function $d(){try{const e=localStorage.getItem(jd);return e?{...Bd,...JSON.parse(e)}:{...Bd}}catch{return{...Bd}}}function Vd(){return $d().deviceId}function qd(e){const t=$d();t.deviceId=e,function(e){try{localStorage.setItem(jd,JSON.stringify(e))}catch{}}(t)}async function Hd(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(e=>"audioinput"===e.kind)}catch{return[]}}async function zd(){const e=Vd();if(!e)return!0;return(await Hd()).some(t=>t.deviceId===e)}function Wd(){try{localStorage.removeItem(jd)}catch{}}const Gd={getAudioSettings:$d,getAudioDeviceId:Vd,setAudioDeviceId:qd,getAudioInputDevices:Hd,isSelectedDeviceAvailable:zd,resetAudioSettings:Wd},Kd="speechos_transcripts";let Jd=null;function Yd(){if(null!==Jd)return[...Jd].sort((e,t)=>t.timestamp-e.timestamp);try{const e=localStorage.getItem(Kd);if(!e)return[];return JSON.parse(e).sort((e,t)=>t.timestamp-e.timestamp)}catch{return[]}}function Qd(e){Jd=e.slice(0,50)}function Xd(e,t,i){const n={id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,text:e,timestamp:Date.now(),action:t};if("edit"===t&&"string"==typeof i&&(n.originalText=i),"command"===t&&"object"==typeof i){const e=i;void 0!==e.inputText&&(n.inputText=e.inputText),void 0!==e.commandResult&&(n.commandResult=e.commandResult),void 0!==e.commandConfig&&(n.commandConfig=e.commandConfig)}const s=Yd();s.unshift(n);const o=s.slice(0,50);Jd=o;try{localStorage.setItem(Kd,JSON.stringify(o))}catch{}return gc.emit("settings:changed",{setting:"history"}),n}function Zd(){Jd=[];try{localStorage.removeItem(Kd)}catch{}gc.emit("settings:changed",{setting:"history"})}function el(e){const t=Yd().filter(t=>t.id!==e);Jd=t;try{localStorage.setItem(Kd,JSON.stringify(t))}catch{}gc.emit("settings:changed",{setting:"history"})}const tl={getTranscripts:Yd,setTranscripts:Qd,saveTranscript:Xd,clearTranscripts:Zd,deleteTranscript:el};const il=new class{constructor(){this.syncTimer=null,this.isSyncing=!1,this.retryCount=0,this.isInitialized=!1,this.unsubscribe=null,this.syncDisabled=!1}async doFetch(e,t){return uc().debug&&console.log("[SpeechOS] Using native fetch",t.method,e),fetch(e,t)}async init(){pc()&&(this.isInitialized||(this.isInitialized=!0,this.unsubscribe=gc.on("settings:changed",()=>{this.scheduleSyncToServer()}),await this.loadFromServer()))}destroy(){this.syncTimer&&(clearTimeout(this.syncTimer),this.syncTimer=null),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.isInitialized=!1,this.retryCount=0,this.syncDisabled=!1}async loadFromServer(){const e=pc();if(!e)return;const t=uc();try{const i=await this.doFetch(`${t.host}/api/user-settings/`,{method:"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(t.debug&&console.log("[SpeechOS] Settings fetch response:",i.status,i.ok?"OK":i.statusText),404===i.status)return t.debug&&console.log("[SpeechOS] No server settings found, syncing local to server"),void await this.syncToServer();if(401===i.status||403===i.status)return void this.handleTokenExpired();if(!i.ok)throw new Error(`Server returned ${i.status}`);const n=await i.json();t.debug&&(console.log("[SpeechOS] Settings received from server:",{language:n.language,vocabularyCount:n.vocabulary?.length??0,snippetsCount:n.snippets?.length??0,historyCount:n.history?.length??0,lastSyncedAt:n.lastSyncedAt}),n.history?.length>0&&console.log("[SpeechOS] History entries:",n.history)),this.mergeSettings(n),gc.emit("settings:loaded",void 0),t.debug&&console.log("[SpeechOS] Settings merged and loaded")}catch(e){const i=e instanceof Error?e.message:"Unknown error";this.isNetworkRestrictionError(e)?(this.syncDisabled=!0,t.debug&&console.log("[SpeechOS] Settings sync disabled (CSP/network restriction), using localStorage only")):t.debug&&console.warn("[SpeechOS] Failed to load settings from server:",i),gc.emit("settings:syncFailed",{error:i})}}mergeSettings(e){e.language&&Yc(e.language),e.vocabulary&&Ad(e.vocabulary),e.snippets&&fd(e.snippets),e.history&&Qd(e.history)}scheduleSyncToServer(){pc()&&!this.syncDisabled&&(this.syncTimer&&clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this.syncToServer()},2e3))}async syncToServer(){const e=pc();if(!e||this.isSyncing||this.syncDisabled)return;this.isSyncing=!0;const t=uc();try{const i=Jc(),n=Od(),s=gd(),o=Yd(),r={language:{inputLanguageCode:i.inputLanguageCode,outputLanguageCode:i.outputLanguageCode,smartFormat:i.smartFormat},vocabulary:n.map(e=>({id:e.id,term:e.term,createdAt:e.createdAt})),snippets:s.map(e=>({id:e.id,trigger:e.trigger,expansion:e.expansion,createdAt:e.createdAt})),history:o.map(e=>({id:e.id,text:e.text,timestamp:e.timestamp,action:e.action,...e.originalText&&{originalText:e.originalText},...e.inputText&&{inputText:e.inputText},...void 0!==e.commandResult&&{commandResult:e.commandResult}}))},a=await this.doFetch(`${t.host}/api/user-settings/`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(401===a.status||403===a.status)return void this.handleTokenExpired();if(!a.ok)throw new Error(`Server returned ${a.status}`);this.retryCount=0,gc.emit("settings:synced",void 0),t.debug&&console.log("[SpeechOS] Settings synced to server")}catch(e){const i=e instanceof Error?e.message:"Unknown error";this.isNetworkRestrictionError(e)?(this.syncDisabled=!0,t.debug&&console.log("[SpeechOS] Settings sync disabled (CSP/network restriction), using localStorage only"),gc.emit("settings:syncFailed",{error:i})):(t.debug&&console.warn("[SpeechOS] Failed to sync settings to server:",i),gc.emit("settings:syncFailed",{error:i}),this.scheduleRetry())}finally{this.isSyncing=!1}}scheduleRetry(){if(this.retryCount>=3){return uc().debug&&console.warn("[SpeechOS] Max retries reached, giving up sync"),void(this.retryCount=0)}this.retryCount++;const e=2e3*Math.pow(2,this.retryCount-1);this.syncTimer=setTimeout(()=>{this.syncToServer()},e)}isNetworkRestrictionError(e){if(e instanceof TypeError){const t=e.message.toLowerCase();return t.includes("failed to fetch")||t.includes("network request failed")||t.includes("content security policy")||t.includes("csp")||t.includes("blocked")}return!1}handleTokenExpired(){lc={...lc,settingsToken:void 0},gc.emit("settings:tokenExpired",void 0);uc().debug&&console.warn("[SpeechOS] Settings token expired")}isEnabled(){return!!pc()}};function nl(e,t,i,n){var s,o=arguments.length,r=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(s=e[a])&&(r=(o<3?s(r):o>3?s(t,i,r):s(t,i))||r);return o>3&&r&&Object.defineProperty(t,i,r),r}"function"==typeof SuppressedError&&SuppressedError;const sl=globalThis,ol=sl.ShadowRoot&&(void 0===sl.ShadyCSS||sl.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,rl=Symbol(),al=new WeakMap;let cl=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==rl)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(ol&&void 0===e){const i=void 0!==t&&1===t.length;i&&(e=al.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&al.set(t,e))}return e}toString(){return this.cssText}};const dl=(e,...t)=>{const i=1===e.length?e[0]:t.reduce((t,i,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[n+1],e[0]);return new cl(i,e,rl)},ll=ol?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return(e=>new cl("string"==typeof e?e:e+"",void 0,rl))(t)})(e):e,{is:ul,defineProperty:hl,getOwnPropertyDescriptor:pl,getOwnPropertyNames:ml,getOwnPropertySymbols:gl,getPrototypeOf:fl}=Object,vl=globalThis,bl=vl.trustedTypes,yl=bl?bl.emptyScript:"",kl=vl.reactiveElementPolyfillSupport,Sl=(e,t)=>e,Tl={toAttribute(e,t){switch(t){case Boolean:e=e?yl:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch(e){i=null}}return i}},Cl=(e,t)=>!ul(e,t),wl={attribute:!0,type:String,converter:Tl,reflect:!1,useDefault:!1,hasChanged:Cl};Symbol.metadata??=Symbol("metadata"),vl.litPropertyMetadata??=new WeakMap;let El=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=wl){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(e,i,t);void 0!==n&&hl(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){const{get:n,set:s}=pl(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const o=n?.call(this);s?.call(this,t),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??wl}static _$Ei(){if(this.hasOwnProperty(Sl("elementProperties")))return;const e=fl(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Sl("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Sl("properties"))){const e=this.properties,t=[...ml(e),...gl(e)];for(const i of t)this.createProperty(i,e[i])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const i=this._$Eu(e,t);void 0!==i&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const e of i)t.unshift(ll(e))}else void 0!==e&&t.push(ll(e));return t}static _$Eu(e,t){const i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(ol)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const i of t){const t=document.createElement("style"),n=sl.litNonce;void 0!==n&&t.setAttribute("nonce",n),t.textContent=i.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){const i=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,i);if(void 0!==n&&!0===i.reflect){const s=(void 0!==i.converter?.toAttribute?i.converter:Tl).toAttribute(t,i.type);this._$Em=e,null==s?this.removeAttribute(n):this.setAttribute(n,s),this._$Em=null}}_$AK(e,t){const i=this.constructor,n=i._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=i.getPropertyOptions(n),s="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:Tl;this._$Em=n;const o=s.fromAttribute(t,e.type);this[n]=o??this._$Ej?.get(n)??o,this._$Em=null}}requestUpdate(e,t,i,n=!1,s){if(void 0!==e){const o=this.constructor;if(!1===n&&(s=this[e]),i??=o.getPropertyOptions(e),!((i.hasChanged??Cl)(s,t)||i.useDefault&&i.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(o._$Eu(e,i))))return;this.C(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:n,wrapped:s},o){i&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,o??t??this[e]),!0!==s||void 0!==o)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,i]of e){const{wrapped:e}=i,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,i,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};El.elementStyles=[],El.shadowRootOptions={mode:"open"},El[Sl("elementProperties")]=new Map,El[Sl("finalized")]=new Map,kl?.({ReactiveElement:El}),(vl.reactiveElementVersions??=[]).push("2.1.2");const xl=globalThis,Rl=e=>e,Pl=xl.trustedTypes,Il=Pl?Pl.createPolicy("lit-html",{createHTML:e=>e}):void 0,Ol="$lit$",Al=`lit$${Math.random().toFixed(9).slice(2)}$`,_l="?"+Al,Ml=`<${_l}>`,Dl=document,Nl=()=>Dl.createComment(""),Ll=e=>null===e||"object"!=typeof e&&"function"!=typeof e,Ul=Array.isArray,Fl="[ \t\n\f\r]",jl=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Bl=/-->/g,$l=/>/g,Vl=RegExp(`>|${Fl}(?:([^\\s"'>=/]+)(${Fl}*=${Fl}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),ql=/'/g,Hl=/"/g,zl=/^(?:script|style|textarea|title)$/i,Wl=(e=>(t,...i)=>({_$litType$:e,strings:t,values:i}))(1),Gl=Symbol.for("lit-noChange"),Kl=Symbol.for("lit-nothing"),Jl=new WeakMap,Yl=Dl.createTreeWalker(Dl,129);function Ql(e,t){if(!Ul(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==Il?Il.createHTML(t):t}const Xl=(e,t)=>{const i=e.length-1,n=[];let s,o=2===t?"<svg>":3===t?"<math>":"",r=jl;for(let t=0;t<i;t++){const i=e[t];let a,c,d=-1,l=0;for(;l<i.length&&(r.lastIndex=l,c=r.exec(i),null!==c);)l=r.lastIndex,r===jl?"!--"===c[1]?r=Bl:void 0!==c[1]?r=$l:void 0!==c[2]?(zl.test(c[2])&&(s=RegExp("</"+c[2],"g")),r=Vl):void 0!==c[3]&&(r=Vl):r===Vl?">"===c[0]?(r=s??jl,d=-1):void 0===c[1]?d=-2:(d=r.lastIndex-c[2].length,a=c[1],r=void 0===c[3]?Vl:'"'===c[3]?Hl:ql):r===Hl||r===ql?r=Vl:r===Bl||r===$l?r=jl:(r=Vl,s=void 0);const u=r===Vl&&e[t+1].startsWith("/>")?" ":"";o+=r===jl?i+Ml:d>=0?(n.push(a),i.slice(0,d)+Ol+i.slice(d)+Al+u):i+Al+(-2===d?t:u)}return[Ql(e,o+(e[i]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),n]};class Zl{constructor({strings:e,_$litType$:t},i){let n;this.parts=[];let s=0,o=0;const r=e.length-1,a=this.parts,[c,d]=Xl(e,t);if(this.el=Zl.createElement(c,i),Yl.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(n=Yl.nextNode())&&a.length<r;){if(1===n.nodeType){if(n.hasAttributes())for(const e of n.getAttributeNames())if(e.endsWith(Ol)){const t=d[o++],i=n.getAttribute(e).split(Al),r=/([.?@])?(.*)/.exec(t);a.push({type:1,index:s,name:r[2],strings:i,ctor:"."===r[1]?su:"?"===r[1]?ou:"@"===r[1]?ru:nu}),n.removeAttribute(e)}else e.startsWith(Al)&&(a.push({type:6,index:s}),n.removeAttribute(e));if(zl.test(n.tagName)){const e=n.textContent.split(Al),t=e.length-1;if(t>0){n.textContent=Pl?Pl.emptyScript:"";for(let i=0;i<t;i++)n.append(e[i],Nl()),Yl.nextNode(),a.push({type:2,index:++s});n.append(e[t],Nl())}}}else if(8===n.nodeType)if(n.data===_l)a.push({type:2,index:s});else{let e=-1;for(;-1!==(e=n.data.indexOf(Al,e+1));)a.push({type:7,index:s}),e+=Al.length-1}s++}}static createElement(e,t){const i=Dl.createElement("template");return i.innerHTML=e,i}}function eu(e,t,i=e,n){if(t===Gl)return t;let s=void 0!==n?i._$Co?.[n]:i._$Cl;const o=Ll(t)?void 0:t._$litDirective$;return s?.constructor!==o&&(s?._$AO?.(!1),void 0===o?s=void 0:(s=new o(e),s._$AT(e,i,n)),void 0!==n?(i._$Co??=[])[n]=s:i._$Cl=s),void 0!==s&&(t=eu(e,s._$AS(e,t.values),s,n)),t}class tu{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,n=(e?.creationScope??Dl).importNode(t,!0);Yl.currentNode=n;let s=Yl.nextNode(),o=0,r=0,a=i[0];for(;void 0!==a;){if(o===a.index){let t;2===a.type?t=new iu(s,s.nextSibling,this,e):1===a.type?t=new a.ctor(s,a.name,a.strings,this,e):6===a.type&&(t=new au(s,this,e)),this._$AV.push(t),a=i[++r]}o!==a?.index&&(s=Yl.nextNode(),o++)}return Yl.currentNode=Dl,n}p(e){let t=0;for(const i of this._$AV)void 0!==i&&(void 0!==i.strings?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class iu{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,i,n){this.type=2,this._$AH=Kl,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=n,this._$Cv=n?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=eu(this,e,t),Ll(e)?e===Kl||null==e||""===e?(this._$AH!==Kl&&this._$AR(),this._$AH=Kl):e!==this._$AH&&e!==Gl&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>Ul(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==Kl&&Ll(this._$AH)?this._$AA.nextSibling.data=e:this.T(Dl.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:i}=e,n="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=Zl.createElement(Ql(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new tu(n,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=Jl.get(e.strings);return void 0===t&&Jl.set(e.strings,t=new Zl(e)),t}k(e){Ul(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,n=0;for(const s of e)n===t.length?t.push(i=new iu(this.O(Nl()),this.O(Nl()),this,this.options)):i=t[n],i._$AI(s),n++;n<t.length&&(this._$AR(i&&i._$AB.nextSibling,n),t.length=n)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){const t=Rl(e).nextSibling;Rl(e).remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}}class nu{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,n,s){this.type=1,this._$AH=Kl,this._$AN=void 0,this.element=e,this.name=t,this._$AM=n,this.options=s,i.length>2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Kl}_$AI(e,t=this,i,n){const s=this.strings;let o=!1;if(void 0===s)e=eu(this,e,t,0),o=!Ll(e)||e!==this._$AH&&e!==Gl,o&&(this._$AH=e);else{const n=e;let r,a;for(e=s[0],r=0;r<s.length-1;r++)a=eu(this,n[i+r],t,r),a===Gl&&(a=this._$AH[r]),o||=!Ll(a)||a!==this._$AH[r],a===Kl?e=Kl:e!==Kl&&(e+=(a??"")+s[r+1]),this._$AH[r]=a}o&&!n&&this.j(e)}j(e){e===Kl?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class su extends nu{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Kl?void 0:e}}class ou extends nu{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Kl)}}class ru extends nu{constructor(e,t,i,n,s){super(e,t,i,n,s),this.type=5}_$AI(e,t=this){if((e=eu(this,e,t,0)??Kl)===Gl)return;const i=this._$AH,n=e===Kl&&i!==Kl||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,s=e!==Kl&&(i===Kl||n);n&&this.element.removeEventListener(this.name,this,i),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}}class au{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){eu(this,e)}}const cu=xl.litHtmlPolyfillSupport;cu?.(Zl,iu),(xl.litHtmlVersions??=[]).push("3.3.2");const du=globalThis;let lu=class extends El{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,i)=>{const n=i?.renderBefore??t;let s=n._$litPart$;if(void 0===s){const e=i?.renderBefore??null;n._$litPart$=s=new iu(t.insertBefore(Nl(),e),e,void 0,i??{})}return s._$AI(e),s})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Gl}};lu._$litElement$=!0,lu.finalized=!0,du.litElementHydrateSupport?.({LitElement:lu});const uu=du.litElementPolyfillSupport;uu?.({LitElement:lu}),(du.litElementVersions??=[]).push("4.2.2");const hu=e=>(t,i)=>{void 0!==i?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)},pu={attribute:!0,type:String,converter:Tl,reflect:!1,hasChanged:Cl},mu=(e=pu,t,i)=>{const{kind:n,metadata:s}=i;let o=globalThis.litPropertyMetadata.get(s);if(void 0===o&&globalThis.litPropertyMetadata.set(s,o=new Map),"setter"===n&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),"accessor"===n){const{name:n}=i;return{set(i){const s=t.get.call(this);t.set.call(this,i),this.requestUpdate(n,s,e,!0,i)},init(t){return void 0!==t&&this.C(n,void 0,e,t),t}}}if("setter"===n){const{name:n}=i;return function(i){const s=this[n];t.call(this,i),this.requestUpdate(n,s,e,!0,i)}}throw Error("Unsupported decorator location: "+n)};function gu(e){return(t,i)=>"object"==typeof i?mu(e,t,i):((e,t,i)=>{const n=t.hasOwnProperty(i);return t.constructor.createProperty(i,e),n?Object.getOwnPropertyDescriptor(t,i):void 0})(e,t,i)}function fu(e){return gu({...e,state:!0,attribute:!1})}const vu=dl`
2
2
  :host {
3
3
  /* Font stack - system fonts for consistent rendering across sites */
4
4
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
5
5
 
6
6
  /* Color tokens */
7
- --speechos-primary: #10B981;
8
- --speechos-primary-hover: #059669;
9
- --speechos-primary-active: #047857;
7
+ --speechos-primary: #0d9488;
8
+ --speechos-primary-hover: #0f766e;
9
+ --speechos-primary-active: #115e59;
10
10
 
11
11
  --speechos-bg: #ffffff;
12
12
  --speechos-bg-hover: #f9fafb;
@@ -41,7 +41,7 @@
41
41
  --speechos-z-base: 999999;
42
42
  --speechos-z-popup: 1000000;
43
43
  }
44
- `,vu=cl`
44
+ `,bu=dl`
45
45
  @keyframes speechos-fadeIn {
46
46
  from {
47
47
  opacity: 0;
@@ -96,7 +96,7 @@
96
96
  transform: scale(1);
97
97
  }
98
98
  }
99
- `;function bu(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement}function yu(e,t){const i=e.ownerDocument.activeElement;if(i===e)return t();try{return e.focus(),t()}finally{e.blur(),i instanceof HTMLElement&&i.focus()}}function ku(e,t){""===t?e.execCommand("delete"):e.execCommand("insertText",!1,t)}function Su(e,t){yu(e,()=>{ku(e.ownerDocument,t)})}function Tu(e){if(bu(e))return e.value.slice(e.selectionStart,e.selectionEnd);const t=e.ownerDocument.getSelection();return t&&e.contains(t.anchorNode)?t.toString():""}cl`
99
+ `;function yu(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement}function ku(e,t){const i=e.ownerDocument.activeElement;if(i===e)return t();try{return e.focus(),t()}finally{e.blur(),i instanceof HTMLElement&&i.focus()}}function Su(e,t){""===t?e.execCommand("delete"):e.execCommand("insertText",!1,t)}function Tu(e,t){ku(e,()=>{Su(e.ownerDocument,t)})}function Cu(e){if(yu(e))return e.value.slice(e.selectionStart,e.selectionEnd);const t=e.ownerDocument.getSelection();return t&&e.contains(t.anchorNode)?t.toString():""}dl`
100
100
  .speechos-hidden {
101
101
  display: none !important;
102
102
  }
@@ -116,7 +116,7 @@
116
116
  .speechos-pulse {
117
117
  animation: speechos-pulse 2s ease-in-out infinite;
118
118
  }
119
- `;const Cu=2;class wu{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}class Eu extends wu{constructor(e){if(super(e),this.it=Gl,e.type!==Cu)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===Gl||null==e)return this._t=void 0,this.it=e;if(e===Wl)return e;if("string"!=typeof e)throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}}Eu.directiveName="unsafeHTML",Eu.resultType=1;const xu=(e=>(...t)=>({_$litDirective$:e,values:t}))(Eu);function Ru(e,t=20){return zl`${xu(`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="${t}"\n height="${t}"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n style="display: block;"\n >\n ${e}\n </svg>\n `)}`}const Pu=(e=20)=>Ru('<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/>',e),Iu=(e=18)=>Ru('<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',e),Ou=(e=18)=>Ru('<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/>',e),Au=(e=20)=>zl`${xu(`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="${e}"\n height="${e}"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n style="display: block; animation: spin 1s linear infinite;"\n >\n <path d="M21 12a9 9 0 1 1-6.219-8.56"/>\n </svg>\n `)}`,_u=(e=14)=>Ru('<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',e),Mu=(e=16)=>Ru('<rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="M12 11h4"/><path d="M12 16h4"/><path d="M8 11h.01"/><path d="M8 16h.01"/>',e),Du=(e=16)=>Ru('<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>',e),Nu=(e=16)=>Ru('<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',e),Lu=(e=16)=>Ru('<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',e),Uu=(e=14)=>Ru('<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',e),Fu=(e=18)=>Ru('<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',e),ju=(e=16)=>Ru('<circle cx="6" cy="6" r="3"/><path d="M8.12 8.12 12 12"/><path d="M20 4 8.12 15.88"/><circle cx="6" cy="18" r="3"/><path d="M14.8 14.8 20 20"/>',e),Bu=(e=16)=>Ru('<path d="M12 7v14"/><path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"/>',e),$u=(e=16)=>Ru('<path d="M5 12h14"/><path d="M12 5v14"/>',e),Vu=(e=18)=>Ru('<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>',e);let qu=class extends du{constructor(){super(...arguments),this.active=!1,this.levels=new Array(5).fill(0),this.mediaStream=null,this.audioContext=null,this.analyser=null,this.animationId=null,this.dataArray=null,this.smoothedLevels=new Array(5).fill(0)}static{this.styles=[fu,cl`
119
+ `;const wu=2;class Eu{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}class xu extends Eu{constructor(e){if(super(e),this.it=Kl,e.type!==wu)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===Kl||null==e)return this._t=void 0,this.it=e;if(e===Gl)return e;if("string"!=typeof e)throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}}xu.directiveName="unsafeHTML",xu.resultType=1;const Ru=(e=>(...t)=>({_$litDirective$:e,values:t}))(xu);function Pu(e,t=20){return Wl`${Ru(`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="${t}"\n height="${t}"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n style="display: block;"\n >\n ${e}\n </svg>\n `)}`}const Iu=(e=20)=>Pu('<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/>',e),Ou=(e=18)=>Pu('<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',e),Au=(e=18)=>Pu('<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/>',e),_u=(e=20)=>Wl`${Ru(`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="${e}"\n height="${e}"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n style="display: block; animation: spin 1s linear infinite;"\n >\n <path d="M21 12a9 9 0 1 1-6.219-8.56"/>\n </svg>\n `)}`,Mu=(e=14)=>Pu('<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',e),Du=(e=16)=>Pu('<rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="M12 11h4"/><path d="M12 16h4"/><path d="M8 11h.01"/><path d="M8 16h.01"/>',e),Nu=(e=16)=>Pu('<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>',e),Lu=(e=16)=>Pu('<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',e),Uu=(e=16)=>Pu('<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',e),Fu=(e=14)=>Pu('<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',e),ju=(e=18)=>Pu('<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',e),Bu=(e=16)=>Pu('<circle cx="6" cy="6" r="3"/><path d="M8.12 8.12 12 12"/><path d="M20 4 8.12 15.88"/><circle cx="6" cy="18" r="3"/><path d="M14.8 14.8 20 20"/>',e),$u=(e=16)=>Pu('<path d="M12 7v14"/><path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"/>',e),Vu=(e=16)=>Pu('<path d="M5 12h14"/><path d="M12 5v14"/>',e),qu=(e=18)=>Pu('<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>',e);let Hu=class extends lu{constructor(){super(...arguments),this.active=!1,this.levels=new Array(5).fill(0),this.mediaStream=null,this.audioContext=null,this.analyser=null,this.animationId=null,this.dataArray=null,this.smoothedLevels=new Array(5).fill(0)}static{this.styles=[vu,dl`
120
120
  :host {
121
121
  display: inline-flex;
122
122
  align-items: center;
@@ -145,16 +145,16 @@
145
145
  .bar.active {
146
146
  background: var(--speechos-primary);
147
147
  }
148
- `]}updated(e){e.has("active")&&(this.active?this.startMonitoring():this.stopMonitoring())}disconnectedCallback(){super.disconnectedCallback(),this.stopMonitoring()}async startMonitoring(){try{this.stopMonitoring();const e=$d(),t={audio:!e||{deviceId:{exact:e}}};this.mediaStream=await navigator.mediaDevices.getUserMedia(t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=128,this.analyser.smoothingTimeConstant=.8;this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.analyser),this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.updateLevels()}catch(e){console.error("[SpeechOS] Audio visualizer error:",e)}}stopMonitoring(){null!==this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.analyser=null,this.dataArray=null,this.levels=new Array(5).fill(0),this.smoothedLevels=new Array(5).fill(0)}updateLevels(){if(!this.analyser||!this.dataArray)return;this.analyser.getByteFrequencyData(this.dataArray);const e=this.dataArray.length,t=Math.floor(e/10),i=[];for(let n=0;n<5;n++){const s=n*t,o=s+t;let r=0;for(let t=s;t<o&&t<e;t++)r+=this.dataArray[t];const a=r/t,c=Math.min(1,a/255*1.8);this.smoothedLevels[n]=.3*this.smoothedLevels[n]+.7*c,i.push(this.smoothedLevels[n])}this.levels=i,this.animationId=requestAnimationFrame(()=>this.updateLevels())}getBarClass(e){return e<.05?"":"active"}render(){return this.active?zl`
148
+ `]}updated(e){e.has("active")&&(this.active?this.startMonitoring():this.stopMonitoring())}disconnectedCallback(){super.disconnectedCallback(),this.stopMonitoring()}async startMonitoring(){try{this.stopMonitoring();const e=Vd(),t={audio:!e||{deviceId:{exact:e}}};this.mediaStream=await navigator.mediaDevices.getUserMedia(t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=128,this.analyser.smoothingTimeConstant=.8;this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.analyser),this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.updateLevels()}catch(e){console.error("[SpeechOS] Audio visualizer error:",e)}}stopMonitoring(){null!==this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.analyser=null,this.dataArray=null,this.levels=new Array(5).fill(0),this.smoothedLevels=new Array(5).fill(0)}updateLevels(){if(!this.analyser||!this.dataArray)return;this.analyser.getByteFrequencyData(this.dataArray);const e=this.dataArray.length,t=Math.floor(e/10),i=[];for(let n=0;n<5;n++){const s=n*t,o=s+t;let r=0;for(let t=s;t<o&&t<e;t++)r+=this.dataArray[t];const a=r/t,c=Math.min(1,a/255*1.8);this.smoothedLevels[n]=.3*this.smoothedLevels[n]+.7*c,i.push(this.smoothedLevels[n])}this.levels=i,this.animationId=requestAnimationFrame(()=>this.updateLevels())}getBarClass(e){return e<.05?"":"active"}render(){return this.active?Wl`
149
149
  <div class="visualizer">
150
- ${this.levels.map(e=>zl`
150
+ ${this.levels.map(e=>Wl`
151
151
  <div
152
152
  class="bar ${this.getBarClass(e)}"
153
153
  style="height: ${Math.max(3,16*e)}px"
154
154
  ></div>
155
155
  `)}
156
156
  </div>
157
- `:zl``}};il([mu({type:Boolean})],qu.prototype,"active",void 0),il([gu()],qu.prototype,"levels",void 0),qu=il([uu("speechos-audio-visualizer")],qu);let Hu=class extends du{constructor(){super(...arguments),this.expanded=!1,this.recordingState="idle",this.activeAction=null,this.editPreviewText="",this.errorMessage=null,this.showRetryButton=!0,this.actionFeedback=null,this.showNoAudioWarning=!1}static{this.styles=[fu,vu,cl`
157
+ `:Wl``}};nl([gu({type:Boolean})],Hu.prototype,"active",void 0),nl([fu()],Hu.prototype,"levels",void 0),Hu=nl([hu("speechos-audio-visualizer")],Hu);let zu=class extends lu{constructor(){super(...arguments),this.expanded=!1,this.recordingState="idle",this.activeAction=null,this.editPreviewText="",this.errorMessage=null,this.showRetryButton=!0,this.actionFeedback=null,this.showNoAudioWarning=!1}static{this.styles=[vu,bu,dl`
158
158
  :host {
159
159
  display: inline-block;
160
160
  }
@@ -167,45 +167,51 @@
167
167
  width: 56px;
168
168
  height: 56px;
169
169
  border-radius: var(--speechos-radius-full);
170
- background: linear-gradient(135deg, #10b981 0%, #059669 100%);
170
+ background: #10b981;
171
171
  border: none;
172
172
  cursor: pointer;
173
173
  display: flex;
174
174
  align-items: center;
175
175
  justify-content: center;
176
176
  color: white;
177
- box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
178
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
177
+ box-shadow: 0 4px 16px rgba(16, 185, 129, 0.35);
178
+ transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
179
179
  position: relative;
180
180
  overflow: hidden;
181
181
  }
182
182
 
183
183
  .mic-button:hover {
184
+ background: #059669;
184
185
  transform: scale(1.05);
185
- box-shadow: 0 6px 20px rgba(16, 185, 129, 0.5);
186
+ box-shadow: 0 6px 24px rgba(16, 185, 129, 0.45);
186
187
  }
187
188
 
188
189
  .mic-button:active {
189
190
  transform: scale(0.98);
190
191
  }
191
192
 
193
+ .mic-button:focus {
194
+ outline: none;
195
+ box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.4), 0 4px 16px rgba(16, 185, 129, 0.35);
196
+ }
197
+
192
198
  /* Expanded state - bubbles visible */
193
199
  .mic-button.expanded {
194
- background: linear-gradient(135deg, #059669 0%, #047857 100%);
200
+ background: #059669;
195
201
  }
196
202
 
197
203
  /* Connecting state - Siri-style metallic spinner */
198
204
  .mic-button.connecting {
199
205
  background: radial-gradient(
200
206
  circle at 30% 30%,
201
- #34d399 0%,
202
- #10b981 40%,
203
- #059669 70%,
204
- #047857 100%
207
+ #2dd4bf 0%,
208
+ #14b8a6 40%,
209
+ #0d9488 70%,
210
+ #0f766e 100%
205
211
  );
206
212
  cursor: wait;
207
- box-shadow: 0 0 20px rgba(16, 185, 129, 0.4),
208
- 0 0 40px rgba(16, 185, 129, 0.2),
213
+ box-shadow: 0 0 20px rgba(13, 148, 136, 0.4),
214
+ 0 0 40px rgba(13, 148, 136, 0.2),
209
215
  inset 0 0 20px rgba(255, 255, 255, 0.1);
210
216
  }
211
217
 
@@ -248,15 +254,15 @@
248
254
  background: conic-gradient(
249
255
  from 0deg,
250
256
  transparent 0deg,
251
- rgba(52, 211, 153, 0.1) 30deg,
252
- rgba(16, 185, 129, 0.8) 90deg,
257
+ rgba(45, 212, 191, 0.1) 30deg,
258
+ rgba(13, 148, 136, 0.8) 90deg,
253
259
  rgba(255, 255, 255, 0.95) 120deg,
254
- rgba(52, 211, 153, 0.9) 150deg,
255
- rgba(16, 185, 129, 0.6) 180deg,
256
- rgba(5, 150, 105, 0.3) 210deg,
260
+ rgba(45, 212, 191, 0.9) 150deg,
261
+ rgba(13, 148, 136, 0.6) 180deg,
262
+ rgba(15, 118, 110, 0.3) 210deg,
257
263
  transparent 270deg,
258
- rgba(110, 231, 183, 0.2) 300deg,
259
- rgba(16, 185, 129, 0.5) 330deg,
264
+ rgba(94, 234, 212, 0.2) 300deg,
265
+ rgba(13, 148, 136, 0.5) 330deg,
260
266
  transparent 360deg
261
267
  );
262
268
  -webkit-mask: linear-gradient(#fff 0 0) content-box,
@@ -277,13 +283,13 @@
277
283
  background: conic-gradient(
278
284
  from 180deg,
279
285
  transparent 0deg,
280
- rgba(167, 243, 208, 0.3) 60deg,
286
+ rgba(153, 246, 228, 0.3) 60deg,
281
287
  rgba(255, 255, 255, 0.7) 90deg,
282
- rgba(110, 231, 183, 0.5) 120deg,
288
+ rgba(94, 234, 212, 0.5) 120deg,
283
289
  transparent 180deg,
284
- rgba(52, 211, 153, 0.2) 240deg,
290
+ rgba(45, 212, 191, 0.2) 240deg,
285
291
  rgba(255, 255, 255, 0.5) 270deg,
286
- rgba(16, 185, 129, 0.4) 300deg,
292
+ rgba(13, 148, 136, 0.4) 300deg,
287
293
  transparent 360deg
288
294
  );
289
295
  -webkit-mask: linear-gradient(#fff 0 0) content-box,
@@ -324,8 +330,8 @@
324
330
  border-radius: 50%;
325
331
  background: radial-gradient(
326
332
  circle,
327
- rgba(16, 185, 129, 0.4) 0%,
328
- rgba(16, 185, 129, 0.15) 40%,
333
+ rgba(13, 148, 136, 0.4) 0%,
334
+ rgba(13, 148, 136, 0.15) 40%,
329
335
  transparent 70%
330
336
  );
331
337
  animation: siri-glow-pulse 2s ease-in-out infinite;
@@ -1102,25 +1108,25 @@
1102
1108
  font-size: 14px;
1103
1109
  }
1104
1110
  }
1105
- `]}handleClick(e){e.stopPropagation(),e.preventDefault(),"recording"===this.recordingState?this.dispatchEvent(new CustomEvent("stop-recording",{bubbles:!0,composed:!0})):"idle"===this.recordingState?this.dispatchEvent(new CustomEvent("mic-click",{bubbles:!0,composed:!0})):"error"===this.recordingState&&this.dispatchEvent(new CustomEvent("cancel-operation",{bubbles:!0,composed:!0}))}handleCancel(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("cancel-operation",{bubbles:!0,composed:!0}))}stopEvent(e){e.stopPropagation()}handleClose(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("close-widget",{bubbles:!0,composed:!0}))}handleRetry(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("retry-connection",{bubbles:!0,composed:!0}))}handleOpenSettings(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("open-settings",{bubbles:!0,composed:!0}))}getButtonClass(){const e=["mic-button"];return this.expanded&&"idle"===this.recordingState&&e.push("expanded"),"idle"!==this.recordingState&&(e.push(this.recordingState),"processing"===this.recordingState&&"edit"===this.activeAction&&e.push("editing")),e.join(" ")}renderIcon(){switch(this.recordingState){case"connecting":case"processing":return Au(24);case"recording":return((e=18)=>zl`${xu(`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="${e}"\n height="${e}"\n viewBox="0 0 24 24"\n fill="currentColor"\n stroke="none"\n style="display: block;"\n >\n <rect x="6" y="6" width="12" height="12" rx="2" />\n </svg>\n `)}`)(20);case"error":return _u(20);default:return Pu(24)}}getAriaLabel(){switch(this.recordingState){case"connecting":return"Connecting...";case"recording":return"Stop recording";case"processing":return"Processing...";case"error":return"Connection error - click to dismiss";default:return"Open voice commands"}}formatPreviewText(e,t=10){const i=e.trim().replace(/\s+/g," ");return i?i.length<=t?`"${i}"`:`"${i.substring(0,t)}…"`:""}getStatusLabel(){switch(this.recordingState){case"connecting":case"processing":default:return"";case"recording":if("edit"===this.activeAction&&this.editPreviewText){return`Editing ${this.formatPreviewText(this.editPreviewText)}...`}return""}}shouldShowVisualizer(){return"recording"===this.recordingState&&!("edit"===this.activeAction&&this.editPreviewText)}getStatusClass(){return"processing"===this.recordingState&&"edit"===this.activeAction?"editing":this.recordingState}getActionFeedbackLabel(){return"command-success"===this.actionFeedback?"Got it!":"command-none"===this.actionFeedback?"No command matched":"edit-empty"===this.actionFeedback?"Couldn't understand edit":""}render(){const e="recording"===this.recordingState,t="connecting"===this.recordingState,i="processing"===this.recordingState&&"edit"!==this.activeAction,n="processing"===this.recordingState&&"edit"===this.activeAction,s=this.getStatusLabel(),o=this.shouldShowVisualizer(),r="idle"===this.recordingState&&null!==this.actionFeedback,a="recording"===this.recordingState||r,c="connecting"===this.recordingState||"recording"===this.recordingState||"processing"===this.recordingState,d="error"===this.recordingState&&this.errorMessage,l="idle"===this.recordingState;return zl`
1111
+ `]}handleClick(e){e.stopPropagation(),e.preventDefault(),"recording"===this.recordingState?this.dispatchEvent(new CustomEvent("stop-recording",{bubbles:!0,composed:!0})):"idle"===this.recordingState?this.dispatchEvent(new CustomEvent("mic-click",{bubbles:!0,composed:!0})):"error"===this.recordingState&&this.dispatchEvent(new CustomEvent("cancel-operation",{bubbles:!0,composed:!0}))}handleCancel(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("cancel-operation",{bubbles:!0,composed:!0}))}stopEvent(e){e.stopPropagation()}handleClose(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("close-widget",{bubbles:!0,composed:!0}))}handleRetry(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("retry-connection",{bubbles:!0,composed:!0}))}handleOpenSettings(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("open-settings",{bubbles:!0,composed:!0}))}getButtonClass(){const e=["mic-button"];return this.expanded&&"idle"===this.recordingState&&e.push("expanded"),"idle"!==this.recordingState&&(e.push(this.recordingState),"processing"===this.recordingState&&"edit"===this.activeAction&&e.push("editing")),e.join(" ")}renderIcon(){switch(this.recordingState){case"connecting":case"processing":return _u(24);case"recording":return((e=18)=>Wl`${Ru(`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="${e}"\n height="${e}"\n viewBox="0 0 24 24"\n fill="currentColor"\n stroke="none"\n style="display: block;"\n >\n <rect x="6" y="6" width="12" height="12" rx="2" />\n </svg>\n `)}`)(20);case"error":return Mu(20);default:return Iu(24)}}getAriaLabel(){switch(this.recordingState){case"connecting":return"Connecting...";case"recording":return"Stop recording";case"processing":return"Processing...";case"error":return"Connection error - click to dismiss";default:return"Open voice commands"}}formatPreviewText(e,t=10){const i=e.trim().replace(/\s+/g," ");return i?i.length<=t?`"${i}"`:`"${i.substring(0,t)}…"`:""}getStatusLabel(){switch(this.recordingState){case"connecting":case"processing":default:return"";case"recording":if("edit"===this.activeAction&&this.editPreviewText){return`Editing ${this.formatPreviewText(this.editPreviewText)}...`}return""}}shouldShowVisualizer(){return"recording"===this.recordingState&&!("edit"===this.activeAction&&this.editPreviewText)}getStatusClass(){return"processing"===this.recordingState&&"edit"===this.activeAction?"editing":this.recordingState}getActionFeedbackLabel(){return"command-success"===this.actionFeedback?"Got it!":"command-none"===this.actionFeedback?"No command matched":"edit-empty"===this.actionFeedback?"Couldn't understand edit":""}render(){const e="recording"===this.recordingState,t="connecting"===this.recordingState,i="processing"===this.recordingState&&"edit"!==this.activeAction,n="processing"===this.recordingState&&"edit"===this.activeAction,s=this.getStatusLabel(),o=this.shouldShowVisualizer(),r="idle"===this.recordingState&&null!==this.actionFeedback,a="recording"===this.recordingState||r,c="connecting"===this.recordingState||"recording"===this.recordingState||"processing"===this.recordingState,d="error"===this.recordingState&&this.errorMessage,l="idle"===this.recordingState;return Wl`
1106
1112
  <div class="button-wrapper">
1107
- ${e?zl`<div class="pulse-ring"></div>`:""}
1108
- ${t?zl`
1113
+ ${e?Wl`<div class="pulse-ring"></div>`:""}
1114
+ ${t?Wl`
1109
1115
  <div class="siri-glow"></div>
1110
1116
  <div class="siri-ring"></div>
1111
1117
  `:""}
1112
- ${i?zl`
1118
+ ${i?Wl`
1113
1119
  <div class="siri-glow-transcribe"></div>
1114
1120
  <div class="siri-ring-transcribe"></div>
1115
1121
  `:""}
1116
- ${n?zl`
1122
+ ${n?Wl`
1117
1123
  <div class="siri-glow-edit"></div>
1118
1124
  <div class="siri-ring-edit"></div>
1119
1125
  `:""}
1120
- ${d?zl`
1126
+ ${d?Wl`
1121
1127
  <div class="error-message ${d?"visible":""}">
1122
1128
  ${this.errorMessage}
1123
- ${this.showRetryButton?zl`
1129
+ ${this.showRetryButton?Wl`
1124
1130
  <button class="retry-button" @click="${this.handleRetry}">
1125
1131
  Retry Connection
1126
1132
  </button>
@@ -1167,7 +1173,7 @@
1167
1173
  <span
1168
1174
  class="status-label ${a?"visible":""} ${r?this.actionFeedback:o?"visualizer":this.getStatusClass()}"
1169
1175
  >
1170
- ${r?this.getActionFeedbackLabel():o?zl`<speechos-audio-visualizer
1176
+ ${r?this.getActionFeedbackLabel():o?Wl`<speechos-audio-visualizer
1171
1177
  ?active="${o}"
1172
1178
  ></speechos-audio-visualizer>`:s}
1173
1179
  </span>
@@ -1179,7 +1185,7 @@
1179
1185
  aria-label="Close"
1180
1186
  title="Close"
1181
1187
  >
1182
- ${_u(16)}
1188
+ ${Mu(16)}
1183
1189
  </button>
1184
1190
 
1185
1191
  <button
@@ -1189,10 +1195,10 @@
1189
1195
  aria-label="Cancel"
1190
1196
  title="Cancel"
1191
1197
  >
1192
- ${_u(16)}
1198
+ ${Mu(16)}
1193
1199
  </button>
1194
1200
  </div>
1195
- `}};il([mu({type:Boolean})],Hu.prototype,"expanded",void 0),il([mu({type:String})],Hu.prototype,"recordingState",void 0),il([mu({type:String})],Hu.prototype,"activeAction",void 0),il([mu({type:String})],Hu.prototype,"editPreviewText",void 0),il([mu({type:String})],Hu.prototype,"errorMessage",void 0),il([mu({type:Boolean})],Hu.prototype,"showRetryButton",void 0),il([mu({type:String})],Hu.prototype,"actionFeedback",void 0),il([mu({type:Boolean})],Hu.prototype,"showNoAudioWarning",void 0),Hu=il([uu("speechos-mic-button")],Hu);let zu=class extends du{constructor(){super(...arguments),this.visible=!1}static{this.styles=[fu,vu,cl`
1201
+ `}};nl([gu({type:Boolean})],zu.prototype,"expanded",void 0),nl([gu({type:String})],zu.prototype,"recordingState",void 0),nl([gu({type:String})],zu.prototype,"activeAction",void 0),nl([gu({type:String})],zu.prototype,"editPreviewText",void 0),nl([gu({type:String})],zu.prototype,"errorMessage",void 0),nl([gu({type:Boolean})],zu.prototype,"showRetryButton",void 0),nl([gu({type:String})],zu.prototype,"actionFeedback",void 0),nl([gu({type:Boolean})],zu.prototype,"showNoAudioWarning",void 0),zu=nl([hu("speechos-mic-button")],zu);let Wu=class extends lu{constructor(){super(...arguments),this.visible=!1}static{this.styles=[vu,bu,dl`
1196
1202
  :host {
1197
1203
  display: block;
1198
1204
  position: absolute;
@@ -1304,9 +1310,9 @@
1304
1310
  gap: 10px;
1305
1311
  }
1306
1312
  }
1307
- `]}get actions(){const e=_c(),t=[{id:"dictate",label:"Dictate",icon:Iu()},{id:"edit",label:"Edit",icon:Ou()}];return e.commands&&e.commands.length>0&&t.push({id:"command",label:"Command",icon:Vu()}),t}handleActionClick(e,t){e.stopPropagation(),e.preventDefault(),gc.emit("action:select",{action:t}),this.dispatchEvent(new CustomEvent("action-select",{bubbles:!0,composed:!0,detail:{action:t}}))}render(){return this.visible?zl`
1313
+ `]}get actions(){const e=_c(),t=[{id:"dictate",label:"Dictate",icon:Ou()},{id:"edit",label:"Edit",icon:Au()}];return e.commands&&e.commands.length>0&&t.push({id:"command",label:"Command",icon:qu()}),t}handleActionClick(e,t){e.stopPropagation(),e.preventDefault(),gc.emit("action:select",{action:t}),this.dispatchEvent(new CustomEvent("action-select",{bubbles:!0,composed:!0,detail:{action:t}}))}render(){return this.visible?Wl`
1308
1314
  <div class="bubbles-container">
1309
- ${this.actions.map(e=>zl`
1315
+ ${this.actions.map(e=>Wl`
1310
1316
  <button
1311
1317
  class="action-button ${e.id}"
1312
1318
  @click="${t=>this.handleActionClick(t,e.id)}"
@@ -1318,7 +1324,7 @@
1318
1324
  </button>
1319
1325
  `)}
1320
1326
  </div>
1321
- `:zl``}};il([mu({type:Boolean})],zu.prototype,"visible",void 0),zu=il([uu("speechos-action-bubbles")],zu);let Wu=class extends du{constructor(){super(...arguments),this.visible=!1}static{this.styles=[fu,cl`
1327
+ `:Wl``}};nl([gu({type:Boolean})],Wu.prototype,"visible",void 0),Wu=nl([hu("speechos-action-bubbles")],Wu);let Gu=class extends lu{constructor(){super(...arguments),this.visible=!1}static{this.styles=[vu,dl`
1322
1328
  :host {
1323
1329
  display: block;
1324
1330
  }
@@ -1372,16 +1378,16 @@
1372
1378
  transform: scale(1.3);
1373
1379
  }
1374
1380
  }
1375
- `]}handleClick(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("settings-click",{bubbles:!0,composed:!0}))}render(){return zl`
1381
+ `]}handleClick(e){e.stopPropagation(),e.preventDefault(),this.dispatchEvent(new CustomEvent("settings-click",{bubbles:!0,composed:!0}))}render(){return Wl`
1376
1382
  <button
1377
1383
  class="settings-button ${this.visible?"visible":""}"
1378
1384
  @click="${this.handleClick}"
1379
1385
  aria-label="Settings"
1380
1386
  title="Settings"
1381
1387
  >
1382
- ${Lu(16)}
1388
+ ${Uu(16)}
1383
1389
  </button>
1384
- `}};il([mu({type:Boolean})],Wu.prototype,"visible",void 0),Wu=il([uu("speechos-settings-button")],Wu);const Gu=cl`
1390
+ `}};nl([gu({type:Boolean})],Gu.prototype,"visible",void 0),Gu=nl([hu("speechos-settings-button")],Gu);const Ku=dl`
1385
1391
  :host {
1386
1392
  position: fixed;
1387
1393
  inset: 0;
@@ -1413,15 +1419,15 @@
1413
1419
  }
1414
1420
 
1415
1421
  .modal {
1416
- background: #1a1d24;
1422
+ background: #f5f5f4;
1417
1423
  border-radius: 16px;
1418
1424
  width: 90%;
1419
1425
  max-width: 580px;
1420
1426
  height: min(560px, 85vh);
1421
1427
  display: flex;
1422
1428
  flex-direction: column;
1423
- box-shadow: 0 24px 48px rgba(0, 0, 0, 0.4),
1424
- 0 0 0 1px rgba(255, 255, 255, 0.05);
1429
+ box-shadow: 0 24px 48px rgba(0, 0, 0, 0.15),
1430
+ 0 0 0 1px rgba(0, 0, 0, 0.05);
1425
1431
  transform: scale(0.95) translateY(10px);
1426
1432
  transition: transform 0.25s cubic-bezier(0.16, 1, 0.3, 1);
1427
1433
  pointer-events: auto;
@@ -1446,16 +1452,16 @@
1446
1452
  align-items: center;
1447
1453
  justify-content: space-between;
1448
1454
  padding: 16px 20px;
1449
- border-bottom: 1px solid rgba(255, 255, 255, 0.06);
1450
- background: rgba(0, 0, 0, 0.2);
1455
+ border-bottom: 1px solid #e5e5e5;
1456
+ background: #ffffff;
1451
1457
  }
1452
1458
 
1453
1459
  .modal-title {
1454
1460
  font-size: 17px;
1455
1461
  font-weight: 600;
1456
- color: white;
1462
+ color: #171717;
1457
1463
  margin: 0;
1458
- letter-spacing: -0.01em;
1464
+ letter-spacing: -0.02em;
1459
1465
  }
1460
1466
 
1461
1467
  .modal-logo {
@@ -1468,7 +1474,7 @@
1468
1474
  width: 28px;
1469
1475
  height: 28px;
1470
1476
  border-radius: 8px;
1471
- background: linear-gradient(135deg, #10b981 0%, #8b5cf6 100%);
1477
+ background: linear-gradient(135deg, #14b8a6 0%, #2563eb 100%);
1472
1478
  display: flex;
1473
1479
  align-items: center;
1474
1480
  justify-content: center;
@@ -1483,13 +1489,13 @@
1483
1489
  .logo-text {
1484
1490
  font-size: 17px;
1485
1491
  font-weight: 500;
1486
- color: white;
1492
+ color: #171717;
1487
1493
  letter-spacing: -0.02em;
1488
1494
  }
1489
1495
 
1490
1496
  .logo-os {
1491
1497
  font-weight: 700;
1492
- background: linear-gradient(135deg, #34d399 0%, #a78bfa 100%);
1498
+ background: linear-gradient(135deg, #14b8a6 0%, #2563eb 100%);
1493
1499
  -webkit-background-clip: text;
1494
1500
  -webkit-text-fill-color: transparent;
1495
1501
  background-clip: text;
@@ -1505,13 +1511,22 @@
1505
1511
  display: flex;
1506
1512
  align-items: center;
1507
1513
  justify-content: center;
1508
- color: rgba(255, 255, 255, 0.5);
1514
+ color: #737373;
1509
1515
  transition: all 0.15s ease;
1510
1516
  }
1511
1517
 
1512
1518
  .close-button:hover {
1513
- background: rgba(255, 255, 255, 0.08);
1514
- color: white;
1519
+ background: #f5f5f4;
1520
+ color: #171717;
1521
+ }
1522
+
1523
+ .close-button:focus {
1524
+ outline: none;
1525
+ box-shadow: 0 0 0 2px #0d9488, 0 0 0 4px rgba(13, 148, 136, 0.2);
1526
+ }
1527
+
1528
+ .close-button:active {
1529
+ transform: scale(0.95);
1515
1530
  }
1516
1531
 
1517
1532
  .modal-body {
@@ -1523,8 +1538,8 @@
1523
1538
  .sidebar {
1524
1539
  width: 110px;
1525
1540
  flex-shrink: 0;
1526
- background: rgba(0, 0, 0, 0.25);
1527
- border-right: 1px solid rgba(255, 255, 255, 0.06);
1541
+ background: #fafaf9;
1542
+ border-right: 1px solid #e5e5e5;
1528
1543
  padding: 12px 8px;
1529
1544
  display: flex;
1530
1545
  flex-direction: column;
@@ -1553,19 +1568,25 @@
1553
1568
  border-radius: 10px;
1554
1569
  background: transparent;
1555
1570
  cursor: pointer;
1556
- color: rgba(255, 255, 255, 0.5);
1571
+ color: #525252;
1557
1572
  transition: all 0.15s ease;
1558
1573
  position: relative;
1559
1574
  }
1560
1575
 
1561
1576
  .sidebar-item:hover {
1562
- background: rgba(255, 255, 255, 0.05);
1563
- color: rgba(255, 255, 255, 0.8);
1577
+ background: #ffffff;
1578
+ color: #171717;
1579
+ }
1580
+
1581
+ .sidebar-item:focus {
1582
+ outline: none;
1583
+ box-shadow: inset 0 0 0 2px rgba(13, 148, 136, 0.4);
1564
1584
  }
1565
1585
 
1566
1586
  .sidebar-item.active {
1567
- background: rgba(16, 185, 129, 0.12);
1568
- color: #34d399;
1587
+ background: rgba(15, 118, 110, 0.12);
1588
+ color: #0f766e;
1589
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
1569
1590
  }
1570
1591
 
1571
1592
  .sidebar-item.active::before {
@@ -1576,7 +1597,7 @@
1576
1597
  transform: translateY(-50%);
1577
1598
  width: 3px;
1578
1599
  height: 24px;
1579
- background: #34d399;
1600
+ background: #0f766e;
1580
1601
  border-radius: 0 3px 3px 0;
1581
1602
  }
1582
1603
 
@@ -1609,7 +1630,7 @@
1609
1630
  padding: 16px;
1610
1631
  }
1611
1632
  }
1612
- `,Ku=cl`
1633
+ `,Ju=dl`
1613
1634
  .section-header {
1614
1635
  margin-bottom: 16px;
1615
1636
  }
@@ -1617,14 +1638,14 @@
1617
1638
  .section-title {
1618
1639
  font-size: 15px;
1619
1640
  font-weight: 600;
1620
- color: white;
1641
+ color: #171717;
1621
1642
  margin: 0 0 6px 0;
1622
- letter-spacing: -0.01em;
1643
+ letter-spacing: -0.02em;
1623
1644
  }
1624
1645
 
1625
1646
  .section-description {
1626
1647
  font-size: 13px;
1627
- color: rgba(255, 255, 255, 0.5);
1648
+ color: #525252;
1628
1649
  line-height: 1.5;
1629
1650
  margin: 0;
1630
1651
  }
@@ -1632,7 +1653,7 @@
1632
1653
  .empty-state {
1633
1654
  text-align: center;
1634
1655
  padding: 40px 20px;
1635
- color: rgba(255, 255, 255, 0.5);
1656
+ color: #737373;
1636
1657
  }
1637
1658
 
1638
1659
  .empty-state-icon {
@@ -1644,7 +1665,7 @@
1644
1665
  font-size: 15px;
1645
1666
  font-weight: 500;
1646
1667
  margin-bottom: 8px;
1647
- color: rgba(255, 255, 255, 0.7);
1668
+ color: #525252;
1648
1669
  }
1649
1670
 
1650
1671
  .empty-state-text {
@@ -1662,7 +1683,7 @@
1662
1683
  display: flex;
1663
1684
  align-items: center;
1664
1685
  justify-content: center;
1665
- color: rgba(255, 255, 255, 0.35);
1686
+ color: #737373;
1666
1687
  transition: all 0.15s ease;
1667
1688
  }
1668
1689
 
@@ -1692,26 +1713,36 @@
1692
1713
  color: #fcd34d;
1693
1714
  line-height: 1.4;
1694
1715
  }
1695
- `,Ju=cl`
1716
+ `,Yu=dl`
1696
1717
  .add-button {
1697
1718
  display: inline-flex;
1698
1719
  align-items: center;
1699
1720
  gap: 6px;
1700
1721
  padding: 10px 16px;
1701
- background: linear-gradient(135deg, #10b981 0%, #059669 100%);
1722
+ background: #0d9488;
1702
1723
  border: none;
1703
1724
  border-radius: 8px;
1704
1725
  color: white;
1705
1726
  font-size: 13px;
1706
1727
  font-weight: 600;
1728
+ letter-spacing: 0.01em;
1707
1729
  cursor: pointer;
1708
- transition: all 0.2s ease;
1709
- box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2);
1730
+ transition: all 0.15s ease;
1731
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
1710
1732
  }
1711
1733
 
1712
1734
  .add-button:hover:not(:disabled) {
1713
- transform: translateY(-1px);
1714
- box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
1735
+ background: #0f766e;
1736
+ box-shadow: 0 4px 12px rgba(13, 148, 136, 0.25);
1737
+ }
1738
+
1739
+ .add-button:focus:not(:disabled) {
1740
+ outline: none;
1741
+ box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px #0d9488;
1742
+ }
1743
+
1744
+ .add-button:active:not(:disabled) {
1745
+ transform: scale(0.98);
1715
1746
  }
1716
1747
 
1717
1748
  .add-button:disabled {
@@ -1722,7 +1753,7 @@
1722
1753
 
1723
1754
  .count-badge {
1724
1755
  font-size: 12px;
1725
- color: rgba(255, 255, 255, 0.45);
1756
+ color: #737373;
1726
1757
  font-weight: 500;
1727
1758
  }
1728
1759
 
@@ -1734,11 +1765,12 @@
1734
1765
  }
1735
1766
 
1736
1767
  .add-form {
1737
- background: rgba(255, 255, 255, 0.04);
1738
- border: 1px solid rgba(255, 255, 255, 0.08);
1768
+ background: #ffffff;
1769
+ border: 1px solid #e5e5e5;
1739
1770
  border-radius: 12px;
1740
1771
  padding: 16px;
1741
1772
  margin-bottom: 16px;
1773
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
1742
1774
  }
1743
1775
 
1744
1776
  .form-group {
@@ -1753,7 +1785,7 @@
1753
1785
  display: block;
1754
1786
  font-size: 12px;
1755
1787
  font-weight: 600;
1756
- color: rgba(255, 255, 255, 0.7);
1788
+ color: #525252;
1757
1789
  margin-bottom: 8px;
1758
1790
  text-transform: uppercase;
1759
1791
  letter-spacing: 0.04em;
@@ -1762,10 +1794,10 @@
1762
1794
  .form-input {
1763
1795
  width: 100%;
1764
1796
  padding: 12px 14px;
1765
- background: rgba(0, 0, 0, 0.3);
1766
- border: 1px solid rgba(255, 255, 255, 0.08);
1797
+ background: #ffffff;
1798
+ border: 1px solid #d4d4d4;
1767
1799
  border-radius: 8px;
1768
- color: white;
1800
+ color: #171717;
1769
1801
  font-size: 14px;
1770
1802
  font-family: inherit;
1771
1803
  transition: all 0.15s ease;
@@ -1774,12 +1806,12 @@
1774
1806
 
1775
1807
  .form-input:focus {
1776
1808
  outline: none;
1777
- border-color: #34d399;
1778
- box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.15);
1809
+ border-color: #0d9488;
1810
+ box-shadow: 0 0 0 3px rgba(13, 148, 136, 0.15);
1779
1811
  }
1780
1812
 
1781
1813
  .form-input::placeholder {
1782
- color: rgba(255, 255, 255, 0.3);
1814
+ color: #a3a3a3;
1783
1815
  }
1784
1816
 
1785
1817
  .form-input.error {
@@ -1803,7 +1835,7 @@
1803
1835
 
1804
1836
  .char-count {
1805
1837
  font-size: 11px;
1806
- color: rgba(255, 255, 255, 0.4);
1838
+ color: #737373;
1807
1839
  font-variant-numeric: tabular-nums;
1808
1840
  }
1809
1841
 
@@ -1837,26 +1869,35 @@
1837
1869
  }
1838
1870
 
1839
1871
  .form-btn.cancel {
1840
- background: transparent;
1841
- border: 1px solid rgba(255, 255, 255, 0.15);
1842
- color: rgba(255, 255, 255, 0.7);
1872
+ background: #ffffff;
1873
+ border: 1px solid #d4d4d4;
1874
+ color: #525252;
1843
1875
  }
1844
1876
 
1845
1877
  .form-btn.cancel:hover {
1846
- background: rgba(255, 255, 255, 0.05);
1847
- border-color: rgba(255, 255, 255, 0.25);
1878
+ background: #fafaf9;
1879
+ border-color: #a3a3a3;
1848
1880
  }
1849
1881
 
1850
1882
  .form-btn.save {
1851
- background: linear-gradient(135deg, #10b981 0%, #059669 100%);
1883
+ background: #0d9488;
1852
1884
  border: none;
1853
1885
  color: white;
1854
- box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2);
1886
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
1855
1887
  }
1856
1888
 
1857
1889
  .form-btn.save:hover:not(:disabled) {
1858
- transform: translateY(-1px);
1859
- box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
1890
+ background: #0f766e;
1891
+ box-shadow: 0 4px 12px rgba(13, 148, 136, 0.25);
1892
+ }
1893
+
1894
+ .form-btn.save:focus:not(:disabled) {
1895
+ outline: none;
1896
+ box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px #0d9488;
1897
+ }
1898
+
1899
+ .form-btn.save:active:not(:disabled) {
1900
+ transform: scale(0.98);
1860
1901
  }
1861
1902
 
1862
1903
  .form-btn.save:disabled {
@@ -1864,7 +1905,7 @@
1864
1905
  cursor: not-allowed;
1865
1906
  transform: none;
1866
1907
  }
1867
- `;let Yu=class extends du{constructor(){super(...arguments),this.transcripts=[],this.unsubscribeSettingsLoaded=null}static{this.styles=[fu,Ku,cl`
1908
+ `;let Qu=class extends lu{constructor(){super(...arguments),this.transcripts=[],this.unsubscribeSettingsLoaded=null}static{this.styles=[vu,Ju,dl`
1868
1909
  :host {
1869
1910
  display: block;
1870
1911
  }
@@ -1876,16 +1917,17 @@
1876
1917
  }
1877
1918
 
1878
1919
  .transcript-item {
1879
- background: rgba(255, 255, 255, 0.04);
1880
- border: 1px solid rgba(255, 255, 255, 0.06);
1920
+ background: #ffffff;
1921
+ border: 1px solid #e5e5e5;
1881
1922
  border-radius: 10px;
1882
1923
  padding: 12px 14px;
1883
1924
  transition: all 0.15s ease;
1925
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
1884
1926
  }
1885
1927
 
1886
1928
  .transcript-item:hover {
1887
- background: rgba(255, 255, 255, 0.06);
1888
- border-color: rgba(255, 255, 255, 0.1);
1929
+ border-color: #d4d4d4;
1930
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
1889
1931
  }
1890
1932
 
1891
1933
  .transcript-header {
@@ -1908,28 +1950,28 @@
1908
1950
  }
1909
1951
 
1910
1952
  .transcript-badge.dictate {
1911
- background: rgba(16, 185, 129, 0.15);
1912
- color: #34d399;
1953
+ background: rgba(13, 148, 136, 0.18);
1954
+ color: #0f766e;
1913
1955
  }
1914
1956
 
1915
1957
  .transcript-badge.edit {
1916
- background: rgba(139, 92, 246, 0.15);
1917
- color: #a78bfa;
1958
+ background: rgba(139, 92, 246, 0.18);
1959
+ color: #7c3aed;
1918
1960
  }
1919
1961
 
1920
1962
  .transcript-badge.command {
1921
- background: rgba(245, 158, 11, 0.15);
1922
- color: #fbbf24;
1963
+ background: rgba(245, 158, 11, 0.18);
1964
+ color: #b45309;
1923
1965
  }
1924
1966
 
1925
1967
  .transcript-time {
1926
1968
  font-size: 12px;
1927
- color: rgba(255, 255, 255, 0.35);
1969
+ color: #737373;
1928
1970
  }
1929
1971
 
1930
1972
  .transcript-text {
1931
1973
  font-size: 14px;
1932
- color: rgba(255, 255, 255, 0.85);
1974
+ color: #171717;
1933
1975
  line-height: 1.5;
1934
1976
  word-break: break-word;
1935
1977
  display: -webkit-box;
@@ -1944,7 +1986,7 @@
1944
1986
  gap: 8px;
1945
1987
  margin-top: 10px;
1946
1988
  padding-top: 10px;
1947
- border-top: 1px solid rgba(255, 255, 255, 0.06);
1989
+ border-top: 1px solid #e5e5e5;
1948
1990
  }
1949
1991
 
1950
1992
  .transcript-action-btn {
@@ -1953,23 +1995,23 @@
1953
1995
  gap: 6px;
1954
1996
  padding: 6px 10px;
1955
1997
  border-radius: 6px;
1956
- background: rgba(255, 255, 255, 0.06);
1998
+ background: rgba(0, 0, 0, 0.08);
1957
1999
  border: none;
1958
2000
  cursor: pointer;
1959
2001
  font-size: 12px;
1960
2002
  font-weight: 500;
1961
- color: rgba(255, 255, 255, 0.6);
2003
+ color: #404040;
1962
2004
  transition: all 0.15s ease;
1963
2005
  }
1964
2006
 
1965
2007
  .transcript-action-btn:hover {
1966
- background: rgba(255, 255, 255, 0.1);
1967
- color: rgba(255, 255, 255, 0.9);
2008
+ background: rgba(0, 0, 0, 0.12);
2009
+ color: #171717;
1968
2010
  }
1969
2011
 
1970
2012
  .transcript-action-btn.copied {
1971
- background: rgba(16, 185, 129, 0.2);
1972
- color: #34d399;
2013
+ background: rgba(13, 148, 136, 0.2);
2014
+ color: #0d9488;
1973
2015
  }
1974
2016
 
1975
2017
  .transcript-action-btn.delete:hover {
@@ -1983,9 +2025,9 @@
1983
2025
  margin-top: 16px;
1984
2026
  padding: 10px;
1985
2027
  background: rgba(239, 68, 68, 0.1);
1986
- border: 1px solid rgba(239, 68, 68, 0.15);
2028
+ border: 1px solid rgba(239, 68, 68, 0.2);
1987
2029
  border-radius: 8px;
1988
- color: #f87171;
2030
+ color: #dc2626;
1989
2031
  font-size: 13px;
1990
2032
  font-weight: 500;
1991
2033
  cursor: pointer;
@@ -1994,36 +2036,36 @@
1994
2036
 
1995
2037
  .clear-all-button:hover {
1996
2038
  background: rgba(239, 68, 68, 0.18);
1997
- border-color: rgba(239, 68, 68, 0.25);
2039
+ border-color: rgba(239, 68, 68, 0.3);
1998
2040
  }
1999
2041
 
2000
2042
  .command-matched {
2001
2043
  font-size: 12px;
2002
- color: rgba(255, 255, 255, 0.5);
2044
+ color: #525252;
2003
2045
  margin-top: 6px;
2004
2046
  }
2005
2047
 
2006
2048
  .command-matched code {
2007
2049
  background: rgba(245, 158, 11, 0.15);
2008
- color: #fbbf24;
2050
+ color: #d97706;
2009
2051
  padding: 2px 6px;
2010
2052
  border-radius: 4px;
2011
2053
  font-family: monospace;
2012
2054
  }
2013
- `]}connectedCallback(){super.connectedCallback(),this.loadTranscripts(),this.unsubscribeSettingsLoaded=gc.on("settings:loaded",()=>{this.loadTranscripts()})}disconnectedCallback(){super.disconnectedCallback(),this.unsubscribeSettingsLoaded&&(this.unsubscribeSettingsLoaded(),this.unsubscribeSettingsLoaded=null)}refresh(){this.loadTranscripts()}loadTranscripts(){this.transcripts=el.getTranscripts()}formatTime(e){const t=new Date(e),i=(new Date).getTime()-t.getTime(),n=Math.floor(i/6e4),s=Math.floor(i/36e5),o=Math.floor(i/864e5);return n<1?"Just now":n<60?`${n}m ago`:s<24?`${s}h ago`:o<7?`${o}d ago`:t.toLocaleDateString()}handleDelete(e){el.deleteTranscript(e),this.loadTranscripts()}handleClearAll(){el.clearTranscripts(),this.loadTranscripts()}async handleCopy(e,t){const i=t.currentTarget;try{await navigator.clipboard.writeText(e)}catch{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}i.classList.add("copied"),i.textContent="Copied!",setTimeout(()=>{i.classList.remove("copied"),this.requestUpdate()},1e3)}getActionIcon(e){switch(e){case"dictate":default:return Iu(12);case"edit":return Ou(12);case"command":return Vu(12)}}renderCommandDetails(e){const t=e.inputText||e.text,i=e.commandResult?.name;return zl`
2055
+ `]}connectedCallback(){super.connectedCallback(),this.loadTranscripts(),this.unsubscribeSettingsLoaded=gc.on("settings:loaded",()=>{this.loadTranscripts()})}disconnectedCallback(){super.disconnectedCallback(),this.unsubscribeSettingsLoaded&&(this.unsubscribeSettingsLoaded(),this.unsubscribeSettingsLoaded=null)}refresh(){this.loadTranscripts()}loadTranscripts(){this.transcripts=tl.getTranscripts()}formatTime(e){const t=new Date(e),i=(new Date).getTime()-t.getTime(),n=Math.floor(i/6e4),s=Math.floor(i/36e5),o=Math.floor(i/864e5);return n<1?"Just now":n<60?`${n}m ago`:s<24?`${s}h ago`:o<7?`${o}d ago`:t.toLocaleDateString()}handleDelete(e){tl.deleteTranscript(e),this.loadTranscripts()}handleClearAll(){tl.clearTranscripts(),this.loadTranscripts()}async handleCopy(e,t){const i=t.currentTarget;try{await navigator.clipboard.writeText(e)}catch{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}i.classList.add("copied"),i.textContent="Copied!",setTimeout(()=>{i.classList.remove("copied"),this.requestUpdate()},1e3)}getActionIcon(e){switch(e){case"dictate":default:return Ou(12);case"edit":return Au(12);case"command":return qu(12)}}renderCommandDetails(e){const t=e.inputText||e.text,i=e.commandResult?.name;return Wl`
2014
2056
  <div class="transcript-text">${t}</div>
2015
- ${i?zl`<div class="command-matched">Matched: <code>${i}</code></div>`:null}
2016
- `}getCopyText(e){return"command"===e.action&&e.inputText||e.text}render(){return 0===this.transcripts.length?zl`
2057
+ ${i?Wl`<div class="command-matched">Matched: <code>${i}</code></div>`:null}
2058
+ `}getCopyText(e){return"command"===e.action&&e.inputText||e.text}render(){return 0===this.transcripts.length?Wl`
2017
2059
  <div class="empty-state">
2018
- <div class="empty-state-icon">${Mu(44)}</div>
2060
+ <div class="empty-state-icon">${Du(44)}</div>
2019
2061
  <div class="empty-state-title">No transcripts yet</div>
2020
2062
  <div class="empty-state-text">
2021
2063
  Your dictation, edit, and command history will appear here.
2022
2064
  </div>
2023
2065
  </div>
2024
- `:zl`
2066
+ `:Wl`
2025
2067
  <div class="transcripts-list">
2026
- ${this.transcripts.map(e=>zl`
2068
+ ${this.transcripts.map(e=>Wl`
2027
2069
  <div class="transcript-item">
2028
2070
  <div class="transcript-header">
2029
2071
  <span class="transcript-badge ${e.action}">
@@ -2034,19 +2076,19 @@
2034
2076
  >${this.formatTime(e.timestamp)}</span
2035
2077
  >
2036
2078
  </div>
2037
- ${"command"===e.action?this.renderCommandDetails(e):zl`<div class="transcript-text">${e.text}</div>`}
2079
+ ${"command"===e.action?this.renderCommandDetails(e):Wl`<div class="transcript-text">${e.text}</div>`}
2038
2080
  <div class="transcript-actions">
2039
2081
  <button
2040
2082
  class="transcript-action-btn copy"
2041
2083
  @click="${t=>this.handleCopy(this.getCopyText(e),t)}"
2042
2084
  >
2043
- ${Uu(12)} Copy
2085
+ ${Fu(12)} Copy
2044
2086
  </button>
2045
2087
  <button
2046
2088
  class="transcript-action-btn delete"
2047
2089
  @click="${()=>this.handleDelete(e.id)}"
2048
2090
  >
2049
- ${((e=14)=>Ru('<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/>',e))(12)} Delete
2091
+ ${((e=14)=>Pu('<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/>',e))(12)} Delete
2050
2092
  </button>
2051
2093
  </div>
2052
2094
  </div>
@@ -2055,7 +2097,7 @@
2055
2097
  <button class="clear-all-button" @click="${this.handleClearAll}">
2056
2098
  Clear All History
2057
2099
  </button>
2058
- `}};il([gu()],Yu.prototype,"transcripts",void 0),Yu=il([uu("speechos-history-tab")],Yu);let Qu=class extends du{static{this.styles=[fu,cl`
2100
+ `}};nl([fu()],Qu.prototype,"transcripts",void 0),Qu=nl([hu("speechos-history-tab")],Qu);let Xu=class extends lu{static{this.styles=[vu,dl`
2059
2101
  :host {
2060
2102
  display: block;
2061
2103
  }
@@ -2074,21 +2116,21 @@
2074
2116
  gap: 8px;
2075
2117
  font-size: 15px;
2076
2118
  font-weight: 600;
2077
- color: white;
2119
+ color: #171717;
2078
2120
  margin-bottom: 10px;
2079
2121
  }
2080
2122
 
2081
2123
  .help-title.dictate {
2082
- color: #34d399;
2124
+ color: #0f766e;
2083
2125
  }
2084
2126
 
2085
2127
  .help-title.edit {
2086
- color: #a78bfa;
2128
+ color: #7c3aed;
2087
2129
  }
2088
2130
 
2089
2131
  .help-text {
2090
2132
  font-size: 13px;
2091
- color: rgba(255, 255, 255, 0.6);
2133
+ color: #525252;
2092
2134
  line-height: 1.6;
2093
2135
  margin-bottom: 10px;
2094
2136
  }
@@ -2105,24 +2147,24 @@
2105
2147
  }
2106
2148
 
2107
2149
  .help-example {
2108
- background: rgba(255, 255, 255, 0.04);
2109
- border: 1px solid rgba(255, 255, 255, 0.06);
2150
+ background: #ffffff;
2151
+ border: 1px solid #e5e5e5;
2110
2152
  border-radius: 6px;
2111
2153
  padding: 8px 12px;
2112
2154
  font-size: 12px;
2113
- color: rgba(255, 255, 255, 0.5);
2155
+ color: #525252;
2114
2156
  font-style: italic;
2115
2157
  }
2116
2158
 
2117
2159
  .help-title.languages {
2118
- background: linear-gradient(135deg, #34d399 0%, #a78bfa 100%);
2160
+ background: linear-gradient(135deg, #0f766e 0%, #1d4ed8 100%);
2119
2161
  -webkit-background-clip: text;
2120
2162
  -webkit-text-fill-color: transparent;
2121
2163
  background-clip: text;
2122
2164
  }
2123
- `]}render(){return zl`
2165
+ `]}render(){return Wl`
2124
2166
  <div class="help-section">
2125
- <div class="help-title dictate">${Iu(18)} Dictate</div>
2167
+ <div class="help-title dictate">${Ou(18)} Dictate</div>
2126
2168
  <div class="help-text">
2127
2169
  Speak naturally and your words are transcribed into polished text—no
2128
2170
  filler words, perfect punctuation.
@@ -2130,7 +2172,7 @@
2130
2172
  </div>
2131
2173
 
2132
2174
  <div class="help-section">
2133
- <div class="help-title edit">${Ou(18)} Edit</div>
2175
+ <div class="help-title edit">${Au(18)} Edit</div>
2134
2176
  <div class="help-text">
2135
2177
  Say anything you want and we'll make it happen. Select specific text
2136
2178
  to edit just that part, or leave nothing selected to transform the
@@ -2150,7 +2192,7 @@
2150
2192
  </div>
2151
2193
 
2152
2194
  <div class="help-section">
2153
- <div class="help-title languages">${Fu(18)} Languages</div>
2195
+ <div class="help-title languages">${ju(18)} Languages</div>
2154
2196
  <div class="help-text">
2155
2197
  Configure your input and output languages in Settings. SpeechOS
2156
2198
  supports 33+ languages with automatic translation—speak in one
@@ -2161,7 +2203,7 @@
2161
2203
  <span class="help-example">Speak Spanish → French text</span>
2162
2204
  </div>
2163
2205
  </div>
2164
- `}};Qu=il([uu("speechos-help-tab")],Qu);let Xu=class extends du{static{this.styles=[fu,cl`
2206
+ `}};Xu=nl([hu("speechos-help-tab")],Xu);let Zu=class extends lu{static{this.styles=[vu,dl`
2165
2207
  :host {
2166
2208
  display: block;
2167
2209
  }
@@ -2177,7 +2219,7 @@
2177
2219
  width: 36px;
2178
2220
  height: 36px;
2179
2221
  border-radius: 10px;
2180
- background: linear-gradient(135deg, #10b981 0%, #8b5cf6 100%);
2222
+ background: linear-gradient(135deg, #14b8a6 0%, #2563eb 100%);
2181
2223
  display: flex;
2182
2224
  align-items: center;
2183
2225
  justify-content: center;
@@ -2192,13 +2234,13 @@
2192
2234
  .about-logo-text {
2193
2235
  font-size: 22px;
2194
2236
  font-weight: 500;
2195
- color: white;
2237
+ color: #171717;
2196
2238
  letter-spacing: -0.02em;
2197
2239
  }
2198
2240
 
2199
2241
  .logo-os {
2200
2242
  font-weight: 700;
2201
- background: linear-gradient(135deg, #34d399 0%, #a78bfa 100%);
2243
+ background: linear-gradient(135deg, #14b8a6 0%, #2563eb 100%);
2202
2244
  -webkit-background-clip: text;
2203
2245
  -webkit-text-fill-color: transparent;
2204
2246
  background-clip: text;
@@ -2206,7 +2248,7 @@
2206
2248
 
2207
2249
  .about-description {
2208
2250
  font-size: 14px;
2209
- color: rgba(255, 255, 255, 0.65);
2251
+ color: #525252;
2210
2252
  line-height: 1.7;
2211
2253
  margin-bottom: 24px;
2212
2254
  }
@@ -2224,21 +2266,31 @@
2224
2266
  align-items: center;
2225
2267
  gap: 8px;
2226
2268
  padding: 12px 18px;
2227
- background: linear-gradient(135deg, #10b981 0%, #059669 100%);
2269
+ background: #0d9488;
2228
2270
  border-radius: 10px;
2229
2271
  color: white;
2230
2272
  font-size: 14px;
2231
2273
  font-weight: 600;
2274
+ letter-spacing: 0.01em;
2232
2275
  text-decoration: none;
2233
- transition: all 0.2s ease;
2234
- box-shadow: 0 4px 12px rgba(16, 185, 129, 0.25);
2276
+ transition: all 0.15s ease;
2277
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
2235
2278
  }
2236
2279
 
2237
2280
  .about-link:hover {
2238
- transform: translateY(-1px);
2239
- box-shadow: 0 6px 16px rgba(16, 185, 129, 0.35);
2281
+ background: #0f766e;
2282
+ box-shadow: 0 4px 12px rgba(13, 148, 136, 0.25);
2283
+ }
2284
+
2285
+ .about-link:focus {
2286
+ outline: none;
2287
+ box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px #0d9488;
2240
2288
  }
2241
- `]}render(){return zl`
2289
+
2290
+ .about-link:active {
2291
+ transform: scale(0.98);
2292
+ }
2293
+ `]}render(){return Wl`
2242
2294
  <div class="about-logo">
2243
2295
  <div class="logo-icon">
2244
2296
  <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -2270,9 +2322,9 @@
2270
2322
  rel="noopener noreferrer"
2271
2323
  class="about-link"
2272
2324
  >
2273
- Visit SpeechOS ${((e=14)=>Ru('<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',e))(14)}
2325
+ Visit SpeechOS ${((e=14)=>Pu('<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',e))(14)}
2274
2326
  </a>
2275
- `}};Xu=il([uu("speechos-about-tab")],Xu);const Zu=12;let eh=class extends du{constructor(){super(...arguments),this.active=!1,this.deviceId="",this.levels=new Array(Zu).fill(0),this.error=null,this.mediaStream=null,this.audioContext=null,this.analyser=null,this.animationId=null,this.dataArray=null,this.smoothedLevels=new Array(Zu).fill(0)}static{this.styles=[fu,cl`
2327
+ `}};Zu=nl([hu("speechos-about-tab")],Zu);const eh=12;let th=class extends lu{constructor(){super(...arguments),this.active=!1,this.deviceId="",this.levels=new Array(eh).fill(0),this.error=null,this.mediaStream=null,this.audioContext=null,this.analyser=null,this.animationId=null,this.dataArray=null,this.smoothedLevels=new Array(eh).fill(0)}static{this.styles=[vu,dl`
2276
2328
  :host {
2277
2329
  display: block;
2278
2330
  }
@@ -2284,20 +2336,21 @@
2284
2336
  gap: 3px;
2285
2337
  height: 32px;
2286
2338
  padding: 8px 12px;
2287
- background: rgba(0, 0, 0, 0.2);
2339
+ background: #ffffff;
2340
+ border: 2px solid #e5e5e5;
2288
2341
  border-radius: 8px;
2289
2342
  }
2290
2343
 
2291
2344
  .meter-bar {
2292
2345
  width: 6px;
2293
2346
  min-height: 4px;
2294
- background: rgba(255, 255, 255, 0.2);
2347
+ background: #d4d4d4;
2295
2348
  border-radius: 2px;
2296
2349
  transition: height 50ms ease-out, background 100ms ease;
2297
2350
  }
2298
2351
 
2299
2352
  .meter-bar.active {
2300
- background: var(--speechos-primary);
2353
+ background: #10b981;
2301
2354
  }
2302
2355
 
2303
2356
  .meter-inactive {
@@ -2306,29 +2359,30 @@
2306
2359
  justify-content: center;
2307
2360
  height: 32px;
2308
2361
  padding: 8px 12px;
2309
- background: rgba(0, 0, 0, 0.2);
2362
+ background: #ffffff;
2363
+ border: 2px solid #e5e5e5;
2310
2364
  border-radius: 8px;
2311
- color: rgba(255, 255, 255, 0.4);
2365
+ color: #737373;
2312
2366
  font-size: 13px;
2313
2367
  }
2314
2368
 
2315
2369
  .meter-error {
2316
- color: #f87171;
2370
+ color: #dc2626;
2317
2371
  }
2318
- `]}updated(e){(e.has("active")||e.has("deviceId"))&&(this.active?this.startMonitoring():this.stopMonitoring())}disconnectedCallback(){super.disconnectedCallback(),this.stopMonitoring()}async startMonitoring(){this.error=null;try{this.stopMonitoring();const e={audio:!this.deviceId||{deviceId:{exact:this.deviceId}}};this.mediaStream=await navigator.mediaDevices.getUserMedia(e),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.analyser.smoothingTimeConstant=.8;this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.analyser),this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.updateLevels()}catch(e){console.error("[SpeechOS] Audio monitoring error:",e),e instanceof Error?"NotAllowedError"===e.name?this.error="Microphone access denied":"NotFoundError"===e.name?this.error="Microphone not found":this.error="Failed to access microphone":this.error="Failed to access microphone"}}stopMonitoring(){null!==this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.analyser=null,this.dataArray=null,this.levels=new Array(Zu).fill(0),this.smoothedLevels=new Array(Zu).fill(0)}updateLevels(){if(!this.analyser||!this.dataArray)return;this.analyser.getByteFrequencyData(this.dataArray);const e=this.dataArray.length,t=Math.floor(e/24),i=[];for(let n=0;n<Zu;n++){const s=n*t,o=s+t;let r=0;for(let t=s;t<o&&t<e;t++)r+=this.dataArray[t];const a=r/t,c=Math.min(1,a/255*1.5);this.smoothedLevels[n]=.3*this.smoothedLevels[n]+.7*c,i.push(this.smoothedLevels[n])}this.levels=i,this.animationId=requestAnimationFrame(()=>this.updateLevels())}getBarClass(e){return e<.05?"":"active"}render(){return this.error?zl`
2372
+ `]}updated(e){(e.has("active")||e.has("deviceId"))&&(this.active?this.startMonitoring():this.stopMonitoring())}disconnectedCallback(){super.disconnectedCallback(),this.stopMonitoring()}async startMonitoring(){this.error=null;try{this.stopMonitoring();const e={audio:!this.deviceId||{deviceId:{exact:this.deviceId}}};this.mediaStream=await navigator.mediaDevices.getUserMedia(e),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.analyser.smoothingTimeConstant=.8;this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.analyser),this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.updateLevels()}catch(e){console.error("[SpeechOS] Audio monitoring error:",e),e instanceof Error?"NotAllowedError"===e.name?this.error="Microphone access denied":"NotFoundError"===e.name?this.error="Microphone not found":this.error="Failed to access microphone":this.error="Failed to access microphone"}}stopMonitoring(){null!==this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.analyser=null,this.dataArray=null,this.levels=new Array(eh).fill(0),this.smoothedLevels=new Array(eh).fill(0)}updateLevels(){if(!this.analyser||!this.dataArray)return;this.analyser.getByteFrequencyData(this.dataArray);const e=this.dataArray.length,t=Math.floor(e/24),i=[];for(let n=0;n<eh;n++){const s=n*t,o=s+t;let r=0;for(let t=s;t<o&&t<e;t++)r+=this.dataArray[t];const a=r/t,c=Math.min(1,a/255*1.5);this.smoothedLevels[n]=.3*this.smoothedLevels[n]+.7*c,i.push(this.smoothedLevels[n])}this.levels=i,this.animationId=requestAnimationFrame(()=>this.updateLevels())}getBarClass(e){return e<.05?"":"active"}render(){return this.error?Wl`
2319
2373
  <div class="meter-inactive meter-error">${this.error}</div>
2320
- `:this.active?zl`
2374
+ `:this.active?Wl`
2321
2375
  <div class="meter-container">
2322
- ${this.levels.map(e=>zl`
2376
+ ${this.levels.map(e=>Wl`
2323
2377
  <div
2324
2378
  class="meter-bar ${this.getBarClass(e)}"
2325
2379
  style="height: ${Math.max(4,28*e)}px"
2326
2380
  ></div>
2327
2381
  `)}
2328
2382
  </div>
2329
- `:zl`
2383
+ `:Wl`
2330
2384
  <div class="meter-inactive">Waiting for microphone access...</div>
2331
- `}};il([mu({type:Boolean})],eh.prototype,"active",void 0),il([mu({type:String})],eh.prototype,"deviceId",void 0),il([gu()],eh.prototype,"levels",void 0),il([gu()],eh.prototype,"error",void 0),eh=il([uu("speechos-audio-level-meter")],eh);let th=class extends du{constructor(){super(...arguments),this.audioDevices=[],this.selectedDeviceId="",this.selectedInputLanguageCode="en-US",this.selectedOutputLanguageCode="en-US",this.isTestingMic=!1,this.showSavedIndicator=!1,this.permissionGranted=!1,this.smartFormatEnabled=!0,this.savedIndicatorTimeout=null,this.unsubscribeSettingsLoaded=null}static{this.styles=[fu,cl`
2385
+ `}};nl([gu({type:Boolean})],th.prototype,"active",void 0),nl([gu({type:String})],th.prototype,"deviceId",void 0),nl([fu()],th.prototype,"levels",void 0),nl([fu()],th.prototype,"error",void 0),th=nl([hu("speechos-audio-level-meter")],th);let ih=class extends lu{constructor(){super(...arguments),this.audioDevices=[],this.selectedDeviceId="",this.selectedInputLanguageCode="en-US",this.selectedOutputLanguageCode="en-US",this.isTestingMic=!1,this.showSavedIndicator=!1,this.permissionGranted=!1,this.smartFormatEnabled=!0,this.savedIndicatorTimeout=null,this.unsubscribeSettingsLoaded=null}static{this.styles=[vu,dl`
2332
2386
  :host {
2333
2387
  display: block;
2334
2388
  }
@@ -2349,18 +2403,18 @@
2349
2403
  }
2350
2404
 
2351
2405
  .settings-section-icon {
2352
- color: #34d399;
2406
+ color: #0d9488;
2353
2407
  }
2354
2408
 
2355
2409
  .settings-section-title {
2356
2410
  font-size: 14px;
2357
2411
  font-weight: 600;
2358
- color: white;
2412
+ color: #171717;
2359
2413
  }
2360
2414
 
2361
2415
  .settings-section-description {
2362
2416
  font-size: 13px;
2363
- color: rgba(255, 255, 255, 0.45);
2417
+ color: #525252;
2364
2418
  line-height: 1.5;
2365
2419
  margin-bottom: 14px;
2366
2420
  }
@@ -2389,10 +2443,10 @@
2389
2443
  .settings-select {
2390
2444
  width: 100%;
2391
2445
  padding: 12px 40px 12px 14px;
2392
- background: rgba(0, 0, 0, 0.3);
2393
- border: 1px solid rgba(255, 255, 255, 0.08);
2446
+ background: #ffffff;
2447
+ border: 1px solid #d4d4d4;
2394
2448
  border-radius: 10px;
2395
- color: white;
2449
+ color: #171717;
2396
2450
  font-size: 14px;
2397
2451
  font-family: inherit;
2398
2452
  cursor: pointer;
@@ -2402,34 +2456,44 @@
2402
2456
  }
2403
2457
 
2404
2458
  .settings-select:hover {
2405
- border-color: rgba(255, 255, 255, 0.15);
2406
- background: rgba(0, 0, 0, 0.4);
2459
+ border-color: #a3a3a3;
2460
+ background: #ffffff;
2407
2461
  }
2408
2462
 
2409
2463
  .settings-select:focus {
2410
2464
  outline: none;
2411
- border-color: #34d399;
2412
- box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.15);
2465
+ border-color: #0d9488;
2466
+ box-shadow: 0 0 0 3px rgba(13, 148, 136, 0.15);
2413
2467
  }
2414
2468
 
2415
2469
  .settings-select option {
2416
- background: #1a1d24;
2417
- color: white;
2470
+ background: #ffffff;
2471
+ color: #171717;
2418
2472
  padding: 8px;
2419
2473
  }
2420
2474
 
2475
+ .settings-select:disabled {
2476
+ opacity: 0.4;
2477
+ cursor: not-allowed;
2478
+ }
2479
+
2480
+ .settings-select:disabled:hover {
2481
+ border-color: #d4d4d4;
2482
+ background: #ffffff;
2483
+ }
2484
+
2421
2485
  .settings-select-arrow {
2422
2486
  position: absolute;
2423
2487
  right: 14px;
2424
2488
  top: 50%;
2425
2489
  transform: translateY(-50%);
2426
2490
  pointer-events: none;
2427
- color: rgba(255, 255, 255, 0.4);
2491
+ color: #737373;
2428
2492
  }
2429
2493
 
2430
2494
  .settings-permission-note {
2431
2495
  font-size: 12px;
2432
- color: rgba(255, 255, 255, 0.4);
2496
+ color: #737373;
2433
2497
  margin-top: 10px;
2434
2498
  font-style: italic;
2435
2499
  }
@@ -2439,7 +2503,7 @@
2439
2503
  align-items: center;
2440
2504
  gap: 4px;
2441
2505
  font-size: 11px;
2442
- color: #34d399;
2506
+ color: #059669;
2443
2507
  font-weight: 500;
2444
2508
  opacity: 0;
2445
2509
  transition: opacity 0.2s ease;
@@ -2455,28 +2519,34 @@
2455
2519
  align-items: center;
2456
2520
  justify-content: space-between;
2457
2521
  padding: 12px 14px;
2458
- background: rgba(0, 0, 0, 0.3);
2459
- border: 1px solid rgba(255, 255, 255, 0.08);
2522
+ background: #ffffff;
2523
+ border: 1px solid #e5e5e5;
2460
2524
  border-radius: 10px;
2525
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
2461
2526
  }
2462
2527
 
2463
2528
  .settings-toggle-label {
2464
2529
  font-size: 14px;
2465
- color: white;
2530
+ color: #171717;
2466
2531
  }
2467
2532
 
2468
2533
  .settings-toggle {
2469
2534
  position: relative;
2470
2535
  width: 44px;
2471
2536
  height: 24px;
2472
- background: rgba(255, 255, 255, 0.1);
2537
+ background: #d4d4d4;
2473
2538
  border-radius: 12px;
2474
2539
  cursor: pointer;
2475
2540
  transition: background 0.2s ease;
2476
2541
  }
2477
2542
 
2478
2543
  .settings-toggle.active {
2479
- background: #34d399;
2544
+ background: #0d9488;
2545
+ }
2546
+
2547
+ .settings-toggle:focus {
2548
+ outline: none;
2549
+ box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px #0d9488;
2480
2550
  }
2481
2551
 
2482
2552
  .settings-toggle-knob {
@@ -2494,14 +2564,15 @@
2494
2564
  .settings-toggle.active .settings-toggle-knob {
2495
2565
  transform: translateX(20px);
2496
2566
  }
2497
- `]}connectedCallback(){super.connectedCallback(),this.loadSettings(),this.unsubscribeSettingsLoaded=gc.on("settings:loaded",()=>{this.loadSettings()})}disconnectedCallback(){super.disconnectedCallback(),this.savedIndicatorTimeout&&clearTimeout(this.savedIndicatorTimeout),this.unsubscribeSettingsLoaded&&(this.unsubscribeSettingsLoaded(),this.unsubscribeSettingsLoaded=null),this.isTestingMic=!1}activate(){this.startMicPreview()}deactivate(){this.isTestingMic=!1}async loadSettings(){this.selectedDeviceId=$d(),this.selectedInputLanguageCode=Qc(),this.selectedOutputLanguageCode=Zc(),this.smartFormatEnabled=sd(),await this.loadAudioDevices()}async loadAudioDevices(){try{const e=await qd(),t=e.some(e=>e.label&&e.label.length>0);this.permissionGranted=t,this.audioDevices=e}catch(e){console.error("[SpeechOS] Failed to enumerate audio devices:",e),this.audioDevices=[]}}async requestMicPermission(){try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),this.permissionGranted=!0,await this.loadAudioDevices()}catch(e){console.error("[SpeechOS] Microphone permission denied:",e)}}async startMicPreview(){this.permissionGranted||await this.requestMicPermission(),this.permissionGranted&&(this.isTestingMic=!0)}showSaved(){this.showSavedIndicator=!0,this.savedIndicatorTimeout&&clearTimeout(this.savedIndicatorTimeout),this.savedIndicatorTimeout=setTimeout(()=>{this.showSavedIndicator=!1},2e3)}handleInputLanguageChange(e){const t=e.target;this.selectedInputLanguageCode=t.value,Xc(this.selectedInputLanguageCode),this.showSaved()}handleOutputLanguageChange(e){const t=e.target;this.selectedOutputLanguageCode=t.value,ed(this.selectedOutputLanguageCode),this.showSaved()}handleDeviceChange(e){const t=e.target;this.selectedDeviceId=t.value,Vd(this.selectedDeviceId),this.showSaved(),this.isTestingMic&&(this.isTestingMic=!1,requestAnimationFrame(()=>{this.isTestingMic=!0}))}handleSmartFormatToggle(){this.smartFormatEnabled=!this.smartFormatEnabled,od(this.smartFormatEnabled),this.showSaved()}renderLanguageSelector(e,t){return zl`
2567
+ `]}connectedCallback(){super.connectedCallback(),this.loadSettings(),this.unsubscribeSettingsLoaded=gc.on("settings:loaded",()=>{this.loadSettings()})}disconnectedCallback(){super.disconnectedCallback(),this.savedIndicatorTimeout&&clearTimeout(this.savedIndicatorTimeout),this.unsubscribeSettingsLoaded&&(this.unsubscribeSettingsLoaded(),this.unsubscribeSettingsLoaded=null),this.isTestingMic=!1}activate(){this.startMicPreview()}deactivate(){this.isTestingMic=!1}async loadSettings(){this.selectedDeviceId=Vd(),this.selectedInputLanguageCode=Xc(),this.selectedOutputLanguageCode=ed(),this.smartFormatEnabled=od(),await this.loadAudioDevices()}async loadAudioDevices(){try{const e=await Hd(),t=e.some(e=>e.label&&e.label.length>0);this.permissionGranted=t,this.audioDevices=e}catch(e){console.error("[SpeechOS] Failed to enumerate audio devices:",e),this.audioDevices=[]}}async requestMicPermission(){try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),this.permissionGranted=!0,await this.loadAudioDevices()}catch(e){console.error("[SpeechOS] Microphone permission denied:",e)}}async startMicPreview(){this.permissionGranted||await this.requestMicPermission(),this.permissionGranted&&(this.isTestingMic=!0)}showSaved(){this.showSavedIndicator=!0,this.savedIndicatorTimeout&&clearTimeout(this.savedIndicatorTimeout),this.savedIndicatorTimeout=setTimeout(()=>{this.showSavedIndicator=!1},2e3)}handleInputLanguageChange(e){const t=e.target;this.selectedInputLanguageCode=t.value,Zc(this.selectedInputLanguageCode),this.showSaved()}handleOutputLanguageChange(e){const t=e.target;this.selectedOutputLanguageCode=t.value,td(this.selectedOutputLanguageCode),this.showSaved()}handleDeviceChange(e){const t=e.target;this.selectedDeviceId=t.value,qd(this.selectedDeviceId),this.showSaved(),this.isTestingMic&&(this.isTestingMic=!1,requestAnimationFrame(()=>{this.isTestingMic=!0}))}handleSmartFormatToggle(){this.smartFormatEnabled=!this.smartFormatEnabled,rd(this.smartFormatEnabled),this.showSaved()}renderLanguageSelector(e,t,i=!1){return Wl`
2498
2568
  <div class="settings-select-wrapper">
2499
2569
  <select
2500
2570
  class="settings-select"
2501
2571
  .value="${e}"
2502
2572
  @change="${t}"
2573
+ ?disabled="${i}"
2503
2574
  >
2504
- ${Wc.map(t=>zl`
2575
+ ${Gc.map(t=>Wl`
2505
2576
  <option
2506
2577
  value="${t.code}"
2507
2578
  ?selected="${t.code===e}"
@@ -2523,7 +2594,7 @@
2523
2594
  </svg>
2524
2595
  </div>
2525
2596
  </div>
2526
- `}renderDeviceSelector(){return zl`
2597
+ `}renderDeviceSelector(){return Wl`
2527
2598
  <div class="settings-select-wrapper">
2528
2599
  <select
2529
2600
  class="settings-select"
@@ -2531,7 +2602,7 @@
2531
2602
  @change="${this.handleDeviceChange}"
2532
2603
  >
2533
2604
  <option value="">System Default</option>
2534
- ${this.audioDevices.map(e=>zl`
2605
+ ${this.audioDevices.map(e=>Wl`
2535
2606
  <option value="${e.deviceId}">
2536
2607
  ${e.label||`Microphone ${e.deviceId.slice(0,8)}`}
2537
2608
  </option>
@@ -2550,7 +2621,7 @@
2550
2621
  </svg>
2551
2622
  </div>
2552
2623
  </div>
2553
- `}renderPermissionRequest(){return zl`
2624
+ `}renderPermissionRequest(){return Wl`
2554
2625
  <div class="settings-select-wrapper">
2555
2626
  <select class="settings-select" disabled>
2556
2627
  <option>Requesting microphone access...</option>
@@ -2571,10 +2642,10 @@
2571
2642
  <p class="settings-permission-note">
2572
2643
  Please allow microphone access in your browser to see available devices.
2573
2644
  </p>
2574
- `}render(){return zl`
2645
+ `}render(){return Wl`
2575
2646
  <div class="settings-section">
2576
2647
  <div class="settings-section-header">
2577
- <span class="settings-section-icon">${Pu(18)}</span>
2648
+ <span class="settings-section-icon">${Iu(18)}</span>
2578
2649
  <span class="settings-section-title">Microphone</span>
2579
2650
  <span
2580
2651
  class="settings-saved-indicator ${this.showSavedIndicator?"visible":""}"
@@ -2585,7 +2656,7 @@
2585
2656
  <div class="settings-section-description">
2586
2657
  Choose which microphone to use for dictation and editing.
2587
2658
  </div>
2588
- ${this.permissionGranted?zl`
2659
+ ${this.permissionGranted?Wl`
2589
2660
  <div class="settings-mic-row">
2590
2661
  ${this.renderDeviceSelector()}
2591
2662
  <speechos-audio-level-meter
@@ -2598,13 +2669,13 @@
2598
2669
 
2599
2670
  <div class="settings-section">
2600
2671
  <div class="settings-section-header">
2601
- <span class="settings-section-icon">${((e=18)=>Ru('<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/><path d="M4 17v2"/><path d="M5 18H3"/>',e))(18)}</span>
2672
+ <span class="settings-section-icon">${((e=18)=>Pu('<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/><path d="M4 17v2"/><path d="M5 18H3"/>',e))(18)}</span>
2602
2673
  <span class="settings-section-title">Smart Format</span>
2603
2674
  </div>
2604
2675
  <div class="settings-section-description">
2605
2676
  AI automatically removes filler words, adds punctuation, and polishes
2606
2677
  your text. Disable for raw transcription output. Note: disabling also
2607
- turns off text snippets.
2678
+ turns off text snippets and output language translation.
2608
2679
  </div>
2609
2680
  <div class="settings-toggle-row">
2610
2681
  <span class="settings-toggle-label">Enable AI formatting</span>
@@ -2623,7 +2694,7 @@
2623
2694
 
2624
2695
  <div class="settings-section">
2625
2696
  <div class="settings-section-header">
2626
- <span class="settings-section-icon">${Fu(18)}</span>
2697
+ <span class="settings-section-icon">${ju(18)}</span>
2627
2698
  <span class="settings-section-title">Input Language</span>
2628
2699
  </div>
2629
2700
  <div class="settings-section-description">
@@ -2635,16 +2706,16 @@
2635
2706
 
2636
2707
  <div class="settings-section">
2637
2708
  <div class="settings-section-header">
2638
- <span class="settings-section-icon">${Fu(18)}</span>
2709
+ <span class="settings-section-icon">${ju(18)}</span>
2639
2710
  <span class="settings-section-title">Output Language</span>
2640
2711
  </div>
2641
2712
  <div class="settings-section-description">
2642
2713
  The language for your transcribed text. Usually the same as input, but
2643
- can differ for translation.
2714
+ can differ for translation.${this.smartFormatEnabled?"":" Requires Smart Format to be enabled."}
2644
2715
  </div>
2645
- ${this.renderLanguageSelector(this.selectedOutputLanguageCode,this.handleOutputLanguageChange.bind(this))}
2716
+ ${this.renderLanguageSelector(this.smartFormatEnabled?this.selectedOutputLanguageCode:this.selectedInputLanguageCode,this.handleOutputLanguageChange.bind(this),!this.smartFormatEnabled)}
2646
2717
  </div>
2647
- `}};il([gu()],th.prototype,"audioDevices",void 0),il([gu()],th.prototype,"selectedDeviceId",void 0),il([gu()],th.prototype,"selectedInputLanguageCode",void 0),il([gu()],th.prototype,"selectedOutputLanguageCode",void 0),il([gu()],th.prototype,"isTestingMic",void 0),il([gu()],th.prototype,"showSavedIndicator",void 0),il([gu()],th.prototype,"permissionGranted",void 0),il([gu()],th.prototype,"smartFormatEnabled",void 0),th=il([uu("speechos-settings-tab")],th);let ih=class extends du{constructor(){super(...arguments),this.snippets=[],this.showForm=!1,this.editingId=null,this.trigger="",this.expansion="",this.error="",this.unsubscribeSettingsLoaded=null}static{this.styles=[fu,Ku,Ju,cl`
2718
+ `}};nl([fu()],ih.prototype,"audioDevices",void 0),nl([fu()],ih.prototype,"selectedDeviceId",void 0),nl([fu()],ih.prototype,"selectedInputLanguageCode",void 0),nl([fu()],ih.prototype,"selectedOutputLanguageCode",void 0),nl([fu()],ih.prototype,"isTestingMic",void 0),nl([fu()],ih.prototype,"showSavedIndicator",void 0),nl([fu()],ih.prototype,"permissionGranted",void 0),nl([fu()],ih.prototype,"smartFormatEnabled",void 0),ih=nl([hu("speechos-settings-tab")],ih);let nh=class extends lu{constructor(){super(...arguments),this.snippets=[],this.showForm=!1,this.editingId=null,this.trigger="",this.expansion="",this.error="",this.unsubscribeSettingsLoaded=null}static{this.styles=[vu,Ju,Yu,dl`
2648
2719
  :host {
2649
2720
  display: block;
2650
2721
  }
@@ -2656,17 +2727,18 @@
2656
2727
  }
2657
2728
 
2658
2729
  .snippet-item {
2659
- background: rgba(255, 255, 255, 0.04);
2660
- border: 1px solid rgba(255, 255, 255, 0.06);
2730
+ background: #ffffff;
2731
+ border: 1px solid #e5e5e5;
2661
2732
  border-radius: 10px;
2662
2733
  padding: 14px;
2663
2734
  transition: all 0.15s ease;
2664
2735
  position: relative;
2736
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
2665
2737
  }
2666
2738
 
2667
2739
  .snippet-item:hover {
2668
- background: rgba(255, 255, 255, 0.06);
2669
- border-color: rgba(255, 255, 255, 0.1);
2740
+ border-color: #d4d4d4;
2741
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
2670
2742
  }
2671
2743
 
2672
2744
  .snippet-trigger {
@@ -2679,7 +2751,7 @@
2679
2751
  .snippet-trigger-text {
2680
2752
  font-size: 14px;
2681
2753
  font-weight: 600;
2682
- color: #34d399;
2754
+ color: #0d9488;
2683
2755
  }
2684
2756
 
2685
2757
  .snippet-trigger-text::before {
@@ -2697,12 +2769,12 @@
2697
2769
  align-items: flex-start;
2698
2770
  gap: 8px;
2699
2771
  font-size: 13px;
2700
- color: rgba(255, 255, 255, 0.65);
2772
+ color: #525252;
2701
2773
  line-height: 1.5;
2702
2774
  }
2703
2775
 
2704
2776
  .snippet-expansion-arrow {
2705
- color: rgba(255, 255, 255, 0.3);
2777
+ color: #a3a3a3;
2706
2778
  flex-shrink: 0;
2707
2779
  margin-top: 2px;
2708
2780
  }
@@ -2731,15 +2803,15 @@
2731
2803
  display: flex;
2732
2804
  align-items: center;
2733
2805
  justify-content: center;
2734
- color: rgba(255, 255, 255, 0.4);
2806
+ color: #737373;
2735
2807
  transition: all 0.15s ease;
2736
2808
  }
2737
2809
 
2738
2810
  .edit-btn:hover {
2739
- background: rgba(52, 211, 153, 0.15);
2740
- color: #34d399;
2811
+ background: rgba(13, 148, 136, 0.1);
2812
+ color: #0d9488;
2741
2813
  }
2742
- `]}connectedCallback(){super.connectedCallback(),this.loadSnippets(),this.unsubscribeSettingsLoaded=gc.on("settings:loaded",()=>{this.loadSnippets()})}disconnectedCallback(){super.disconnectedCallback(),this.unsubscribeSettingsLoaded&&(this.unsubscribeSettingsLoaded(),this.unsubscribeSettingsLoaded=null)}refresh(){this.loadSnippets()}resetForm(){this.showForm=!1,this.editingId=null,this.trigger="",this.expansion="",this.error=""}loadSnippets(){this.snippets=Ed.getSnippets()}handleAddClick(){this.editingId=null,this.trigger="",this.expansion="",this.showForm=!0,this.error=""}handleEditClick(e){this.editingId=e.id,this.trigger=e.trigger,this.expansion=e.expansion,this.showForm=!0,this.error=""}handleCancel(){this.resetForm()}handleTriggerInput(e){const t=e.target;this.trigger=t.value,this.error=""}handleExpansionInput(e){const t=e.target;this.expansion=t.value,this.error=""}handleSave(){const e=this.editingId?Ed.updateSnippet(this.editingId,this.trigger,this.expansion):Ed.addSnippet(this.trigger,this.expansion);e.success?(this.loadSnippets(),this.resetForm()):this.error=e.error.message}handleDelete(e){Ed.deleteSnippet(e),this.loadSnippets()}renderForm(){const e=this.trigger.length,t=this.expansion.length,i=e>0&&e<=30&&t>0&&t<=300;return zl`
2814
+ `]}connectedCallback(){super.connectedCallback(),this.loadSnippets(),this.unsubscribeSettingsLoaded=gc.on("settings:loaded",()=>{this.loadSnippets()})}disconnectedCallback(){super.disconnectedCallback(),this.unsubscribeSettingsLoaded&&(this.unsubscribeSettingsLoaded(),this.unsubscribeSettingsLoaded=null)}refresh(){this.loadSnippets()}resetForm(){this.showForm=!1,this.editingId=null,this.trigger="",this.expansion="",this.error=""}loadSnippets(){this.snippets=xd.getSnippets()}handleAddClick(){this.editingId=null,this.trigger="",this.expansion="",this.showForm=!0,this.error=""}handleEditClick(e){this.editingId=e.id,this.trigger=e.trigger,this.expansion=e.expansion,this.showForm=!0,this.error=""}handleCancel(){this.resetForm()}handleTriggerInput(e){const t=e.target;this.trigger=t.value,this.error=""}handleExpansionInput(e){const t=e.target;this.expansion=t.value,this.error=""}handleSave(){const e=this.editingId?xd.updateSnippet(this.editingId,this.trigger,this.expansion):xd.addSnippet(this.trigger,this.expansion);e.success?(this.loadSnippets(),this.resetForm()):this.error=e.error.message}handleDelete(e){xd.deleteSnippet(e),this.loadSnippets()}renderForm(){const e=this.trigger.length,t=this.expansion.length,i=e>0&&e<=30&&t>0&&t<=300;return Wl`
2743
2815
  <div class="add-form">
2744
2816
  <div class="form-group">
2745
2817
  <label class="form-label">Trigger phrase</label>
@@ -2778,7 +2850,7 @@
2778
2850
  </div>
2779
2851
  </div>
2780
2852
 
2781
- ${this.error?zl`<div class="form-error">${this.error}</div>`:""}
2853
+ ${this.error?Wl`<div class="form-error">${this.error}</div>`:""}
2782
2854
 
2783
2855
  <div class="form-actions">
2784
2856
  <button class="form-btn cancel" @click="${this.handleCancel}">
@@ -2793,7 +2865,7 @@
2793
2865
  </button>
2794
2866
  </div>
2795
2867
  </div>
2796
- `}render(){const e=Ed.getSnippetCount(),t=Ed.isAtSnippetLimit();return zl`
2868
+ `}render(){const e=xd.getSnippetCount(),t=xd.isAtSnippetLimit();return Wl`
2797
2869
  <div class="section-header">
2798
2870
  <h3 class="section-title">Text Snippets</h3>
2799
2871
  <p class="section-description">
@@ -2802,9 +2874,9 @@
2802
2874
  </p>
2803
2875
  </div>
2804
2876
 
2805
- ${t?zl`
2877
+ ${t?Wl`
2806
2878
  <div class="limit-warning">
2807
- <span class="limit-warning-icon">${Nu(16)}</span>
2879
+ <span class="limit-warning-icon">${Lu(16)}</span>
2808
2880
  <span class="limit-warning-text">
2809
2881
  You've reached the ${e.max} snippet limit. Delete unused
2810
2882
  snippets to add more.
@@ -2819,22 +2891,22 @@
2819
2891
  ?disabled="${t||this.showForm}"
2820
2892
  @click="${this.handleAddClick}"
2821
2893
  >
2822
- ${$u(14)} Add Snippet
2894
+ ${Vu(14)} Add Snippet
2823
2895
  </button>
2824
2896
  <span class="count-badge">${e.current}/${e.max} used</span>
2825
2897
  </div>
2826
2898
 
2827
- ${0===this.snippets.length?zl`
2899
+ ${0===this.snippets.length?Wl`
2828
2900
  <div class="empty-state">
2829
- <div class="empty-state-icon">${ju(44)}</div>
2901
+ <div class="empty-state-icon">${Bu(44)}</div>
2830
2902
  <div class="empty-state-title">No snippets yet</div>
2831
2903
  <div class="empty-state-text">
2832
2904
  Add your first snippet to speed up your dictation.
2833
2905
  </div>
2834
2906
  </div>
2835
- `:zl`
2907
+ `:Wl`
2836
2908
  <div class="snippet-list">
2837
- ${this.snippets.map(e=>zl`
2909
+ ${this.snippets.map(e=>Wl`
2838
2910
  <div class="snippet-item">
2839
2911
  <div class="snippet-trigger">
2840
2912
  <span class="snippet-trigger-text">${e.trigger}</span>
@@ -2844,14 +2916,14 @@
2844
2916
  @click="${()=>this.handleEditClick(e)}"
2845
2917
  title="Edit snippet"
2846
2918
  >
2847
- ${Ou(14)}
2919
+ ${Au(14)}
2848
2920
  </button>
2849
2921
  <button
2850
2922
  class="delete-btn"
2851
2923
  @click="${()=>this.handleDelete(e.id)}"
2852
2924
  title="Delete snippet"
2853
2925
  >
2854
- ${_u(14)}
2926
+ ${Mu(14)}
2855
2927
  </button>
2856
2928
  </div>
2857
2929
  </div>
@@ -2863,7 +2935,7 @@
2863
2935
  `)}
2864
2936
  </div>
2865
2937
  `}
2866
- `}};il([gu()],ih.prototype,"snippets",void 0),il([gu()],ih.prototype,"showForm",void 0),il([gu()],ih.prototype,"editingId",void 0),il([gu()],ih.prototype,"trigger",void 0),il([gu()],ih.prototype,"expansion",void 0),il([gu()],ih.prototype,"error",void 0),ih=il([uu("speechos-snippets-tab")],ih);let nh=class extends du{constructor(){super(...arguments),this.vocabulary=[],this.showForm=!1,this.term="",this.error="",this.unsubscribeSettingsLoaded=null}static{this.styles=[fu,Ku,Ju,cl`
2938
+ `}};nl([fu()],nh.prototype,"snippets",void 0),nl([fu()],nh.prototype,"showForm",void 0),nl([fu()],nh.prototype,"editingId",void 0),nl([fu()],nh.prototype,"trigger",void 0),nl([fu()],nh.prototype,"expansion",void 0),nl([fu()],nh.prototype,"error",void 0),nh=nl([hu("speechos-snippets-tab")],nh);let sh=class extends lu{constructor(){super(...arguments),this.vocabulary=[],this.showForm=!1,this.term="",this.error="",this.unsubscribeSettingsLoaded=null}static{this.styles=[vu,Ju,Yu,dl`
2867
2939
  :host {
2868
2940
  display: block;
2869
2941
  }
@@ -2880,32 +2952,34 @@
2880
2952
  gap: 8px;
2881
2953
  padding: 8px 12px;
2882
2954
  background: rgba(139, 92, 246, 0.1);
2883
- border: 1px solid rgba(139, 92, 246, 0.2);
2955
+ border: 1px solid rgba(139, 92, 246, 0.25);
2884
2956
  border-radius: 8px;
2885
2957
  transition: all 0.15s ease;
2886
2958
  }
2887
2959
 
2888
2960
  .vocabulary-chip:hover {
2889
2961
  background: rgba(139, 92, 246, 0.15);
2890
- border-color: rgba(139, 92, 246, 0.3);
2962
+ border-color: rgba(139, 92, 246, 0.35);
2891
2963
  }
2892
2964
 
2893
2965
  .vocabulary-chip-text {
2894
2966
  font-size: 13px;
2895
2967
  font-weight: 500;
2896
- color: #c4b5fd;
2968
+ color: #7c3aed;
2897
2969
  }
2898
2970
 
2899
2971
  .vocabulary-chip .delete-btn {
2900
2972
  width: 20px;
2901
2973
  height: 20px;
2902
2974
  margin: -4px -4px -4px 0;
2975
+ color: #737373;
2903
2976
  }
2904
2977
 
2905
2978
  .vocabulary-chip .delete-btn:hover {
2906
2979
  background: rgba(239, 68, 68, 0.2);
2980
+ color: #f87171;
2907
2981
  }
2908
- `]}connectedCallback(){super.connectedCallback(),this.loadVocabulary(),this.unsubscribeSettingsLoaded=gc.on("settings:loaded",()=>{this.loadVocabulary()})}disconnectedCallback(){super.disconnectedCallback(),this.unsubscribeSettingsLoaded&&(this.unsubscribeSettingsLoaded(),this.unsubscribeSettingsLoaded=null)}refresh(){this.loadVocabulary()}resetForm(){this.showForm=!1,this.term="",this.error=""}loadVocabulary(){this.vocabulary=Ud.getVocabulary()}handleAddClick(){this.showForm=!0,this.error=""}handleCancel(){this.resetForm()}handleTermInput(e){const t=e.target;this.term=t.value,this.error=""}handleSave(){const e=Ud.addTerm(this.term);e.success?(this.loadVocabulary(),this.resetForm()):this.error=e.error.message}handleDelete(e){Ud.deleteTerm(e),this.loadVocabulary()}renderForm(){const e=this.term.length,t=e>0&&e<=50;return zl`
2982
+ `]}connectedCallback(){super.connectedCallback(),this.loadVocabulary(),this.unsubscribeSettingsLoaded=gc.on("settings:loaded",()=>{this.loadVocabulary()})}disconnectedCallback(){super.disconnectedCallback(),this.unsubscribeSettingsLoaded&&(this.unsubscribeSettingsLoaded(),this.unsubscribeSettingsLoaded=null)}refresh(){this.loadVocabulary()}resetForm(){this.showForm=!1,this.term="",this.error=""}loadVocabulary(){this.vocabulary=Fd.getVocabulary()}handleAddClick(){this.showForm=!0,this.error=""}handleCancel(){this.resetForm()}handleTermInput(e){const t=e.target;this.term=t.value,this.error=""}handleSave(){const e=Fd.addTerm(this.term);e.success?(this.loadVocabulary(),this.resetForm()):this.error=e.error.message}handleDelete(e){Fd.deleteTerm(e),this.loadVocabulary()}renderForm(){const e=this.term.length,t=e>0&&e<=50;return Wl`
2909
2983
  <div class="add-form">
2910
2984
  <div class="form-group">
2911
2985
  <label class="form-label">Term</label>
@@ -2926,7 +3000,7 @@
2926
3000
  </div>
2927
3001
  </div>
2928
3002
 
2929
- ${this.error?zl`<div class="form-error">${this.error}</div>`:""}
3003
+ ${this.error?Wl`<div class="form-error">${this.error}</div>`:""}
2930
3004
 
2931
3005
  <div class="form-actions">
2932
3006
  <button class="form-btn cancel" @click="${this.handleCancel}">
@@ -2941,7 +3015,7 @@
2941
3015
  </button>
2942
3016
  </div>
2943
3017
  </div>
2944
- `}render(){const e=Ud.getVocabularyCount(),t=Ud.isAtVocabularyLimit();return zl`
3018
+ `}render(){const e=Fd.getVocabularyCount(),t=Fd.isAtVocabularyLimit();return Wl`
2945
3019
  <div class="section-header">
2946
3020
  <h3 class="section-title">Custom Vocabulary</h3>
2947
3021
  <p class="section-description">
@@ -2950,9 +3024,9 @@
2950
3024
  </p>
2951
3025
  </div>
2952
3026
 
2953
- ${t?zl`
3027
+ ${t?Wl`
2954
3028
  <div class="limit-warning">
2955
- <span class="limit-warning-icon">${Nu(16)}</span>
3029
+ <span class="limit-warning-icon">${Lu(16)}</span>
2956
3030
  <span class="limit-warning-text">
2957
3031
  You've reached the ${e.max} term limit. Remove unused terms
2958
3032
  to add more.
@@ -2967,22 +3041,22 @@
2967
3041
  ?disabled="${t||this.showForm}"
2968
3042
  @click="${this.handleAddClick}"
2969
3043
  >
2970
- ${$u(14)} Add Term
3044
+ ${Vu(14)} Add Term
2971
3045
  </button>
2972
3046
  <span class="count-badge">${e.current}/${e.max} used</span>
2973
3047
  </div>
2974
3048
 
2975
- ${0===this.vocabulary.length?zl`
3049
+ ${0===this.vocabulary.length?Wl`
2976
3050
  <div class="empty-state">
2977
- <div class="empty-state-icon">${Bu(44)}</div>
3051
+ <div class="empty-state-icon">${$u(44)}</div>
2978
3052
  <div class="empty-state-title">No custom terms yet</div>
2979
3053
  <div class="empty-state-text">
2980
3054
  Add words that are unique to your work.
2981
3055
  </div>
2982
3056
  </div>
2983
- `:zl`
3057
+ `:Wl`
2984
3058
  <div class="vocabulary-grid">
2985
- ${this.vocabulary.map(e=>zl`
3059
+ ${this.vocabulary.map(e=>Wl`
2986
3060
  <div class="vocabulary-chip">
2987
3061
  <span class="vocabulary-chip-text">${e.term}</span>
2988
3062
  <button
@@ -2990,13 +3064,13 @@
2990
3064
  @click="${()=>this.handleDelete(e.id)}"
2991
3065
  title="Remove term"
2992
3066
  >
2993
- ${_u(12)}
3067
+ ${Mu(12)}
2994
3068
  </button>
2995
3069
  </div>
2996
3070
  `)}
2997
3071
  </div>
2998
3072
  `}
2999
- `}};il([gu()],nh.prototype,"vocabulary",void 0),il([gu()],nh.prototype,"showForm",void 0),il([gu()],nh.prototype,"term",void 0),il([gu()],nh.prototype,"error",void 0),nh=il([uu("speechos-vocabulary-tab")],nh);let sh=class extends du{constructor(){super(...arguments),this.open=!1,this.activeTab="settings",this.mainTabs=[{id:"settings",label:"Settings",icon:Lu(18)},{id:"transcripts",label:"History",icon:Mu(18)},{id:"vocabulary",label:"Vocab",icon:Bu(18)},{id:"snippets",label:"Snippets",icon:ju(18)},{id:"help",label:"Help",icon:Du(18)}],this.bottomTabs=[{id:"about",label:"About",icon:Nu(18)}]}static{this.styles=[fu,Gu]}updated(e){e.has("open")&&(this.open?this.refreshActiveTab():this.resetTabs())}refreshActiveTab(){const e=this.getTabElement();e&&"refresh"in e&&e.refresh(),e&&"activate"in e&&e.activate()}resetTabs(){const e=this.shadowRoot?.querySelector("speechos-snippets-tab"),t=this.shadowRoot?.querySelector("speechos-vocabulary-tab"),i=this.shadowRoot?.querySelector("speechos-settings-tab");e&&"resetForm"in e&&e.resetForm(),t&&"resetForm"in t&&t.resetForm(),i&&"deactivate"in i&&i.deactivate()}getTabElement(){return this.shadowRoot?.querySelector({transcripts:"speechos-history-tab",help:"speechos-help-tab",about:"speechos-about-tab",settings:"speechos-settings-tab",snippets:"speechos-snippets-tab",vocabulary:"speechos-vocabulary-tab"}[this.activeTab])??null}handleOverlayClick(e){e.target===e.currentTarget&&this.close()}handleClose(){this.close()}close(){this.dispatchEvent(new CustomEvent("modal-close",{bubbles:!0,composed:!0}))}handleTabClick(e){const t=this.getTabElement();t&&"deactivate"in t&&t.deactivate(),this.activeTab=e,this.updateComplete.then(()=>{this.refreshActiveTab()})}renderTabContent(){switch(this.activeTab){case"transcripts":return zl`<speechos-history-tab></speechos-history-tab>`;case"help":return zl`<speechos-help-tab></speechos-help-tab>`;case"about":return zl`<speechos-about-tab></speechos-about-tab>`;case"settings":return zl`<speechos-settings-tab></speechos-settings-tab>`;case"snippets":return zl`<speechos-snippets-tab></speechos-snippets-tab>`;case"vocabulary":return zl`<speechos-vocabulary-tab></speechos-vocabulary-tab>`}}render(){return zl`
3073
+ `}};nl([fu()],sh.prototype,"vocabulary",void 0),nl([fu()],sh.prototype,"showForm",void 0),nl([fu()],sh.prototype,"term",void 0),nl([fu()],sh.prototype,"error",void 0),sh=nl([hu("speechos-vocabulary-tab")],sh);let oh=class extends lu{constructor(){super(...arguments),this.open=!1,this.activeTab="settings",this.mainTabs=[{id:"settings",label:"Settings",icon:Uu(18)},{id:"transcripts",label:"History",icon:Du(18)},{id:"vocabulary",label:"Vocab",icon:$u(18)},{id:"snippets",label:"Snippets",icon:Bu(18)},{id:"help",label:"Help",icon:Nu(18)}],this.bottomTabs=[{id:"about",label:"About",icon:Lu(18)}]}static{this.styles=[vu,Ku]}updated(e){e.has("open")&&(this.open?this.refreshActiveTab():this.resetTabs())}refreshActiveTab(){const e=this.getTabElement();e&&"refresh"in e&&e.refresh(),e&&"activate"in e&&e.activate()}resetTabs(){const e=this.shadowRoot?.querySelector("speechos-snippets-tab"),t=this.shadowRoot?.querySelector("speechos-vocabulary-tab"),i=this.shadowRoot?.querySelector("speechos-settings-tab");e&&"resetForm"in e&&e.resetForm(),t&&"resetForm"in t&&t.resetForm(),i&&"deactivate"in i&&i.deactivate()}getTabElement(){return this.shadowRoot?.querySelector({transcripts:"speechos-history-tab",help:"speechos-help-tab",about:"speechos-about-tab",settings:"speechos-settings-tab",snippets:"speechos-snippets-tab",vocabulary:"speechos-vocabulary-tab"}[this.activeTab])??null}handleOverlayClick(e){e.target===e.currentTarget&&this.close()}handleClose(){this.close()}close(){this.dispatchEvent(new CustomEvent("modal-close",{bubbles:!0,composed:!0}))}handleTabClick(e){const t=this.getTabElement();t&&"deactivate"in t&&t.deactivate(),this.activeTab=e,this.updateComplete.then(()=>{this.refreshActiveTab()})}renderTabContent(){switch(this.activeTab){case"transcripts":return Wl`<speechos-history-tab></speechos-history-tab>`;case"help":return Wl`<speechos-help-tab></speechos-help-tab>`;case"about":return Wl`<speechos-about-tab></speechos-about-tab>`;case"settings":return Wl`<speechos-settings-tab></speechos-settings-tab>`;case"snippets":return Wl`<speechos-snippets-tab></speechos-snippets-tab>`;case"vocabulary":return Wl`<speechos-vocabulary-tab></speechos-vocabulary-tab>`}}render(){return Wl`
3000
3074
  <div
3001
3075
  class="modal-overlay ${this.open?"open":""}"
3002
3076
  @click="${this.handleOverlayClick}"
@@ -3023,13 +3097,13 @@
3023
3097
  @click="${this.handleClose}"
3024
3098
  aria-label="Close"
3025
3099
  >
3026
- ${_u(16)}
3100
+ ${Mu(16)}
3027
3101
  </button>
3028
3102
  </div>
3029
3103
 
3030
3104
  <div class="modal-body">
3031
3105
  <nav class="sidebar">
3032
- ${this.mainTabs.map(e=>zl`
3106
+ ${this.mainTabs.map(e=>Wl`
3033
3107
  <button
3034
3108
  class="sidebar-item ${this.activeTab===e.id?"active":""}"
3035
3109
  @click="${()=>this.handleTabClick(e.id)}"
@@ -3039,7 +3113,7 @@
3039
3113
  </button>
3040
3114
  `)}
3041
3115
  <div class="sidebar-spacer"></div>
3042
- ${this.bottomTabs.map(e=>zl`
3116
+ ${this.bottomTabs.map(e=>Wl`
3043
3117
  <button
3044
3118
  class="sidebar-item ${this.activeTab===e.id?"active":""}"
3045
3119
  @click="${()=>this.handleTabClick(e.id)}"
@@ -3054,7 +3128,7 @@
3054
3128
  </div>
3055
3129
  </div>
3056
3130
  </div>
3057
- `}};il([mu({type:Boolean})],sh.prototype,"open",void 0),il([gu()],sh.prototype,"activeTab",void 0),sh=il([uu("speechos-settings-modal")],sh);const oh=cl`
3131
+ `}};nl([gu({type:Boolean})],oh.prototype,"open",void 0),nl([fu()],oh.prototype,"activeTab",void 0),oh=nl([hu("speechos-settings-modal")],oh);const rh=dl`
3058
3132
  :host {
3059
3133
  position: fixed;
3060
3134
  inset: 0;
@@ -3084,14 +3158,14 @@
3084
3158
  }
3085
3159
 
3086
3160
  .modal-card {
3087
- background: #1a1d24;
3161
+ background: #f5f5f4;
3088
3162
  border-radius: 16px;
3089
3163
  width: 90%;
3090
3164
  max-width: 400px;
3091
3165
  display: flex;
3092
3166
  flex-direction: column;
3093
- box-shadow: 0 24px 48px rgba(0, 0, 0, 0.4),
3094
- 0 0 0 1px rgba(255, 255, 255, 0.05);
3167
+ box-shadow: 0 24px 48px rgba(0, 0, 0, 0.15),
3168
+ 0 0 0 1px rgba(0, 0, 0, 0.05);
3095
3169
  transform: scale(0.95) translateY(10px);
3096
3170
  transition: transform 0.25s cubic-bezier(0.16, 1, 0.3, 1);
3097
3171
  pointer-events: auto;
@@ -3107,14 +3181,14 @@
3107
3181
  align-items: center;
3108
3182
  justify-content: space-between;
3109
3183
  padding: 16px 20px;
3110
- border-bottom: 1px solid rgba(255, 255, 255, 0.06);
3111
- background: rgba(0, 0, 0, 0.2);
3184
+ border-bottom: 1px solid #e5e5e5;
3185
+ background: #ffffff;
3112
3186
  }
3113
3187
 
3114
3188
  .modal-title {
3115
3189
  font-size: 16px;
3116
3190
  font-weight: 600;
3117
- color: white;
3191
+ color: #171717;
3118
3192
  margin: 0;
3119
3193
  letter-spacing: -0.01em;
3120
3194
  }
@@ -3129,13 +3203,22 @@
3129
3203
  display: flex;
3130
3204
  align-items: center;
3131
3205
  justify-content: center;
3132
- color: rgba(255, 255, 255, 0.5);
3206
+ color: #737373;
3133
3207
  transition: all 0.15s ease;
3134
3208
  }
3135
3209
 
3136
3210
  .close-button:hover {
3137
- background: rgba(255, 255, 255, 0.08);
3138
- color: white;
3211
+ background: #f5f5f4;
3212
+ color: #171717;
3213
+ }
3214
+
3215
+ .close-button:focus {
3216
+ outline: none;
3217
+ box-shadow: 0 0 0 2px #0d9488, 0 0 0 4px rgba(13, 148, 136, 0.2);
3218
+ }
3219
+
3220
+ .close-button:active {
3221
+ transform: scale(0.95);
3139
3222
  }
3140
3223
 
3141
3224
  .modal-body {
@@ -3147,8 +3230,8 @@
3147
3230
  justify-content: flex-end;
3148
3231
  gap: 10px;
3149
3232
  padding: 16px 20px;
3150
- border-top: 1px solid rgba(255, 255, 255, 0.06);
3151
- background: rgba(0, 0, 0, 0.1);
3233
+ border-top: 1px solid #e5e5e5;
3234
+ background: #ffffff;
3152
3235
  }
3153
3236
 
3154
3237
  .btn {
@@ -3165,42 +3248,47 @@
3165
3248
  }
3166
3249
 
3167
3250
  .btn-secondary {
3168
- background: rgba(255, 255, 255, 0.08);
3169
- color: rgba(255, 255, 255, 0.8);
3251
+ background: rgba(0, 0, 0, 0.08);
3252
+ color: #525252;
3170
3253
  }
3171
3254
 
3172
3255
  .btn-secondary:hover {
3173
- background: rgba(255, 255, 255, 0.12);
3174
- color: white;
3256
+ background: rgba(0, 0, 0, 0.12);
3257
+ color: #171717;
3175
3258
  }
3176
3259
 
3177
3260
  .btn-primary {
3178
- background: linear-gradient(135deg, #10b981 0%, #059669 100%);
3261
+ background: #0d9488;
3179
3262
  color: white;
3180
- box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2);
3263
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
3181
3264
  }
3182
3265
 
3183
3266
  .btn-primary:hover {
3184
- transform: translateY(-1px);
3185
- box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
3267
+ background: #0f766e;
3268
+ box-shadow: 0 4px 12px rgba(13, 148, 136, 0.25);
3269
+ }
3270
+
3271
+ .btn-primary:focus {
3272
+ outline: none;
3273
+ box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px #0d9488;
3186
3274
  }
3187
3275
 
3188
3276
  .btn-primary:active {
3189
- transform: translateY(0);
3277
+ transform: scale(0.98);
3190
3278
  }
3191
3279
 
3192
3280
  /* Success state for copy button */
3193
3281
  .btn-success {
3194
- background: linear-gradient(135deg, #34d399 0%, #10b981 100%);
3282
+ background: #059669;
3195
3283
  }
3196
3284
 
3197
3285
  /* Text display area */
3198
3286
  .text-display {
3199
- background: rgba(0, 0, 0, 0.3);
3200
- border: 1px solid rgba(255, 255, 255, 0.08);
3287
+ background: #ffffff;
3288
+ border: 1px solid #e5e5e5;
3201
3289
  border-radius: 10px;
3202
3290
  padding: 14px 16px;
3203
- color: white;
3291
+ color: #171717;
3204
3292
  font-size: 14px;
3205
3293
  line-height: 1.5;
3206
3294
  max-height: 200px;
@@ -3219,12 +3307,12 @@
3219
3307
  }
3220
3308
 
3221
3309
  .text-display::-webkit-scrollbar-thumb {
3222
- background: rgba(255, 255, 255, 0.15);
3310
+ background: rgba(0, 0, 0, 0.15);
3223
3311
  border-radius: 3px;
3224
3312
  }
3225
3313
 
3226
3314
  .text-display::-webkit-scrollbar-thumb:hover {
3227
- background: rgba(255, 255, 255, 0.25);
3315
+ background: rgba(0, 0, 0, 0.25);
3228
3316
  }
3229
3317
 
3230
3318
  /* Instruction list styling */
@@ -3239,7 +3327,7 @@
3239
3327
  align-items: flex-start;
3240
3328
  gap: 12px;
3241
3329
  padding: 12px 0;
3242
- border-bottom: 1px solid rgba(255, 255, 255, 0.06);
3330
+ border-bottom: 1px solid #e5e5e5;
3243
3331
  }
3244
3332
 
3245
3333
  .instruction-item:last-child {
@@ -3250,7 +3338,7 @@
3250
3338
  width: 24px;
3251
3339
  height: 24px;
3252
3340
  border-radius: 50%;
3253
- background: linear-gradient(135deg, #10b981 0%, #059669 100%);
3341
+ background: #0d9488;
3254
3342
  color: white;
3255
3343
  font-size: 12px;
3256
3344
  font-weight: 700;
@@ -3262,7 +3350,7 @@
3262
3350
 
3263
3351
  .instruction-text {
3264
3352
  font-size: 14px;
3265
- color: rgba(255, 255, 255, 0.85);
3353
+ color: #171717;
3266
3354
  line-height: 1.5;
3267
3355
  padding-top: 2px;
3268
3356
  }
@@ -3291,7 +3379,7 @@
3291
3379
  font-size: 15px;
3292
3380
  }
3293
3381
  }
3294
- `;let rh=class extends du{constructor(){super(...arguments),this.open=!1,this.text="",this.mode="dictation",this.copied=!1,this.copyTimeout=null}static{this.styles=[fu,oh,cl`
3382
+ `;let ah=class extends lu{constructor(){super(...arguments),this.open=!1,this.text="",this.mode="dictation",this.copied=!1,this.copyTimeout=null}static{this.styles=[vu,rh,dl`
3295
3383
  .header-content {
3296
3384
  display: flex;
3297
3385
  align-items: center;
@@ -3302,7 +3390,7 @@
3302
3390
  width: 32px;
3303
3391
  height: 32px;
3304
3392
  border-radius: 8px;
3305
- background: linear-gradient(135deg, #10b981 0%, #8b5cf6 100%);
3393
+ background: linear-gradient(135deg, #14b8a6 0%, #2563eb 100%);
3306
3394
  display: flex;
3307
3395
  align-items: center;
3308
3396
  justify-content: center;
@@ -3316,31 +3404,35 @@
3316
3404
  }
3317
3405
 
3318
3406
  .modal-title {
3319
- background: linear-gradient(135deg, #34d399 0%, #a78bfa 100%);
3407
+ background: linear-gradient(135deg, #14b8a6 0%, #2563eb 100%);
3320
3408
  -webkit-background-clip: text;
3321
3409
  -webkit-text-fill-color: transparent;
3322
3410
  background-clip: text;
3323
3411
  }
3324
3412
 
3325
3413
  .btn-primary {
3326
- background: linear-gradient(135deg, #10b981 0%, #059669 100%);
3327
- box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
3414
+ background: #0d9488;
3415
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
3328
3416
  border-radius: 999px;
3329
3417
  }
3330
3418
 
3331
3419
  .btn-primary:hover {
3332
- background: linear-gradient(135deg, #34d399 0%, #10b981 100%);
3333
- transform: translateY(-2px);
3334
- box-shadow: 0 6px 16px rgba(16, 185, 129, 0.4);
3420
+ background: #0f766e;
3421
+ box-shadow: 0 4px 12px rgba(13, 148, 136, 0.25);
3422
+ }
3423
+
3424
+ .btn-primary:focus {
3425
+ outline: none;
3426
+ box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px #0d9488;
3335
3427
  }
3336
3428
 
3337
3429
  .btn-primary:active {
3338
- transform: translateY(0);
3430
+ transform: scale(0.98);
3339
3431
  }
3340
3432
 
3341
3433
  .btn-success {
3342
- background: linear-gradient(135deg, #34d399 0%, #10b981 100%);
3343
- box-shadow: 0 4px 12px rgba(52, 211, 153, 0.3);
3434
+ background: #059669;
3435
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
3344
3436
  border-radius: 999px;
3345
3437
  }
3346
3438
 
@@ -3354,14 +3446,15 @@
3354
3446
  gap: 6px;
3355
3447
  margin-top: 12px;
3356
3448
  padding: 8px 12px;
3357
- background: rgba(16, 185, 129, 0.08);
3449
+ background: #ffffff;
3450
+ border: 1px solid #e5e5e5;
3358
3451
  border-radius: 8px;
3359
3452
  font-size: 12px;
3360
- color: rgba(255, 255, 255, 0.6);
3453
+ color: #525252;
3361
3454
  }
3362
3455
 
3363
3456
  .hint-icon {
3364
- color: #10b981;
3457
+ color: #0d9488;
3365
3458
  flex-shrink: 0;
3366
3459
  }
3367
3460
 
@@ -3399,7 +3492,7 @@
3399
3492
  background: linear-gradient(135deg, #a78bfa 0%, #8b5cf6 100%);
3400
3493
  box-shadow: 0 4px 12px rgba(167, 139, 250, 0.3);
3401
3494
  }
3402
- `]}disconnectedCallback(){super.disconnectedCallback(),this.copyTimeout&&(clearTimeout(this.copyTimeout),this.copyTimeout=null)}updated(e){e.has("open")&&(this.open||(this.copied=!1,this.copyTimeout&&(clearTimeout(this.copyTimeout),this.copyTimeout=null)))}handleOverlayClick(e){e.target===e.currentTarget&&this.close()}handleClose(){this.close()}close(){this.dispatchEvent(new CustomEvent("modal-close",{bubbles:!0,composed:!0}))}async handleCopy(){try{await navigator.clipboard.writeText(this.text),this.copied=!0,this.copyTimeout&&clearTimeout(this.copyTimeout),this.copyTimeout=window.setTimeout(()=>{this.copied=!1,this.copyTimeout=null},2e3)}catch(e){console.error("[SpeechOS] Failed to copy text:",e)}}get modalTitle(){return"edit"===this.mode?"Edit Complete":"Dictation Complete"}get modalIcon(){return"edit"===this.mode?Ou(18):Pu(18)}get hintText(){return"edit"===this.mode?"Tip: The editor didn't accept the edit. Copy and paste manually.":"Tip: Focus a text field first to auto-insert next time"}render(){return zl`
3495
+ `]}disconnectedCallback(){super.disconnectedCallback(),this.copyTimeout&&(clearTimeout(this.copyTimeout),this.copyTimeout=null)}updated(e){e.has("open")&&(this.open||(this.copied=!1,this.copyTimeout&&(clearTimeout(this.copyTimeout),this.copyTimeout=null)))}handleOverlayClick(e){e.target===e.currentTarget&&this.close()}handleClose(){this.close()}close(){this.dispatchEvent(new CustomEvent("modal-close",{bubbles:!0,composed:!0}))}async handleCopy(){try{await navigator.clipboard.writeText(this.text),this.copied=!0,this.copyTimeout&&clearTimeout(this.copyTimeout),this.copyTimeout=window.setTimeout(()=>{this.copied=!1,this.copyTimeout=null},2e3)}catch(e){console.error("[SpeechOS] Failed to copy text:",e)}}get modalTitle(){return"edit"===this.mode?"Edit Complete":"Dictation Complete"}get modalIcon(){return"edit"===this.mode?Au(18):Iu(18)}get hintText(){return"edit"===this.mode?"Tip: The editor didn't accept the edit. Copy and paste manually.":"Tip: Focus a text field first to auto-insert next time"}render(){return Wl`
3403
3496
  <div
3404
3497
  class="modal-overlay ${this.open?"open":""}"
3405
3498
  @click="${this.handleOverlayClick}"
@@ -3415,7 +3508,7 @@
3415
3508
  @click="${this.handleClose}"
3416
3509
  aria-label="Close"
3417
3510
  >
3418
- ${_u(16)}
3511
+ ${Mu(16)}
3419
3512
  </button>
3420
3513
  </div>
3421
3514
 
@@ -3434,7 +3527,7 @@
3434
3527
  class="btn ${this.copied?"btn-success":"btn-primary"}"
3435
3528
  @click="${this.handleCopy}"
3436
3529
  >
3437
- ${this.copied?((e=18)=>Ru('<path d="M20 6 9 17l-5-5"/>',e))(16):Uu(16)}
3530
+ ${this.copied?((e=18)=>Pu('<path d="M20 6 9 17l-5-5"/>',e))(16):Fu(16)}
3438
3531
  ${this.copied?"Copied!":"Copy"}
3439
3532
  </button>
3440
3533
  <button class="btn btn-secondary" @click="${this.handleClose}">
@@ -3443,7 +3536,7 @@
3443
3536
  </div>
3444
3537
  </div>
3445
3538
  </div>
3446
- `}};il([mu({type:Boolean})],rh.prototype,"open",void 0),il([mu({type:String})],rh.prototype,"text",void 0),il([mu({type:String,reflect:!0})],rh.prototype,"mode",void 0),il([gu()],rh.prototype,"copied",void 0),rh=il([uu("speechos-dictation-output-modal")],rh);let ah=class extends du{constructor(){super(...arguments),this.open=!1}static{this.styles=[fu,oh,cl`
3539
+ `}};nl([gu({type:Boolean})],ah.prototype,"open",void 0),nl([gu({type:String})],ah.prototype,"text",void 0),nl([gu({type:String,reflect:!0})],ah.prototype,"mode",void 0),nl([fu()],ah.prototype,"copied",void 0),ah=nl([hu("speechos-dictation-output-modal")],ah);let ch=class extends lu{constructor(){super(...arguments),this.open=!1}static{this.styles=[vu,rh,dl`
3447
3540
  .header-content {
3448
3541
  display: flex;
3449
3542
  align-items: center;
@@ -3493,7 +3586,7 @@
3493
3586
  .btn-primary:active {
3494
3587
  transform: translateY(0);
3495
3588
  }
3496
- `]}handleOverlayClick(e){e.target===e.currentTarget&&this.close()}handleClose(){this.close()}close(){this.dispatchEvent(new CustomEvent("modal-close",{bubbles:!0,composed:!0}))}render(){return zl`
3589
+ `]}handleOverlayClick(e){e.target===e.currentTarget&&this.close()}handleClose(){this.close()}close(){this.dispatchEvent(new CustomEvent("modal-close",{bubbles:!0,composed:!0}))}render(){return Wl`
3497
3590
  <div
3498
3591
  class="modal-overlay ${this.open?"open":""}"
3499
3592
  @click="${this.handleOverlayClick}"
@@ -3501,7 +3594,7 @@
3501
3594
  <div class="modal-card">
3502
3595
  <div class="modal-header">
3503
3596
  <div class="header-content">
3504
- <div class="logo-icon">${Ou(18)}</div>
3597
+ <div class="logo-icon">${Au(18)}</div>
3505
3598
  <h2 class="modal-title">How to Use Edit</h2>
3506
3599
  </div>
3507
3600
  <button
@@ -3509,7 +3602,7 @@
3509
3602
  @click="${this.handleClose}"
3510
3603
  aria-label="Close"
3511
3604
  >
3512
- ${_u(16)}
3605
+ ${Mu(16)}
3513
3606
  </button>
3514
3607
  </div>
3515
3608
 
@@ -3545,7 +3638,7 @@
3545
3638
  </div>
3546
3639
  </div>
3547
3640
  </div>
3548
- `}};var ch;il([mu({type:Boolean})],ah.prototype,"open",void 0),ah=il([uu("speechos-edit-help-modal")],ah);let dh=class extends du{constructor(){super(...arguments),this.widgetState=vc.getState(),this.settingsOpen=!1,this.settingsOpenFromWarning=!1,this.dictationModalOpen=!1,this.dictationModalText="",this.dictationModalMode="dictation",this.editHelpModalOpen=!1,this.actionFeedback=null,this.showNoAudioWarning=!1,this.isErrorRetryable=!0,this.dictationTargetElement=null,this.editTargetElement=null,this.dictationCursorStart=null,this.dictationCursorEnd=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText="",this.boundClickOutsideHandler=null,this.modalElement=null,this.dictationModalElement=null,this.editHelpModalElement=null,this.actionFeedbackTimeout=null,this.customPosition=null,this.isDragging=!1,this.dragStartPos=null,this.dragOffset={x:0,y:0},this.boundDragMove=null,this.boundDragEnd=null,this.suppressNextClick=!1,this.boundViewportResizeHandler=null,this.boundScrollHandler=null,this.consecutiveNoAudioActions=0,this.transcriptionReceived=!1,this.noAudioWarningTimeout=null,this.transcriptionInterimUnsubscribe=null}static{ch=this}static{this.styles=[fu,vu,cl`
3641
+ `}};var dh;nl([gu({type:Boolean})],ch.prototype,"open",void 0),ch=nl([hu("speechos-edit-help-modal")],ch);let lh=class extends lu{constructor(){super(...arguments),this.widgetState=vc.getState(),this.settingsOpen=!1,this.settingsOpenFromWarning=!1,this.dictationModalOpen=!1,this.dictationModalText="",this.dictationModalMode="dictation",this.editHelpModalOpen=!1,this.actionFeedback=null,this.showNoAudioWarning=!1,this.isErrorRetryable=!0,this.dictationTargetElement=null,this.editTargetElement=null,this.dictationCursorStart=null,this.dictationCursorEnd=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText="",this.boundClickOutsideHandler=null,this.modalElement=null,this.dictationModalElement=null,this.editHelpModalElement=null,this.actionFeedbackTimeout=null,this.customPosition=null,this.isDragging=!1,this.dragStartPos=null,this.dragOffset={x:0,y:0},this.boundDragMove=null,this.boundDragEnd=null,this.suppressNextClick=!1,this.boundViewportResizeHandler=null,this.boundScrollHandler=null,this.consecutiveNoAudioActions=0,this.transcriptionReceived=!1,this.noAudioWarningTimeout=null,this.transcriptionInterimUnsubscribe=null}static{dh=this}static{this.styles=[vu,bu,dl`
3549
3642
  :host {
3550
3643
  position: fixed;
3551
3644
  bottom: var(--speechos-spacing-md); /* 12px - same as spacing above */
@@ -3613,7 +3706,7 @@
3613
3706
  left: -56px;
3614
3707
  }
3615
3708
  }
3616
- `]}static{this.DRAG_THRESHOLD=5}static{this.KEYBOARD_HEIGHT_THRESHOLD=150}connectedCallback(){super.connectedCallback(),this.modalElement=document.createElement("speechos-settings-modal"),this.modalElement.addEventListener("modal-close",()=>{this.settingsOpen=!1,this.settingsOpenFromWarning=!1}),document.body.appendChild(this.modalElement),this.dictationModalElement=document.createElement("speechos-dictation-output-modal"),this.dictationModalElement.addEventListener("modal-close",()=>{this.dictationModalOpen=!1}),document.body.appendChild(this.dictationModalElement),this.editHelpModalElement=document.createElement("speechos-edit-help-modal"),this.editHelpModalElement.addEventListener("modal-close",()=>{this.editHelpModalOpen=!1}),document.body.appendChild(this.editHelpModalElement),this.stateUnsubscribe=vc.subscribe(e=>{e.isVisible?e.isExpanded||this.settingsOpenFromWarning||(uc().debug&&this.settingsOpen&&console.log("[SpeechOS] Closing settings modal: widget collapsed"),this.settingsOpen=!1):(uc().debug&&this.settingsOpen&&console.log("[SpeechOS] Closing settings modal: widget hidden"),this.settingsOpen=!1,this.settingsOpenFromWarning=!1),e.focusedElement!==this.widgetState.focusedElement&&(this.customPosition=null,this.classList.remove("custom-position")),this.widgetState=e,this.updatePosition()}),this.errorEventUnsubscribe=gc.on("error",e=>{"idle"!==this.widgetState.recordingState&&"error"!==this.widgetState.recordingState&&(this.isErrorRetryable="connection_blocked"!==e.code,vc.setError(e.message),Pc().disconnect().catch(()=>{}))}),this.updatePosition(),this.boundClickOutsideHandler=this.handleClickOutside.bind(this),document.addEventListener("click",this.boundClickOutsideHandler,!0),window.visualViewport&&(this.boundViewportResizeHandler=this.handleViewportResize.bind(this),window.visualViewport.addEventListener("resize",this.boundViewportResizeHandler)),this.boundScrollHandler=this.handleScroll.bind(this),window.addEventListener("scroll",this.boundScrollHandler,{passive:!0})}disconnectedCallback(){super.disconnectedCallback(),this.modalElement&&(this.modalElement.remove(),this.modalElement=null),this.dictationModalElement&&(this.dictationModalElement.remove(),this.dictationModalElement=null),this.editHelpModalElement&&(this.editHelpModalElement.remove(),this.editHelpModalElement=null),this.actionFeedbackTimeout&&(clearTimeout(this.actionFeedbackTimeout),this.actionFeedbackTimeout=null),this.stateUnsubscribe&&this.stateUnsubscribe(),this.errorEventUnsubscribe&&this.errorEventUnsubscribe(),this.boundClickOutsideHandler&&(document.removeEventListener("click",this.boundClickOutsideHandler,!0),this.boundClickOutsideHandler=null),this.boundDragMove&&(document.removeEventListener("mousemove",this.boundDragMove),this.boundDragMove=null),this.boundDragEnd&&(document.removeEventListener("mouseup",this.boundDragEnd),this.boundDragEnd=null),this.boundViewportResizeHandler&&window.visualViewport&&(window.visualViewport.removeEventListener("resize",this.boundViewportResizeHandler),this.boundViewportResizeHandler=null),this.boundScrollHandler&&(window.removeEventListener("scroll",this.boundScrollHandler),this.boundScrollHandler=null),this.cleanupNoAudioWarningTracking()}updated(e){e.has("settingsOpen")&&this.modalElement&&(this.modalElement.open=this.settingsOpen),e.has("dictationModalOpen")&&this.dictationModalElement&&(this.dictationModalElement.open=this.dictationModalOpen),e.has("dictationModalText")&&this.dictationModalElement&&(this.dictationModalElement.text=this.dictationModalText),e.has("dictationModalMode")&&this.dictationModalElement&&(this.dictationModalElement.mode=this.dictationModalMode),e.has("editHelpModalOpen")&&this.editHelpModalElement&&(this.editHelpModalElement.open=this.editHelpModalOpen)}handleClickOutside(e){const t=e.target,i=t instanceof Element&&t.closest("[data-speechos-no-close]");if(console.log("[SpeechOS] handleClickOutside called",{isExpanded:this.widgetState.isExpanded,recordingState:this.widgetState.recordingState,target:e.target,hasNoCloseAttr:!!i}),i)return void console.log("[SpeechOS] Skipping due to data-speechos-no-close");if(!this.widgetState.isExpanded||"idle"!==this.widgetState.recordingState)return void console.log("[SpeechOS] Early return - not expanded or not idle");const n=e.composedPath?e.composedPath():[],s=this.contains(t)||n.includes(this),o=this.modalElement&&(this.modalElement.contains(t)||n.includes(this.modalElement));this.settingsOpen&&o||(!this.settingsOpen||o?s||!this.isFormField(t)?s||Dc()||vc.hide():vc.setFocusedElement(t):this.settingsOpen=!1)}isFormField(e){if(!(e&&e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();if("input"===t||"textarea"===t){if("input"===t){const t=e.type.toLowerCase();if(["checkbox","radio","submit","button","reset","file","hidden"].includes(t))return!1}return!0}return!(!e.isContentEditable&&"true"!==e.getAttribute("contenteditable"))}isMobileDevice(){const e="ontouchstart"in window||navigator.maxTouchPoints>0,t=window.innerWidth<=768;return e&&t}updatePosition(){const e=_c();if(this.style.zIndex=String(e.zIndex),this.customPosition)return;const t=this.widgetState.focusedElement;t&&this.isMobileDevice()?this.positionBelowElement(t):(this.classList.remove("anchored-to-element"),this.style.top="",this.style.left="",this.style.bottom="12px")}positionBelowElement(e){const t=e.getBoundingClientRect(),i=t.bottom+8+window.scrollY,n=t.left+t.width/2+window.scrollX;this.classList.add("anchored-to-element"),this.removeAttribute("position"),this.style.top=`${i}px`,this.style.left=`${n}px`,this.style.bottom=""}handleViewportResize(){if(!window.visualViewport)return;if(this.customPosition)return;if(this.widgetState.focusedElement&&this.isMobileDevice())return void this.updatePosition();const e=window.innerHeight-window.visualViewport.height;e>ch.KEYBOARD_HEIGHT_THRESHOLD?this.style.bottom=`${e+12}px`:this.style.bottom="12px"}handleScroll(){!this.customPosition&&this.widgetState.focusedElement&&this.isMobileDevice()&&this.positionBelowElement(this.widgetState.focusedElement)}handleMicClick(){if(this.suppressNextClick)this.suppressNextClick=!1;else if("idle"===this.widgetState.recordingState){if(this.clearActionFeedback(),!this.widgetState.isExpanded){const e=Pc();e.prefetchToken?.()?.catch(e=>{uc().debug&&console.warn("[SpeechOS] Token prefetch failed:",e)})}vc.toggleExpanded()}}async handleStopRecording(){if(this.cleanupNoAudioWarningTracking(),"edit"===this.widgetState.activeAction)await this.handleStopEdit();else if("command"===this.widgetState.activeAction)await this.handleStopCommand();else{vc.stopRecording();const e=Pc();try{const t=await this.withMinDisplayTime(e.stopVoiceSession(),300);this.trackActionResult(!!t),t&&(uc().debug&&console.log("[SpeechOS] Transcription received:",{transcription:t,dictationTargetElement:this.dictationTargetElement,tagName:this.dictationTargetElement?.tagName}),this.dictationTargetElement?this.insertTranscription(t):(uc().debug&&console.log("[SpeechOS] No target element, showing dictation modal"),this.dictationModalText=t,this.dictationModalMode="dictation",this.dictationModalOpen=!0),el.saveTranscript(t,"dictate")),vc.completeRecording(),gc.emit("action:select",{action:"dictate"}),e.disconnect().catch(()=>{}),e.startAutoRefresh?.()}catch(t){this.trackActionResult(!1);const i=t instanceof Error?t.message:"Failed to transcribe audio";"Disconnected"!==i&&(vc.setError(i),e.disconnect().catch(()=>{}))}}}async handleCancelOperation(){this.cleanupNoAudioWarningTracking(),await Pc().disconnect(),"error"===this.widgetState.recordingState?vc.clearError():vc.cancelRecording(),this.dictationTargetElement=null,this.editTargetElement=null,this.dictationCursorStart=null,this.dictationCursorEnd=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText=""}async handleRetryConnection(){const e=this.widgetState.activeAction;vc.clearError(),"edit"===e?await this.startEdit():"command"===e?await this.startCommand():await this.startDictation()}handleCloseWidget(){this.clearActionFeedback(),vc.hide()}handleSettingsClick(){this.settingsOpen=!0}handleDragStart(e){if(0!==e.button)return;if(e.composedPath().some(e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();if("speechos-action-bubbles"===t||"speechos-settings-button"===t)return!0;if("button"===t){if(!(e.className||"").includes("mic-button"))return!0}return!1}))return;this.dragStartPos={x:e.clientX,y:e.clientY},this.isDragging=!1;const t=this.getBoundingClientRect();this.dragOffset={x:e.clientX-t.left-t.width/2,y:t.bottom-e.clientY},this.boundDragMove=this.handleDragMove.bind(this),this.boundDragEnd=this.handleDragEnd.bind(this),document.addEventListener("mousemove",this.boundDragMove),document.addEventListener("mouseup",this.boundDragEnd)}handleDragMove(e){if(!this.isDragging&&this.dragStartPos){const t=e.clientX-this.dragStartPos.x,i=e.clientY-this.dragStartPos.y;if(!(Math.sqrt(t*t+i*i)>=ch.DRAG_THRESHOLD))return;this.isDragging=!0,e.preventDefault()}this.isDragging&&(e.preventDefault(),this.customPosition={x:e.clientX-this.dragOffset.x,y:window.innerHeight-e.clientY-this.dragOffset.y},this.applyCustomPosition())}handleDragEnd(){this.isDragging&&(this.suppressNextClick=!0),this.isDragging=!1,this.dragStartPos=null,this.boundDragMove&&(document.removeEventListener("mousemove",this.boundDragMove),this.boundDragMove=null),this.boundDragEnd&&(document.removeEventListener("mouseup",this.boundDragEnd),this.boundDragEnd=null)}applyCustomPosition(){this.customPosition&&(this.classList.add("custom-position"),this.style.left=`${this.customPosition.x}px`,this.style.bottom=`${this.customPosition.y}px`)}insertTranscription(e){const t=this.dictationTargetElement;if(!t)return;const i=t.tagName.toLowerCase(),n=this.getElementContent(t)||"";if("input"===i||"textarea"===i){const i=t;i.focus();const n=this.dictationCursorStart??i.value.length,s=this.dictationCursorEnd??i.value.length;i.setSelectionRange(n,s),Su(i,e),vc.setFocusedElement(i)}else t.isContentEditable&&(t.focus(),vc.setFocusedElement(t),Su(t,e));gc.emit("transcription:inserted",{text:e,element:t}),this.verifyInsertionApplied(t,e,n),this.dictationTargetElement=null,this.dictationCursorStart=null,this.dictationCursorEnd=null}verifyInsertionApplied(e,t,i){requestAnimationFrame(()=>{const n=e.tagName.toLowerCase();let s="";"input"===n||"textarea"===n?s=e.value:e.isContentEditable&&(s=e.textContent||"");s.includes(t)||""===i&&""!==s||(uc().debug&&console.log("[SpeechOS] Dictation failed to insert, showing fallback modal",{insertedText:t,currentContent:s,originalContent:i}),this.dictationModalText=t,this.dictationModalMode="dictation",this.dictationModalOpen=!0)})}handleActionSelect(e){const{action:t}=e.detail;if(this.clearActionFeedback(),vc.setActiveAction(t),"dictate"===t)this.startDictation();else if("edit"===t){if(!this.widgetState.focusedElement)return this.editHelpModalOpen=!0,void vc.setActiveAction(null);this.startEdit()}else"command"===t?this.startCommand():setTimeout(()=>{vc.setState({isExpanded:!1,activeAction:null})},300)}async withMinDisplayTime(e,t){const[i]=await Promise.all([e,new Promise(e=>setTimeout(e,t))]);return i}async startDictation(){if(this.dictationTargetElement=this.widgetState.focusedElement,this.dictationCursorStart=null,this.dictationCursorEnd=null,uc().debug&&console.log("[SpeechOS] startDictation:",{focusedElement:this.widgetState.focusedElement,dictationTargetElement:this.dictationTargetElement,tagName:this.dictationTargetElement?.tagName}),this.dictationTargetElement){const e=this.dictationTargetElement.tagName.toLowerCase();if("input"===e||"textarea"===e){const e=this.dictationTargetElement;this.supportsSelection(e)?(this.dictationCursorStart=e.selectionStart,this.dictationCursorEnd=e.selectionEnd):(this.dictationCursorStart=e.value.length,this.dictationCursorEnd=e.value.length)}}vc.startRecording();const e=Date.now(),t=Pc();try{await t.startVoiceSession({action:"dictate",settings:uh(),onMicReady:()=>{const t=200-(Date.now()-e),i=()=>{"error"!==vc.getState().recordingState&&(vc.setRecordingState("recording"),this.startNoAudioWarningTracking())};t>0?setTimeout(i,t):i()}})}catch(e){const i=e instanceof Error?e.message:"Connection failed";"Disconnected"!==i&&("error"!==this.widgetState.recordingState&&vc.setError(`Failed to connect: ${i}`),await t.disconnect())}}async startEdit(){if(this.editTargetElement=this.widgetState.focusedElement,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText="",uc().debug&&console.log("[SpeechOS] startEdit:",{focusedElement:this.widgetState.focusedElement,editTargetElement:this.editTargetElement,tagName:this.editTargetElement?.tagName}),this.editTargetElement){const e=this.editTargetElement.tagName.toLowerCase();if("input"===e||"textarea"===e){const e=this.editTargetElement;if(this.supportsSelection(e)){this.editSelectionStart=e.selectionStart,this.editSelectionEnd=e.selectionEnd;(this.editSelectionStart??0)!==(this.editSelectionEnd??0)&&(this.editSelectedText=Tu(e))}else this.editSelectionStart=0,this.editSelectionEnd=0}else if(this.editTargetElement.isContentEditable){const e=Tu(this.editTargetElement);this.editSelectionStart=0,this.editSelectionEnd=e.length,this.editSelectedText=e}}const e=this.getElementContent(this.editTargetElement);vc.startRecording();const t=Date.now(),i=Pc();try{await i.startVoiceSession({action:"edit",inputText:e,settings:uh(),onMicReady:()=>{const e=200-(Date.now()-t),i=()=>{"error"!==vc.getState().recordingState&&(vc.setRecordingState("recording"),this.startNoAudioWarningTracking())};e>0?setTimeout(i,e):i()}})}catch(e){const t=e instanceof Error?e.message:"Connection failed";"Disconnected"!==t&&("error"!==this.widgetState.recordingState&&vc.setError(`Failed to connect: ${t}`),await i.disconnect())}}async handleStopEdit(){vc.stopRecording();const e=this.getElementContent(this.editTargetElement),t=Pc();try{const i=await this.withMinDisplayTime(t.requestEditText(e),300);if(i.trim()===e.trim())return this.trackActionResult(!1),this.showActionFeedback("edit-empty"),vc.completeRecording(),this.editTargetElement=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText="",t.disconnect().catch(()=>{}),void t.startAutoRefresh?.();this.trackActionResult(!0),this.applyEdit(i),t.disconnect().catch(()=>{}),t.startAutoRefresh?.()}catch(e){this.trackActionResult(!1);const i=e instanceof Error?e.message:"Failed to apply edit";"Disconnected"!==i&&(vc.setError(i),t.disconnect().catch(()=>{}))}}async startCommand(){vc.startRecording();const e=Date.now(),t=Pc(),i=_c().commands;try{await t.startVoiceSession({action:"command",commands:i,settings:uh(),onMicReady:()=>{const t=200-(Date.now()-e),i=()=>{"error"!==vc.getState().recordingState&&(vc.setRecordingState("recording"),this.startNoAudioWarningTracking())};t>0?setTimeout(i,t):i()}})}catch(e){const i=e instanceof Error?e.message:"Connection failed";"Disconnected"!==i&&("error"!==this.widgetState.recordingState&&vc.setError(`Failed to connect: ${i}`),await t.disconnect())}}async handleStopCommand(){vc.stopRecording();const e=_c().commands,t=Pc();try{const i=await this.withMinDisplayTime(t.requestCommand(e),300);this.trackActionResult(null!==i);const n=t.getLastInputText?.(),s=i?`${i.name}${Object.keys(i.arguments).length>0?`: ${JSON.stringify(i.arguments)}`:""}`:"No command matched";el.saveTranscript(s,"command",{inputText:n,commandResult:i,commandConfig:e}),vc.completeRecording(),this.showActionFeedback(i?"command-success":"command-none"),t.disconnect().catch(()=>{}),t.startAutoRefresh?.()}catch(e){this.trackActionResult(!1);const i=e instanceof Error?e.message:"Failed to process command";"Disconnected"!==i&&(vc.setError(i),t.disconnect().catch(()=>{}))}}showActionFeedback(e){this.actionFeedback=e,this.actionFeedbackTimeout&&clearTimeout(this.actionFeedbackTimeout),this.actionFeedbackTimeout=window.setTimeout(()=>{this.actionFeedback=null,this.actionFeedbackTimeout=null},4e3)}clearActionFeedback(){this.actionFeedbackTimeout&&(clearTimeout(this.actionFeedbackTimeout),this.actionFeedbackTimeout=null),this.actionFeedback=null}startNoAudioWarningTracking(){this.transcriptionReceived=!1,this.showNoAudioWarning=!1,this.consecutiveNoAudioActions>=2&&(this.showNoAudioWarning=!0),this.noAudioWarningTimeout=window.setTimeout(()=>{this.transcriptionReceived||"recording"!==this.widgetState.recordingState||(this.showNoAudioWarning=!0)},5e3),this.transcriptionInterimUnsubscribe=gc.on("transcription:interim",()=>{this.transcriptionReceived=!0,this.showNoAudioWarning&&(this.showNoAudioWarning=!1)})}cleanupNoAudioWarningTracking(){null!==this.noAudioWarningTimeout&&(clearTimeout(this.noAudioWarningTimeout),this.noAudioWarningTimeout=null),this.transcriptionInterimUnsubscribe&&(this.transcriptionInterimUnsubscribe(),this.transcriptionInterimUnsubscribe=null),this.showNoAudioWarning=!1}trackActionResult(e){e?this.consecutiveNoAudioActions=0:this.consecutiveNoAudioActions++}async handleOpenSettingsFromWarning(){uc().debug&&console.log("[SpeechOS] No-audio settings link clicked"),this.cleanupNoAudioWarningTracking(),this.settingsOpenFromWarning=!0;const e=Pc().disconnect().catch(e=>{uc().debug&&console.log("[SpeechOS] Disconnect failed while opening settings",e)});vc.cancelRecording(),this.dictationTargetElement=null,this.editTargetElement=null,this.dictationCursorStart=null,this.dictationCursorEnd=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText="",this.settingsOpen=!0,uc().debug&&console.log("[SpeechOS] Settings modal opened from no-audio warning"),await e}supportsSelection(e){if("textarea"===e.tagName.toLowerCase())return!0;return["text","search","url","tel","password"].includes(e.type||"text")}getElementContent(e){if(!e)return"";const t=e.tagName.toLowerCase();if("input"===t||"textarea"===t){const t=e;return Tu(t)||t.value}if(e.isContentEditable){return Tu(e)||e.textContent||""}return""}applyEdit(e){const t=this.editTargetElement;if(!t)return void vc.completeRecording();const i=t.tagName.toLowerCase();let n="";if("input"===i||"textarea"===i){const i=t;n=i.value,i.focus();const s=this.editSelectionStart??0,o=this.editSelectionEnd??i.value.length;s!==o?(i.setSelectionRange(s,o),Su(i,e)):function(e,t){if(bu(e))e.select(),Su(e,t);else{const i=e.ownerDocument;yu(e,()=>{i.execCommand("selectAll",!1,t),ku(i,t)})}}(i,e),vc.setFocusedElement(i)}else if(t.isContentEditable){n=t.textContent||"";if(null!==this.editSelectionStart&&null!==this.editSelectionEnd&&this.editSelectionStart!==this.editSelectionEnd)t.focus(),Su(t,e);else{t.focus();const i=window.getSelection();if(i){const e=document.createRange();e.selectNodeContents(t),i.removeAllRanges(),i.addRange(e)}Su(t,e)}vc.setFocusedElement(t)}el.saveTranscript(e,"edit",n),gc.emit("edit:applied",{originalContent:n,editedContent:e,element:t}),vc.completeRecording(),this.verifyEditApplied(t,e,n),this.editTargetElement=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText=""}verifyEditApplied(e,t,i){requestAnimationFrame(()=>{const n=e.tagName.toLowerCase();let s="";"input"===n||"textarea"===n?s=e.value:e.isContentEditable&&(s=e.textContent||"");const o=s.trim(),r=t.trim();o!==i.trim()||o===r||o.includes(r)||(uc().debug&&console.log("[SpeechOS] Edit failed to apply, showing fallback modal",{expected:t,actual:s,original:i}),this.dictationModalText=t,this.dictationModalMode="edit",this.dictationModalOpen=!0)})}render(){if(!this.widgetState.isVisible)return this.setAttribute("hidden",""),zl``;this.removeAttribute("hidden");const e=this.widgetState.isExpanded&&"idle"===this.widgetState.recordingState,t="idle"===this.widgetState.recordingState;return zl`
3709
+ `]}static{this.DRAG_THRESHOLD=5}static{this.KEYBOARD_HEIGHT_THRESHOLD=150}connectedCallback(){super.connectedCallback(),this.modalElement=document.createElement("speechos-settings-modal"),this.modalElement.addEventListener("modal-close",()=>{this.settingsOpen=!1,this.settingsOpenFromWarning=!1}),document.body.appendChild(this.modalElement),this.dictationModalElement=document.createElement("speechos-dictation-output-modal"),this.dictationModalElement.addEventListener("modal-close",()=>{this.dictationModalOpen=!1}),document.body.appendChild(this.dictationModalElement),this.editHelpModalElement=document.createElement("speechos-edit-help-modal"),this.editHelpModalElement.addEventListener("modal-close",()=>{this.editHelpModalOpen=!1}),document.body.appendChild(this.editHelpModalElement),this.stateUnsubscribe=vc.subscribe(e=>{e.isVisible?e.isExpanded||this.settingsOpenFromWarning||(uc().debug&&this.settingsOpen&&console.log("[SpeechOS] Closing settings modal: widget collapsed"),this.settingsOpen=!1):(uc().debug&&this.settingsOpen&&console.log("[SpeechOS] Closing settings modal: widget hidden"),this.settingsOpen=!1,this.settingsOpenFromWarning=!1),e.focusedElement!==this.widgetState.focusedElement&&(this.customPosition=null,this.classList.remove("custom-position")),this.widgetState=e,this.updatePosition()}),this.errorEventUnsubscribe=gc.on("error",e=>{"idle"!==this.widgetState.recordingState&&"error"!==this.widgetState.recordingState&&(this.isErrorRetryable="connection_blocked"!==e.code,vc.setError(e.message),Pc().disconnect().catch(()=>{}))}),this.updatePosition(),this.boundClickOutsideHandler=this.handleClickOutside.bind(this),document.addEventListener("click",this.boundClickOutsideHandler,!0),window.visualViewport&&(this.boundViewportResizeHandler=this.handleViewportResize.bind(this),window.visualViewport.addEventListener("resize",this.boundViewportResizeHandler)),this.boundScrollHandler=this.handleScroll.bind(this),window.addEventListener("scroll",this.boundScrollHandler,{passive:!0})}disconnectedCallback(){super.disconnectedCallback(),this.modalElement&&(this.modalElement.remove(),this.modalElement=null),this.dictationModalElement&&(this.dictationModalElement.remove(),this.dictationModalElement=null),this.editHelpModalElement&&(this.editHelpModalElement.remove(),this.editHelpModalElement=null),this.actionFeedbackTimeout&&(clearTimeout(this.actionFeedbackTimeout),this.actionFeedbackTimeout=null),this.stateUnsubscribe&&this.stateUnsubscribe(),this.errorEventUnsubscribe&&this.errorEventUnsubscribe(),this.boundClickOutsideHandler&&(document.removeEventListener("click",this.boundClickOutsideHandler,!0),this.boundClickOutsideHandler=null),this.boundDragMove&&(document.removeEventListener("mousemove",this.boundDragMove),this.boundDragMove=null),this.boundDragEnd&&(document.removeEventListener("mouseup",this.boundDragEnd),this.boundDragEnd=null),this.boundViewportResizeHandler&&window.visualViewport&&(window.visualViewport.removeEventListener("resize",this.boundViewportResizeHandler),this.boundViewportResizeHandler=null),this.boundScrollHandler&&(window.removeEventListener("scroll",this.boundScrollHandler),this.boundScrollHandler=null),this.cleanupNoAudioWarningTracking()}updated(e){e.has("settingsOpen")&&this.modalElement&&(this.modalElement.open=this.settingsOpen),e.has("dictationModalOpen")&&this.dictationModalElement&&(this.dictationModalElement.open=this.dictationModalOpen),e.has("dictationModalText")&&this.dictationModalElement&&(this.dictationModalElement.text=this.dictationModalText),e.has("dictationModalMode")&&this.dictationModalElement&&(this.dictationModalElement.mode=this.dictationModalMode),e.has("editHelpModalOpen")&&this.editHelpModalElement&&(this.editHelpModalElement.open=this.editHelpModalOpen)}handleClickOutside(e){const t=e.target,i=t instanceof Element&&t.closest("[data-speechos-no-close]");if(console.log("[SpeechOS] handleClickOutside called",{isExpanded:this.widgetState.isExpanded,recordingState:this.widgetState.recordingState,target:e.target,hasNoCloseAttr:!!i}),i)return void console.log("[SpeechOS] Skipping due to data-speechos-no-close");if(!this.widgetState.isExpanded||"idle"!==this.widgetState.recordingState)return void console.log("[SpeechOS] Early return - not expanded or not idle");const n=e.composedPath?e.composedPath():[],s=this.contains(t)||n.includes(this),o=this.modalElement&&(this.modalElement.contains(t)||n.includes(this.modalElement));this.settingsOpen&&o||(!this.settingsOpen||o?s||!this.isFormField(t)?s||Dc()||vc.hide():vc.setFocusedElement(t):this.settingsOpen=!1)}isFormField(e){if(!(e&&e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();if("input"===t||"textarea"===t){if("input"===t){const t=e.type.toLowerCase();if(["checkbox","radio","submit","button","reset","file","hidden"].includes(t))return!1}return!0}return!(!e.isContentEditable&&"true"!==e.getAttribute("contenteditable"))}isMobileDevice(){const e="ontouchstart"in window||navigator.maxTouchPoints>0,t=window.innerWidth<=768;return e&&t}updatePosition(){const e=_c();if(this.style.zIndex=String(e.zIndex),this.customPosition)return;const t=this.widgetState.focusedElement;t&&this.isMobileDevice()?this.positionBelowElement(t):(this.classList.remove("anchored-to-element"),this.style.top="",this.style.left="",this.style.bottom="12px")}positionBelowElement(e){const t=e.getBoundingClientRect(),i=t.bottom+8+window.scrollY,n=t.left+t.width/2+window.scrollX;this.classList.add("anchored-to-element"),this.removeAttribute("position"),this.style.top=`${i}px`,this.style.left=`${n}px`,this.style.bottom=""}handleViewportResize(){if(!window.visualViewport)return;if(this.customPosition)return;if(this.widgetState.focusedElement&&this.isMobileDevice())return void this.updatePosition();const e=window.innerHeight-window.visualViewport.height;e>dh.KEYBOARD_HEIGHT_THRESHOLD?this.style.bottom=`${e+12}px`:this.style.bottom="12px"}handleScroll(){!this.customPosition&&this.widgetState.focusedElement&&this.isMobileDevice()&&this.positionBelowElement(this.widgetState.focusedElement)}handleMicClick(){if(this.suppressNextClick)this.suppressNextClick=!1;else if("idle"===this.widgetState.recordingState){if(this.clearActionFeedback(),!this.widgetState.isExpanded){const e=Pc();e.prefetchToken?.()?.catch(e=>{uc().debug&&console.warn("[SpeechOS] Token prefetch failed:",e)})}vc.toggleExpanded()}}async handleStopRecording(){if(this.cleanupNoAudioWarningTracking(),"edit"===this.widgetState.activeAction)await this.handleStopEdit();else if("command"===this.widgetState.activeAction)await this.handleStopCommand();else{vc.stopRecording();const e=Pc();try{const t=await this.withMinDisplayTime(e.stopVoiceSession(),300);this.trackActionResult(!!t),t&&(uc().debug&&console.log("[SpeechOS] Transcription received:",{transcription:t,dictationTargetElement:this.dictationTargetElement,tagName:this.dictationTargetElement?.tagName}),this.dictationTargetElement?this.insertTranscription(t):(uc().debug&&console.log("[SpeechOS] No target element, showing dictation modal"),this.dictationModalText=t,this.dictationModalMode="dictation",this.dictationModalOpen=!0),tl.saveTranscript(t,"dictate")),vc.completeRecording(),gc.emit("action:select",{action:"dictate"}),e.disconnect().catch(()=>{}),e.startAutoRefresh?.()}catch(t){this.trackActionResult(!1);const i=t instanceof Error?t.message:"Failed to transcribe audio";"Disconnected"!==i&&(vc.setError(i),e.disconnect().catch(()=>{}))}}}async handleCancelOperation(){this.cleanupNoAudioWarningTracking(),await Pc().disconnect(),"error"===this.widgetState.recordingState?vc.clearError():vc.cancelRecording(),this.dictationTargetElement=null,this.editTargetElement=null,this.dictationCursorStart=null,this.dictationCursorEnd=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText=""}async handleRetryConnection(){const e=this.widgetState.activeAction;vc.clearError(),"edit"===e?await this.startEdit():"command"===e?await this.startCommand():await this.startDictation()}handleCloseWidget(){this.clearActionFeedback(),vc.hide()}handleSettingsClick(){if(Nc()){const e=`${uc().host}/a/extension-settings`;window.open(e,"_blank","noopener,noreferrer")}else this.settingsOpen=!0}handleDragStart(e){if(0!==e.button)return;if(e.composedPath().some(e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();if("speechos-action-bubbles"===t||"speechos-settings-button"===t)return!0;if("button"===t){if(!(e.className||"").includes("mic-button"))return!0}return!1}))return;this.dragStartPos={x:e.clientX,y:e.clientY},this.isDragging=!1;const t=this.getBoundingClientRect();this.dragOffset={x:e.clientX-t.left-t.width/2,y:t.bottom-e.clientY},this.boundDragMove=this.handleDragMove.bind(this),this.boundDragEnd=this.handleDragEnd.bind(this),document.addEventListener("mousemove",this.boundDragMove),document.addEventListener("mouseup",this.boundDragEnd)}handleDragMove(e){if(!this.isDragging&&this.dragStartPos){const t=e.clientX-this.dragStartPos.x,i=e.clientY-this.dragStartPos.y;if(!(Math.sqrt(t*t+i*i)>=dh.DRAG_THRESHOLD))return;this.isDragging=!0,e.preventDefault()}this.isDragging&&(e.preventDefault(),this.customPosition={x:e.clientX-this.dragOffset.x,y:window.innerHeight-e.clientY-this.dragOffset.y},this.applyCustomPosition())}handleDragEnd(){this.isDragging&&(this.suppressNextClick=!0),this.isDragging=!1,this.dragStartPos=null,this.boundDragMove&&(document.removeEventListener("mousemove",this.boundDragMove),this.boundDragMove=null),this.boundDragEnd&&(document.removeEventListener("mouseup",this.boundDragEnd),this.boundDragEnd=null)}applyCustomPosition(){this.customPosition&&(this.classList.add("custom-position"),this.style.left=`${this.customPosition.x}px`,this.style.bottom=`${this.customPosition.y}px`)}insertTranscription(e){const t=this.dictationTargetElement;if(!t)return;const i=t.tagName.toLowerCase(),n=this.getElementContent(t)||"";if("input"===i||"textarea"===i){const i=t;i.focus();const n=this.dictationCursorStart??i.value.length,s=this.dictationCursorEnd??i.value.length;i.setSelectionRange(n,s),Tu(i,e),vc.setFocusedElement(i)}else t.isContentEditable&&(t.focus(),vc.setFocusedElement(t),Tu(t,e));gc.emit("transcription:inserted",{text:e,element:t}),this.verifyInsertionApplied(t,e,n),this.dictationTargetElement=null,this.dictationCursorStart=null,this.dictationCursorEnd=null}verifyInsertionApplied(e,t,i){requestAnimationFrame(()=>{const n=e.tagName.toLowerCase();let s="";"input"===n||"textarea"===n?s=e.value:e.isContentEditable&&(s=e.textContent||"");s.includes(t)||""===i&&""!==s||(uc().debug&&console.log("[SpeechOS] Dictation failed to insert, showing fallback modal",{insertedText:t,currentContent:s,originalContent:i}),this.dictationModalText=t,this.dictationModalMode="dictation",this.dictationModalOpen=!0)})}handleActionSelect(e){const{action:t}=e.detail;if(this.clearActionFeedback(),vc.setActiveAction(t),"dictate"===t)this.startDictation();else if("edit"===t){if(!this.widgetState.focusedElement)return this.editHelpModalOpen=!0,void vc.setActiveAction(null);this.startEdit()}else"command"===t?this.startCommand():setTimeout(()=>{vc.setState({isExpanded:!1,activeAction:null})},300)}async withMinDisplayTime(e,t){const[i]=await Promise.all([e,new Promise(e=>setTimeout(e,t))]);return i}async startDictation(){if(this.dictationTargetElement=this.widgetState.focusedElement,this.dictationCursorStart=null,this.dictationCursorEnd=null,uc().debug&&console.log("[SpeechOS] startDictation:",{focusedElement:this.widgetState.focusedElement,dictationTargetElement:this.dictationTargetElement,tagName:this.dictationTargetElement?.tagName}),this.dictationTargetElement){const e=this.dictationTargetElement.tagName.toLowerCase();if("input"===e||"textarea"===e){const e=this.dictationTargetElement;this.supportsSelection(e)?(this.dictationCursorStart=e.selectionStart,this.dictationCursorEnd=e.selectionEnd):(this.dictationCursorStart=e.value.length,this.dictationCursorEnd=e.value.length)}}vc.startRecording();const e=Date.now(),t=Pc();try{await t.startVoiceSession({action:"dictate",settings:hh(),onMicReady:()=>{const t=200-(Date.now()-e),i=()=>{"error"!==vc.getState().recordingState&&(vc.setRecordingState("recording"),this.startNoAudioWarningTracking())};t>0?setTimeout(i,t):i()}})}catch(e){const i=e instanceof Error?e.message:"Connection failed";"Disconnected"!==i&&("error"!==this.widgetState.recordingState&&vc.setError(`Failed to connect: ${i}`),await t.disconnect())}}async startEdit(){if(this.editTargetElement=this.widgetState.focusedElement,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText="",uc().debug&&console.log("[SpeechOS] startEdit:",{focusedElement:this.widgetState.focusedElement,editTargetElement:this.editTargetElement,tagName:this.editTargetElement?.tagName}),this.editTargetElement){const e=this.editTargetElement.tagName.toLowerCase();if("input"===e||"textarea"===e){const e=this.editTargetElement;if(this.supportsSelection(e)){this.editSelectionStart=e.selectionStart,this.editSelectionEnd=e.selectionEnd;(this.editSelectionStart??0)!==(this.editSelectionEnd??0)&&(this.editSelectedText=Cu(e))}else this.editSelectionStart=0,this.editSelectionEnd=0}else if(this.editTargetElement.isContentEditable){const e=Cu(this.editTargetElement);this.editSelectionStart=0,this.editSelectionEnd=e.length,this.editSelectedText=e}}const e=this.getElementContent(this.editTargetElement);vc.startRecording();const t=Date.now(),i=Pc();try{await i.startVoiceSession({action:"edit",inputText:e,settings:hh(),onMicReady:()=>{const e=200-(Date.now()-t),i=()=>{"error"!==vc.getState().recordingState&&(vc.setRecordingState("recording"),this.startNoAudioWarningTracking())};e>0?setTimeout(i,e):i()}})}catch(e){const t=e instanceof Error?e.message:"Connection failed";"Disconnected"!==t&&("error"!==this.widgetState.recordingState&&vc.setError(`Failed to connect: ${t}`),await i.disconnect())}}async handleStopEdit(){vc.stopRecording();const e=this.getElementContent(this.editTargetElement),t=Pc();try{const i=await this.withMinDisplayTime(t.requestEditText(e),300);if(i.trim()===e.trim())return this.trackActionResult(!1),this.showActionFeedback("edit-empty"),vc.completeRecording(),this.editTargetElement=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText="",t.disconnect().catch(()=>{}),void t.startAutoRefresh?.();this.trackActionResult(!0),this.applyEdit(i),t.disconnect().catch(()=>{}),t.startAutoRefresh?.()}catch(e){this.trackActionResult(!1);const i=e instanceof Error?e.message:"Failed to apply edit";"Disconnected"!==i&&(vc.setError(i),t.disconnect().catch(()=>{}))}}async startCommand(){vc.startRecording();const e=Date.now(),t=Pc(),i=_c().commands;try{await t.startVoiceSession({action:"command",commands:i,settings:hh(),onMicReady:()=>{const t=200-(Date.now()-e),i=()=>{"error"!==vc.getState().recordingState&&(vc.setRecordingState("recording"),this.startNoAudioWarningTracking())};t>0?setTimeout(i,t):i()}})}catch(e){const i=e instanceof Error?e.message:"Connection failed";"Disconnected"!==i&&("error"!==this.widgetState.recordingState&&vc.setError(`Failed to connect: ${i}`),await t.disconnect())}}async handleStopCommand(){vc.stopRecording();const e=_c().commands,t=Pc();try{const i=await this.withMinDisplayTime(t.requestCommand(e),300);this.trackActionResult(null!==i);const n=t.getLastInputText?.(),s=i?`${i.name}${Object.keys(i.arguments).length>0?`: ${JSON.stringify(i.arguments)}`:""}`:"No command matched";tl.saveTranscript(s,"command",{inputText:n,commandResult:i,commandConfig:e}),vc.completeRecording(),this.showActionFeedback(i?"command-success":"command-none"),t.disconnect().catch(()=>{}),t.startAutoRefresh?.()}catch(e){this.trackActionResult(!1);const i=e instanceof Error?e.message:"Failed to process command";"Disconnected"!==i&&(vc.setError(i),t.disconnect().catch(()=>{}))}}showActionFeedback(e){this.actionFeedback=e,this.actionFeedbackTimeout&&clearTimeout(this.actionFeedbackTimeout),this.actionFeedbackTimeout=window.setTimeout(()=>{this.actionFeedback=null,this.actionFeedbackTimeout=null},4e3)}clearActionFeedback(){this.actionFeedbackTimeout&&(clearTimeout(this.actionFeedbackTimeout),this.actionFeedbackTimeout=null),this.actionFeedback=null}startNoAudioWarningTracking(){this.transcriptionReceived=!1,this.showNoAudioWarning=!1,this.consecutiveNoAudioActions>=2&&(this.showNoAudioWarning=!0),this.noAudioWarningTimeout=window.setTimeout(()=>{this.transcriptionReceived||"recording"!==this.widgetState.recordingState||(this.showNoAudioWarning=!0)},5e3),this.transcriptionInterimUnsubscribe=gc.on("transcription:interim",()=>{this.transcriptionReceived=!0,this.showNoAudioWarning&&(this.showNoAudioWarning=!1)})}cleanupNoAudioWarningTracking(){null!==this.noAudioWarningTimeout&&(clearTimeout(this.noAudioWarningTimeout),this.noAudioWarningTimeout=null),this.transcriptionInterimUnsubscribe&&(this.transcriptionInterimUnsubscribe(),this.transcriptionInterimUnsubscribe=null),this.showNoAudioWarning=!1}trackActionResult(e){e?this.consecutiveNoAudioActions=0:this.consecutiveNoAudioActions++}async handleOpenSettingsFromWarning(){uc().debug&&console.log("[SpeechOS] No-audio settings link clicked"),this.cleanupNoAudioWarningTracking(),this.settingsOpenFromWarning=!0;const e=Pc().disconnect().catch(e=>{uc().debug&&console.log("[SpeechOS] Disconnect failed while opening settings",e)});if(vc.cancelRecording(),this.dictationTargetElement=null,this.editTargetElement=null,this.dictationCursorStart=null,this.dictationCursorEnd=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText="",Nc()){const e=`${uc().host}/a/extension-settings`;window.open(e,"_blank","noopener,noreferrer")}else this.settingsOpen=!0;uc().debug&&console.log("[SpeechOS] Settings opened from no-audio warning",{useExternalSettings:Nc()}),await e}supportsSelection(e){if("textarea"===e.tagName.toLowerCase())return!0;return["text","search","url","tel","password"].includes(e.type||"text")}getElementContent(e){if(!e)return"";const t=e.tagName.toLowerCase();if("input"===t||"textarea"===t){const t=e;return Cu(t)||t.value}if(e.isContentEditable){return Cu(e)||e.textContent||""}return""}applyEdit(e){const t=this.editTargetElement;if(!t)return void vc.completeRecording();const i=t.tagName.toLowerCase();let n="";if("input"===i||"textarea"===i){const i=t;n=i.value,i.focus();const s=this.editSelectionStart??0,o=this.editSelectionEnd??i.value.length;s!==o?(i.setSelectionRange(s,o),Tu(i,e)):function(e,t){if(yu(e))e.select(),Tu(e,t);else{const i=e.ownerDocument;ku(e,()=>{i.execCommand("selectAll",!1,t),Su(i,t)})}}(i,e),vc.setFocusedElement(i)}else if(t.isContentEditable){n=t.textContent||"";if(null!==this.editSelectionStart&&null!==this.editSelectionEnd&&this.editSelectionStart!==this.editSelectionEnd)t.focus(),Tu(t,e);else{t.focus();const i=window.getSelection();if(i){const e=document.createRange();e.selectNodeContents(t),i.removeAllRanges(),i.addRange(e)}Tu(t,e)}vc.setFocusedElement(t)}tl.saveTranscript(e,"edit",n),gc.emit("edit:applied",{originalContent:n,editedContent:e,element:t}),vc.completeRecording(),this.verifyEditApplied(t,e,n),this.editTargetElement=null,this.editSelectionStart=null,this.editSelectionEnd=null,this.editSelectedText=""}verifyEditApplied(e,t,i){requestAnimationFrame(()=>{const n=e.tagName.toLowerCase();let s="";"input"===n||"textarea"===n?s=e.value:e.isContentEditable&&(s=e.textContent||"");const o=s.trim(),r=t.trim();o!==i.trim()||o===r||o.includes(r)||(uc().debug&&console.log("[SpeechOS] Edit failed to apply, showing fallback modal",{expected:t,actual:s,original:i}),this.dictationModalText=t,this.dictationModalMode="edit",this.dictationModalOpen=!0)})}render(){if(!this.widgetState.isVisible)return this.setAttribute("hidden",""),Wl``;this.removeAttribute("hidden");const e=this.widgetState.isExpanded&&"idle"===this.widgetState.recordingState,t="idle"===this.widgetState.recordingState;return Wl`
3617
3710
  <div class="widget-container" @mousedown="${this.handleDragStart}">
3618
3711
  <speechos-action-bubbles
3619
3712
  ?visible="${e}"
@@ -3644,5 +3737,5 @@
3644
3737
  ></speechos-mic-button>
3645
3738
  </div>
3646
3739
  </div>
3647
- `}};il([gu()],dh.prototype,"widgetState",void 0),il([gu()],dh.prototype,"settingsOpen",void 0),il([gu()],dh.prototype,"dictationModalOpen",void 0),il([gu()],dh.prototype,"dictationModalText",void 0),il([gu()],dh.prototype,"dictationModalMode",void 0),il([gu()],dh.prototype,"editHelpModalOpen",void 0),il([gu()],dh.prototype,"actionFeedback",void 0),il([gu()],dh.prototype,"showNoAudioWarning",void 0),il([gu()],dh.prototype,"isErrorRetryable",void 0),dh=ch=il([uu("speechos-widget")],dh);const lh=customElements.define.bind(customElements);function uh(){return{inputLanguageCode:Qc(),outputLanguageCode:Zc(),smartFormat:sd(),vocabulary:Id().map(e=>e.term),snippets:md().map(e=>({trigger:e.trigger,expansion:e.expansion})),audioDeviceId:$d()}}customElements.define=(e,t,i)=>{e.startsWith("speechos-")?void 0===customElements.get(e)&&lh(e,t,i):lh(e,t,i)},customElements.define=lh;class hh{static{this.instance=null}static{this.widgetElement=null}static{this.isInitialized=!1}static{this.activeFormDetector=null}static init(e){if(this.isInitialized)return void console.warn("SpeechOS is already initialized");try{hc(e),Ac(e)}catch(e){const t=e instanceof Error?e.message:"Invalid configuration";throw console.error(`[SpeechOS] Error: ${t} (init_config)`),gc.emit("error",{code:"init_config",message:t,source:"init"}),e}const t=uc();this.instance=new hh;const i=e.formDetection??!0;!0===i?(Uc.start(),this.activeFormDetector=Uc):"object"==typeof i&&(i.start(),this.activeFormDetector=i),e.textInputHandler&&Vc(e.textInputHandler),this.mountWidget(),Dc()&&vc.show(),this.isInitialized=!0,tl.init().catch(e=>{t.debug&&console.warn("[SpeechOS] Settings sync initialization failed:",e)}),t.debug&&console.log("[SpeechOS] Initialized with config:",t)}static async destroy(){if(!this.isInitialized)return void console.warn("SpeechOS is not initialized");this.activeFormDetector&&(this.activeFormDetector.stop(),this.activeFormDetector=null),await Pc().disconnect(),this.unmountWidget(),gc.clear(),vc.reset(),Mc(),qc(),tl.destroy(),this.instance=null,this.isInitialized=!1;uc().debug&&console.log("[SpeechOS] Destroyed and cleaned up")}static get initialized(){return this.isInitialized}static getState(){return vc.getState()}static get events(){return gc}static getClientConfig(){return _c()}static mountWidget(){if(this.widgetElement)return void console.warn("Widget is already mounted");const e=document.createElement("speechos-widget");this.widgetElement=e,document.body.appendChild(e)}static unmountWidget(){this.widgetElement&&(this.widgetElement.remove(),this.widgetElement=null)}static show(){vc.show()}static hide(){vc.hide()}static showFor(e){this.isInitialized?(vc.setFocusedElement(e),vc.show()):console.warn("SpeechOS.showFor() called before init(). Call init() first.")}static attachTo(e){this.isInitialized?(vc.setFocusedElement(e),vc.show()):console.warn("SpeechOS.attachTo() called before init(). Call init() first.")}static detach(){this.isInitialized?vc.setFocusedElement(null):console.warn("SpeechOS.detach() called before init(). Call init() first.")}static identify(e){if(!this.isInitialized)return void console.warn("SpeechOS.identify() called before init(). Call init() first.");const t=uc();!function(e){lc={...lc,userId:e}}(e),t.debug&&console.log(`[SpeechOS] User identified: ${e}`)}constructor(){}}e.DEFAULT_HOST=cc,e.DefaultTextInputHandler=jc,e.FormDetector=Lc,e.SUPPORTED_LANGUAGES=Wc,e.SpeechOS=hh,e.VERSION="0.1.0",e.addSnippet=yd,e.addTerm=_d,e.audioSettings=Wd,e.clearSnippets=Td,e.clearTranscripts=Xd,e.clearVocabulary=Dd,e.default=hh,e.defaultTextInputHandler=Bc,e.deleteSnippet=Sd,e.deleteTerm=Md,e.deleteTranscript=Zd,e.events=gc,e.formDetector=Uc,e.getAudioDeviceId=$d,e.getAudioInputDevices=qd,e.getAudioSettings=Bd,e.getClientConfig=_c,e.getCommands=function(){return[...Oc.commands]},e.getConfig=uc,e.getInputLanguageCode=Qc,e.getInputLanguageName=id,e.getLanguageByCode=td,e.getLanguageCode=rd,e.getLanguageName=cd,e.getLanguageSettings=Kc,e.getOutputLanguageCode=Zc,e.getOutputLanguageName=nd,e.getSessionSettings=uh,e.getSmartFormatEnabled=sd,e.getSnippetCount=Cd,e.getSnippets=md,e.getTextInputHandler=function(){return $c},e.getTranscripts=Jd,e.getVocabulary=Id,e.getVocabularyCount=Nd,e.getZIndex=function(){return Oc.zIndex},e.hasCommands=function(){return Oc.commands.length>0},e.isAtSnippetLimit=wd,e.isAtVocabularyLimit=Ld,e.isSelectedDeviceAvailable=Hd,e.languageSettings=ld,e.livekit=kc,e.resetAudioSettings=zd,e.resetClientConfig=Mc,e.resetConfig=function(){lc={...dc}},e.resetLanguageSettings=dd,e.resetTextInputHandler=qc,e.saveTranscript=Qd,e.setAudioDeviceId=Vd,e.setClientConfig=Ac,e.setConfig=hc,e.setInputLanguageCode=Xc,e.setLanguageCode=ad,e.setOutputLanguageCode=ed,e.setSmartFormatEnabled=od,e.setTextInputHandler=Vc,e.settingsSync=tl,e.snippetsStore=Ed,e.state=vc,e.transcriptStore=el,e.updateSnippet=kd,e.vocabularyStore=Ud,Object.defineProperty(e,"__esModule",{value:!0})}(this.SpeechOSNamespace=this.SpeechOSNamespace||{}),"undefined"!=typeof window&&(window.SpeechOS=SpeechOSNamespace.SpeechOS,window.SpeechOS.VERSION=SpeechOSNamespace.VERSION,window.SpeechOS.events=SpeechOSNamespace.events,window.SpeechOS.state=SpeechOSNamespace.state,window.SpeechOS.getConfig=SpeechOSNamespace.getConfig,window.SpeechOS.setConfig=SpeechOSNamespace.setConfig,window.SpeechOS.resetConfig=SpeechOSNamespace.resetConfig);
3740
+ `}};nl([fu()],lh.prototype,"widgetState",void 0),nl([fu()],lh.prototype,"settingsOpen",void 0),nl([fu()],lh.prototype,"dictationModalOpen",void 0),nl([fu()],lh.prototype,"dictationModalText",void 0),nl([fu()],lh.prototype,"dictationModalMode",void 0),nl([fu()],lh.prototype,"editHelpModalOpen",void 0),nl([fu()],lh.prototype,"actionFeedback",void 0),nl([fu()],lh.prototype,"showNoAudioWarning",void 0),nl([fu()],lh.prototype,"isErrorRetryable",void 0),lh=dh=nl([hu("speechos-widget")],lh);const uh=customElements.define.bind(customElements);function hh(){return{inputLanguageCode:Xc(),outputLanguageCode:ed(),smartFormat:od(),vocabulary:Od().map(e=>e.term),snippets:gd().map(e=>({trigger:e.trigger,expansion:e.expansion})),audioDeviceId:Vd()}}customElements.define=(e,t,i)=>{e.startsWith("speechos-")?void 0===customElements.get(e)&&uh(e,t,i):uh(e,t,i)},customElements.define=uh;class ph{static{this.instance=null}static{this.widgetElement=null}static{this.isInitialized=!1}static{this.activeFormDetector=null}static init(e){if(this.isInitialized)return void console.warn("SpeechOS is already initialized");try{hc(e),Ac(e)}catch(e){const t=e instanceof Error?e.message:"Invalid configuration";throw console.error(`[SpeechOS] Error: ${t} (init_config)`),gc.emit("error",{code:"init_config",message:t,source:"init"}),e}const t=uc();this.instance=new ph;const i=e.formDetection??!0;!0===i?(Fc.start(),this.activeFormDetector=Fc):"object"==typeof i&&(i.start(),this.activeFormDetector=i),e.textInputHandler&&qc(e.textInputHandler),this.mountWidget(),Dc()&&vc.show(),this.isInitialized=!0,il.init().catch(e=>{t.debug&&console.warn("[SpeechOS] Settings sync initialization failed:",e)}),t.debug&&console.log("[SpeechOS] Initialized with config:",t)}static async destroy(){if(!this.isInitialized)return void console.warn("SpeechOS is not initialized");this.activeFormDetector&&(this.activeFormDetector.stop(),this.activeFormDetector=null),await Pc().disconnect(),this.unmountWidget(),gc.clear(),vc.reset(),Mc(),Hc(),il.destroy(),this.instance=null,this.isInitialized=!1;uc().debug&&console.log("[SpeechOS] Destroyed and cleaned up")}static get initialized(){return this.isInitialized}static getState(){return vc.getState()}static get events(){return gc}static getClientConfig(){return _c()}static mountWidget(){if(this.widgetElement)return void console.warn("Widget is already mounted");const e=document.createElement("speechos-widget");this.widgetElement=e,document.body.appendChild(e)}static unmountWidget(){this.widgetElement&&(this.widgetElement.remove(),this.widgetElement=null)}static show(){vc.show()}static hide(){vc.hide()}static showFor(e){this.isInitialized?(vc.setFocusedElement(e),vc.show()):console.warn("SpeechOS.showFor() called before init(). Call init() first.")}static attachTo(e){this.isInitialized?(vc.setFocusedElement(e),vc.show()):console.warn("SpeechOS.attachTo() called before init(). Call init() first.")}static detach(){this.isInitialized?vc.setFocusedElement(null):console.warn("SpeechOS.detach() called before init(). Call init() first.")}static identify(e){if(!this.isInitialized)return void console.warn("SpeechOS.identify() called before init(). Call init() first.");const t=uc();!function(e){lc={...lc,userId:e}}(e),t.debug&&console.log(`[SpeechOS] User identified: ${e}`)}constructor(){}}e.DEFAULT_HOST=cc,e.DefaultTextInputHandler=Bc,e.FormDetector=Uc,e.SUPPORTED_LANGUAGES=Gc,e.SpeechOS=ph,e.VERSION="0.1.0",e.addSnippet=kd,e.addTerm=Md,e.audioSettings=Gd,e.clearSnippets=Cd,e.clearTranscripts=Zd,e.clearVocabulary=Nd,e.default=ph,e.defaultTextInputHandler=$c,e.deleteSnippet=Td,e.deleteTerm=Dd,e.deleteTranscript=el,e.events=gc,e.formDetector=Fc,e.getAudioDeviceId=Vd,e.getAudioInputDevices=Hd,e.getAudioSettings=$d,e.getClientConfig=_c,e.getCommands=function(){return[...Oc.commands]},e.getConfig=uc,e.getInputLanguageCode=Xc,e.getInputLanguageName=nd,e.getLanguageByCode=id,e.getLanguageCode=ad,e.getLanguageName=dd,e.getLanguageSettings=Jc,e.getOutputLanguageCode=ed,e.getOutputLanguageName=sd,e.getSessionSettings=hh,e.getSmartFormatEnabled=od,e.getSnippetCount=wd,e.getSnippets=gd,e.getTextInputHandler=function(){return Vc},e.getTranscripts=Yd,e.getVocabulary=Od,e.getVocabularyCount=Ld,e.getZIndex=function(){return Oc.zIndex},e.hasCommands=function(){return Oc.commands.length>0},e.isAtSnippetLimit=Ed,e.isAtVocabularyLimit=Ud,e.isSelectedDeviceAvailable=zd,e.languageSettings=ud,e.livekit=kc,e.resetAudioSettings=Wd,e.resetClientConfig=Mc,e.resetConfig=function(){lc={...dc}},e.resetLanguageSettings=ld,e.resetTextInputHandler=Hc,e.saveTranscript=Xd,e.setAudioDeviceId=qd,e.setClientConfig=Ac,e.setConfig=hc,e.setInputLanguageCode=Zc,e.setLanguageCode=cd,e.setOutputLanguageCode=td,e.setSmartFormatEnabled=rd,e.setTextInputHandler=qc,e.settingsSync=il,e.snippetsStore=xd,e.state=vc,e.transcriptStore=tl,e.updateSnippet=Sd,e.useExternalSettings=Nc,e.vocabularyStore=Fd,Object.defineProperty(e,"__esModule",{value:!0})}(this.SpeechOSNamespace=this.SpeechOSNamespace||{}),"undefined"!=typeof window&&(window.SpeechOS=SpeechOSNamespace.SpeechOS,window.SpeechOS.VERSION=SpeechOSNamespace.VERSION,window.SpeechOS.events=SpeechOSNamespace.events,window.SpeechOS.state=SpeechOSNamespace.state,window.SpeechOS.getConfig=SpeechOSNamespace.getConfig,window.SpeechOS.setConfig=SpeechOSNamespace.setConfig,window.SpeechOS.resetConfig=SpeechOSNamespace.resetConfig);
3648
3741
  //# sourceMappingURL=index.iife.min.js.map