function Fs(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var Bs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Js(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var fr={exports:{}};(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Bs,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function s(b,w){var R=b[w];if(typeof R.bind=="function")return R.bind(b);try{return Function.prototype.bind.call(R,b)}catch{return function(){return Function.prototype.apply.apply(R,[b,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 o(b){return b==="debug"&&(b="log"),typeof console===t?!1:b==="trace"&&n?a:console[b]!==void 0?s(console,b):console.log!==void 0?s(console,"log"):e}function c(b,w){for(var R=0;R=0&&D<=I.levels.SILENT){if(B=D,ke!==!1&&Mt(D),c.call(I,D,b),typeof console===t&&DGs||ijs||i<0)throw new Error("invalid uint 32: "+i)}function pr(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>Vs||i({no:r.no,name:r.name,localName:i[r.no]})))}function yr(i,e,t){const n=Object.create(null),r=Object.create(null),s=[];for(const a of e){const o=kr(a);s.push(o),n[a.name]=o,r[a.no]=o}return{typeName:i,values:s,findName(a){return n[a]},findNumber(a){return r[a]}}}function Hs(i,e,t){const n={};for(const r of e){const s=kr(r);n[s.localName]=s.no,n[s.no]=s.localName}return vr(n,i,e),n}function kr(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class C{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),r=n.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const n=this.getType(),r=n.runtime.json,s=r.makeReadOptions(t);return r.readMessage(n,e,s,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,r=n.makeWriteOptions(e),s=r.writerFactory();return n.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,r=n.makeWriteOptions(e);return n.writeMessage(this,r)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function zs(i,e,t,n){var r;const s=(r=n==null?void 0:n.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){i.util.initFields(this),i.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new C),Object.assign(a,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return i.util.equals(a,o,c)}}),a}function Ys(i,e,t,n){return{syntax:i,json:e,bin:t,util:n,makeMessageType(r,s,a){return zs(this,r,s,a)},makeEnum:Hs,makeEnumType:yr,getEnumType:Ks}}var v;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(v||(v={}));var wt;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(wt||(wt={}));function Qs(){let i=0,e=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(i|=(r&127)<>4,!(t&128))return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<>>s,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const n=i>>>28&15|(e&7)<<4,r=!!(e>>3);if(t.push((r?n|128:n)&255),!!r){for(let s=3;s<31;s=s+7){const a=e>>>s,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const pi=4294967296;function En(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,r=0;function s(a,o){const c=Number(i.slice(a,o));r*=t,n=n*t+c,n>=pi&&(r=r+(n/pi|0),n=n%pi)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Tr(n,r):pn(n,r)}function Xs(i,e){let t=pn(i,e);const n=t.hi&2147483648;n&&(t=Tr(t.lo,t.hi));const r=br(t.lo,t.hi);return n?"-"+r:r}function br(i,e){if({lo:i,hi:e}=$s(i,e),e<=2097151)return String(pi*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,r=e>>16&65535;let s=t+n*6777216+r*6710656,a=n+r*8147497,o=r*2;const c=1e7;return s>=c&&(a+=Math.floor(s/c),s%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+Pn(a)+Pn(s)}function $s(i,e){return{lo:i>>>0,hi:e>>>0}}function pn(i,e){return{lo:i|0,hi:e|0}}function Tr(i,e){return e=~e,i?i=~i+1:e+=1,pn(i,e)}const Pn=i=>{const e=String(i);return"0000000".slice(e.length)+e};function wn(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function Zs(){let i=this.buf[this.pos++],e=i&127;if(!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,!(i&128))return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;i&128&&t<10;t++)i=this.buf[this.pos++];if(i&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function ea(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof{NODE_ENV:"development",CHAT_URL:"https://openimhailiao.com/chat",API_URL:"https://openimhailiao.com/api",WS_URL:"wss://openimhailiao.com/msg_gateway",OBJECT_STORAGE:"minio",AMAP_KEY:"36e6a7bb847411f06258d03b066ecc67",AMAP_SNAP_KEY:"39b41b2a48453d7e66007c6f45d26a12",VERSION:"IM-HCER 3.5.1 SDK v3.5.1"}!="object"||{NODE_ENV:"development",CHAT_URL:"https://openimhailiao.com/chat",API_URL:"https://openimhailiao.com/api",WS_URL:"wss://openimhailiao.com/msg_gateway",OBJECT_STORAGE:"minio",AMAP_KEY:"36e6a7bb847411f06258d03b066ecc67",AMAP_SNAP_KEY:"39b41b2a48453d7e66007c6f45d26a12",VERSION:"IM-HCER 3.5.1 SDK v3.5.1"}.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>s||do||dte(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),n=r=>te(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),En(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),n(r),En(r)},dec(r,s){return Xs(r,s)},uDec(r,s){return br(r,s)}}}const N=ea();var U;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(U||(U={}));class ta{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ki(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return mi(e),wn(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){pr(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){Ki(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){mi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return mi(e),e=(e<<1^e>>31)>>>0,wn(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=N.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=N.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=N.enc(e);return Li(t.lo,t.hi,this.buf),this}sint64(e){let t=N.enc(e),n=t.hi>>31,r=t.lo<<1^n,s=(t.hi<<1|t.lo>>>31)^n;return Li(r,s,this.buf),this}uint64(e){let t=N.uEnc(e);return Li(t.lo,t.hi,this.buf),this}}class ia{constructor(e,t){this.varint64=Qs,this.uint32=Zs,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e){let t=this.pos;switch(e){case U.Varint:for(;this.buf[this.pos++]&128;);break;case U.Bit64:this.pos+=4;case U.Bit32:this.pos+=4;break;case U.LengthDelimited:let n=this.uint32();this.pos+=n;break;case U.StartGroup:let r;for(;(r=this.tag()[1])!==U.EndGroup;)this.skip(r);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return N.dec(...this.varint64())}uint64(){return N.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,N.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return N.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return N.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 Hi(i,e){return e instanceof C||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}v.DOUBLE,v.FLOAT,v.INT64,v.UINT64,v.INT32,v.UINT32,v.BOOL,v.STRING,v.BYTES;function mt(i,e,t){if(e===t)return!0;if(i==v.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;nnew ia(i)},In={writeUnknownFields:!0,writerFactory:()=>new ta};function na(i){return i?Object.assign(Object.assign({},Rn),i):Rn}function ra(i){return i?Object.assign(Object.assign({},In),i):In}function sa(){return{makeReadOptions:na,makeWriteOptions:ra,listUnknownFields(i){var e;return(e=i[Lt])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Lt]},writeUnknownFields(i,e){const n=i[Lt];if(n)for(const r of n)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(i,e,t,n){const r=i;Array.isArray(r[Lt])||(r[Lt]=[]),r[Lt].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n){const r=i.getType(),s=t===void 0?e.len:e.pos+t;for(;e.pos0&&(g=oa),u){let R=d[h];if(o==U.LengthDelimited&&m!=v.STRING&&m!=v.BYTES){let I=e.uint32()+e.pos;for(;e.pos>4,a=s,r=2;break;case 2:t[n++]=(a&15)<<4|(s&60)>>2,a=s,r=3;break;case 3:t[n++]=(a&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,r=0;for(let s=0;s>2],r=(n&3)<<4,t=1;break;case 1:e+=Ve[r|n>>4],r=(n&15)<<2,t=2;break;case 2:e+=Ve[r|n>>6],e+=Ve[n&63],t=0;break}return t&&(e+=Ve[r],e+="=",t==1&&(e+="=")),e}},Nn={ignoreUnknownFields:!1},Dn={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function la(i){return i?Object.assign(Object.assign({},Nn),i):Nn}function ha(i){return i?Object.assign(Object.assign({},Dn),i):Dn}function fa(i){const e=i(ma,On);return{makeReadOptions:la,makeWriteOptions:ha,readMessage(t,n,r,s){if(n==null||Array.isArray(n)||typeof n!="object")throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(this.debug(n)));s=s??new t;const a={};for(const[o,c]of Object.entries(n)){const d=t.fields.findJsonName(o);if(!d){if(!r.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(o,'" is unknown'));continue}let u=d.localName,h=s;if(d.oneof){if(c===null&&d.kind=="scalar")continue;const m=a[d.oneof.localName];if(m)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(m,'", "').concat(o,'"'));a[d.oneof.localName]=o,h=h[d.oneof.localName]={case:u},u="value"}if(d.repeated){if(c===null)continue;if(!Array.isArray(c))throw new Error("cannot decode field ".concat(t.typeName,".").concat(d.name," from JSON: ").concat(this.debug(c)));const m=h[u];for(const g of c){if(g===null)throw new Error("cannot decode field ".concat(t.typeName,".").concat(d.name," from JSON: ").concat(this.debug(g)));let k;switch(d.kind){case"message":k=d.T.fromJson(g,r);break;case"enum":if(k=_i(d.T,g,r.ignoreUnknownFields),k===void 0)continue;break;case"scalar":try{k=Ht(d.T,g,d.L)}catch(b){let w="cannot decode field ".concat(t.typeName,".").concat(d.name," from JSON: ").concat(this.debug(g));throw b instanceof Error&&b.message.length>0&&(w+=": ".concat(b.message)),new Error(w)}break}m.push(k)}}else if(d.kind=="map"){if(c===null)continue;if(Array.isArray(c)||typeof c!="object")throw new Error("cannot decode field ".concat(t.typeName,".").concat(d.name," from JSON: ").concat(this.debug(c)));const m=h[u];for(const[g,k]of Object.entries(c)){if(k===null)throw new Error("cannot decode field ".concat(t.typeName,".").concat(d.name," from JSON: map value null"));let b;switch(d.V.kind){case"message":b=d.V.T.fromJson(k,r);break;case"enum":if(b=_i(d.V.T,k,r.ignoreUnknownFields),b===void 0)continue;break;case"scalar":try{b=Ht(d.V.T,k,wt.BIGINT)}catch(w){let R="cannot decode map value for field ".concat(t.typeName,".").concat(d.name," from JSON: ").concat(this.debug(c));throw w instanceof Error&&w.message.length>0&&(R+=": ".concat(w.message)),new Error(R)}break}try{m[Ht(d.K,d.K==v.BOOL?g=="true"?!0:g=="false"?!1:g:g,wt.BIGINT).toString()]=b}catch(w){let R="cannot decode map key for field ".concat(t.typeName,".").concat(d.name," from JSON: ").concat(this.debug(c));throw w instanceof Error&&w.message.length>0&&(R+=": ".concat(w.message)),new Error(R)}}}else switch(d.kind){case"message":const m=d.T;if(c===null&&m.typeName!="google.protobuf.Value"){if(d.oneof)throw new Error("cannot decode field ".concat(t.typeName,".").concat(d.name,' from JSON: null is invalid for oneof field "').concat(o,'"'));continue}h[u]instanceof C?h[u].fromJson(c,r):(h[u]=m.fromJson(c,r),m.fieldWrapper&&!d.oneof&&(h[u]=m.fieldWrapper.unwrapField(h[u])));break;case"enum":const g=_i(d.T,c,r.ignoreUnknownFields);g!==void 0&&(h[u]=g);break;case"scalar":try{h[u]=Ht(d.T,c,d.L)}catch(k){let b="cannot decode field ".concat(t.typeName,".").concat(d.name," from JSON: ").concat(this.debug(c));throw k instanceof Error&&k.message.length>0&&(b+=": ".concat(k.message)),new Error(b)}break}}return s},writeMessage(t,n){const r=t.getType(),s={};let a;try{for(const o of r.fields.byMember()){let c;if(o.kind=="oneof"){const d=t[o.localName];if(d.value===void 0)continue;if(a=o.findField(d.case),!a)throw"oneof case not found: "+d.case;c=e(a,d.value,n)}else a=o,c=e(a,t[a.localName],n);c!==void 0&&(s[n.useProtoFieldName?a.name:a.jsonName]=c)}}catch(o){const c=a?"cannot encode field ".concat(r.typeName,".").concat(a.name," to JSON"):"cannot encode message ".concat(r.typeName," to JSON"),d=o instanceof Error?o.message:String(o);throw new Error(c+(d.length>0?": ".concat(d):""))}return s},readScalar:Ht,writeScalar:On,debug:Er}}function Er(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function Ht(i,e,t){switch(i){case v.DOUBLE:case v.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const n=Number(e);if(Number.isNaN(n)||!Number.isFinite(n))break;return i==v.FLOAT&&pr(n),n;case v.INT32:case v.FIXED32:case v.SFIXED32:case v.SINT32:case v.UINT32:if(e===null)return 0;let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return i==v.UINT32?Ki(r):mi(r),r;case v.INT64:case v.SFIXED64:case v.SINT64:if(e===null)return N.zero;if(typeof e!="number"&&typeof e!="string")break;const s=N.parse(e);return t?s.toString():s;case v.FIXED64:case v.UINT64:if(e===null)return N.zero;if(typeof e!="number"&&typeof e!="string")break;const a=N.uParse(e);return t?a.toString():a;case v.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case v.STRING:if(e===null)return"";if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case v.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return Cr.dec(e)}throw new Error}function _i(i,e,t){if(e===null)return 0;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const n=i.findName(e);if(n||t)return n==null?void 0:n.no;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Er(e)))}function ma(i,e,t,n){var r;if(e===void 0)return e;if(e===0&&!t)return;if(n)return e;if(i.typeName=="google.protobuf.NullValue")return null;const s=i.findNumber(e);return(r=s==null?void 0:s.name)!==null&&r!==void 0?r:e}function On(i,e,t){if(e!==void 0)switch(i){case v.INT32:case v.SFIXED32:case v.SINT32:case v.FIXED32:case v.UINT32:return te(typeof e=="number"),e!=0||t?e:void 0;case v.FLOAT:case v.DOUBLE:return te(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e!==0||t?e:void 0;case v.STRING:return te(typeof e=="string"),e.length>0||t?e:void 0;case v.BOOL:return te(typeof e=="boolean"),e||t?e:void 0;case v.UINT64:case v.FIXED64:case v.INT64:case v.SFIXED64:case v.SINT64:return te(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),t||e!=0?e.toString(10):void 0;case v.BYTES:return te(e instanceof Uint8Array),t||e.byteLength>0?Cr.enc(e):void 0}}function pa(){return fa((i,e)=>function(n,r,s){if(n.kind=="map"){const a={};switch(n.V.kind){case"scalar":for(const[c,d]of Object.entries(r)){const u=e(n.V.T,d,!0);te(u!==void 0),a[c.toString()]=u}break;case"message":for(const[c,d]of Object.entries(r))a[c.toString()]=d.toJson(s);break;case"enum":const o=n.V.T;for(const[c,d]of Object.entries(r)){te(d===void 0||typeof d=="number");const u=i(o,d,!0,s.enumAsInteger);te(u!==void 0),a[c.toString()]=u}break}return s.emitDefaultValues||Object.keys(a).length>0?a:void 0}else if(n.repeated){const a=[];switch(n.kind){case"scalar":for(let o=0;o0?a:void 0}else switch(n.kind){case"scalar":return e(n.T,r,!!n.oneof||n.opt||s.emitDefaultValues);case"enum":return i(n.T,r,!!n.oneof||n.opt||s.emitDefaultValues,s.enumAsInteger);case"message":return r!==void 0?Hi(n.T,r).toJson(s):void 0}})}function ga(){return{setEnumType:vr,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const r=n.localName,s=e,a=i;if(a[r]!==void 0)switch(n.kind){case"oneof":const o=a[r].case;if(o===void 0)continue;const c=n.findField(o);let d=a[r].value;c&&c.kind=="message"&&!(d instanceof c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===v.BYTES&&(d=zt(d)),s[r]={case:o,value:d};break;case"scalar":case"enum":let u=a[r];n.T===v.BYTES&&(u=n.repeated?u.map(zt):zt(u)),s[r]=u;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===v.BYTES)for(const[g,k]of Object.entries(a[r]))s[r][g]=zt(k);else Object.assign(s[r],a[r]);break;case"message":const m=n.V.T;for(const g of Object.keys(a[r])){let k=a[r][g];m.fieldWrapper||(k=new m(k)),s[r][g]=k}break}break;case"message":const h=n.T;if(n.repeated)s[r]=a[r].map(m=>m instanceof h?m:new h(m));else if(a[r]!==void 0){const m=a[r];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?s[r]=zt(m):s[r]=m:s[r]=m instanceof h?m:new h(m)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const r=e[n.localName],s=t[n.localName];if(n.repeated){if(r.length!==s.length)return!1;switch(n.kind){case"message":return r.every((a,o)=>n.T.equals(a,s[o]));case"scalar":return r.every((a,o)=>mt(n.T,a,s[o]));case"enum":return r.every((a,o)=>mt(v.INT32,a,s[o]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":return n.T.equals(r,s);case"enum":return mt(v.INT32,r,s);case"scalar":return mt(n.T,r,s);case"oneof":if(r.case!==s.case)return!1;const a=n.findField(r.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(r.value,s.value);case"enum":return mt(v.INT32,r.value,s.value);case"scalar":return mt(a.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(r).concat(Object.keys(s));switch(n.V.kind){case"message":const c=n.V.T;return o.every(u=>c.equals(r[u],s[u]));case"enum":return o.every(u=>mt(v.INT32,r[u],s[u]));case"scalar":const d=n.V.T;return o.every(u=>mt(d,r[u],s[u]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const r of e.fields.byMember()){const s=i[r.localName];let a;if(r.repeated)a=s.map(li);else if(r.kind=="map"){a=n[r.localName];for(const[o,c]of Object.entries(s))a[o]=li(c)}else r.kind=="oneof"?a=r.findField(s.case)?{case:s.case,value:li(s.value)}:{case:void 0}:a=li(s);n[r.localName]=a}return t}}}function li(i){if(i===void 0)return i;if(i instanceof C)return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function zt(i){return i instanceof Uint8Array?i:new Uint8Array(i)}class va{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;this.numbers=t}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 n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function Pr(i,e){const t=wr(i);return e?t:Ca(Sa(t))}function ya(i){return Pr(i,!1)}const ka=wr;function wr(i){let e=!1;const t=[];for(let n=0;n"".concat(i,"$"),Sa=i=>Ta.has(i)?Rr(i):i,Ca=i=>ba.has(i)?Rr(i):i;class Ea{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=ya(e)}addField(e){te(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 t=0;tDate.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=N.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(tDate.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 n="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?n="."+r.substring(0,3)+"Z":r.substring(6)==="000"?n="."+r.substring(0,6)+"Z":n="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return G.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new G({seconds:N.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new G().fromBinary(e,t)}static fromJson(e,t){return new G().fromJson(e,t)}static fromJsonString(e,t){return new G().fromJsonString(e,t)}static equals(e,t){return l.util.equals(G,e,t)}}G.runtime=l;G.typeName="google.protobuf.Timestamp";G.fields=l.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);var Qi;(function(i){i[i.DEFAULT_AC=0]="DEFAULT_AC",i[i.OPUS=1]="OPUS",i[i.AAC=2]="AAC"})(Qi||(Qi={}));l.util.setEnumType(Qi,"livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]);var Xi;(function(i){i[i.DEFAULT_VC=0]="DEFAULT_VC",i[i.H264_BASELINE=1]="H264_BASELINE",i[i.H264_MAIN=2]="H264_MAIN",i[i.H264_HIGH=3]="H264_HIGH",i[i.VP8=4]="VP8"})(Xi||(Xi={}));l.util.setEnumType(Xi,"livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]);var $i;(function(i){i[i.IC_DEFAULT=0]="IC_DEFAULT",i[i.IC_JPEG=1]="IC_JPEG"})($i||($i={}));l.util.setEnumType($i,"livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]);var z;(function(i){i[i.AUDIO=0]="AUDIO",i[i.VIDEO=1]="VIDEO",i[i.DATA=2]="DATA"})(z||(z={}));l.util.setEnumType(z,"livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]);var F;(function(i){i[i.UNKNOWN=0]="UNKNOWN",i[i.CAMERA=1]="CAMERA",i[i.MICROPHONE=2]="MICROPHONE",i[i.SCREEN_SHARE=3]="SCREEN_SHARE",i[i.SCREEN_SHARE_AUDIO=4]="SCREEN_SHARE_AUDIO"})(F||(F={}));l.util.setEnumType(F,"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"}]);var q;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH",i[i.OFF=3]="OFF"})(q||(q={}));l.util.setEnumType(q,"livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]);var qe;(function(i){i[i.POOR=0]="POOR",i[i.GOOD=1]="GOOD",i[i.EXCELLENT=2]="EXCELLENT",i[i.LOST=3]="LOST"})(qe||(qe={}));l.util.setEnumType(qe,"livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]);var ye;(function(i){i[i.UNSET=0]="UNSET",i[i.DISABLED=1]="DISABLED",i[i.ENABLED=2]="ENABLED"})(ye||(ye={}));l.util.setEnumType(ye,"livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]);var ht;(function(i){i[i.UNKNOWN_REASON=0]="UNKNOWN_REASON",i[i.CLIENT_INITIATED=1]="CLIENT_INITIATED",i[i.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",i[i.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",i[i.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",i[i.ROOM_DELETED=5]="ROOM_DELETED",i[i.STATE_MISMATCH=6]="STATE_MISMATCH",i[i.JOIN_FAILURE=7]="JOIN_FAILURE"})(ht||(ht={}));l.util.setEnumType(ht,"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"}]);var Be;(function(i){i[i.RR_UNKNOWN=0]="RR_UNKNOWN",i[i.RR_SIGNAL_DISCONNECTED=1]="RR_SIGNAL_DISCONNECTED",i[i.RR_PUBLISHER_FAILED=2]="RR_PUBLISHER_FAILED",i[i.RR_SUBSCRIBER_FAILED=3]="RR_SUBSCRIBER_FAILED",i[i.RR_SWITCH_CANDIDATE=4]="RR_SWITCH_CANDIDATE"})(Be||(Be={}));l.util.setEnumType(Be,"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"}]);var ai;(function(i){i[i.SE_UNKNOWN=0]="SE_UNKNOWN",i[i.SE_CODEC_UNSUPPORTED=1]="SE_CODEC_UNSUPPORTED",i[i.SE_TRACK_NOTFOUND=2]="SE_TRACK_NOTFOUND"})(ai||(ai={}));l.util.setEnumType(ai,"livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]);let Gt=class Zt extends C{constructor(e){super(),this.sid="",this.name="",this.emptyTimeout=0,this.maxParticipants=0,this.creationTime=N.zero,this.turnPassword="",this.enabledCodecs=[],this.metadata="",this.numParticipants=0,this.numPublishers=0,this.activeRecording=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new Zt().fromBinary(e,t)}static fromJson(e,t){return new Zt().fromJson(e,t)}static fromJsonString(e,t){return new Zt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Zt,e,t)}};Gt.runtime=l;Gt.typeName="livekit.Room";Gt.fields=l.util.newFieldList(()=>[{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:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:ue,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}]);class ue extends C{constructor(e){super(),this.mime="",this.fmtpLine="",l.util.initPartial(e,this)}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 l.util.equals(ue,e,t)}}ue.runtime=l;ue.typeName="livekit.Codec";ue.fields=l.util.newFieldList(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]);class gt extends C{constructor(e){super(),this.enabled=!1,this.min=0,this.max=0,l.util.initPartial(e,this)}static fromBinary(e,t){return new gt().fromBinary(e,t)}static fromJson(e,t){return new gt().fromJson(e,t)}static fromJsonString(e,t){return new gt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(gt,e,t)}}gt.runtime=l;gt.typeName="livekit.PlayoutDelay";gt.fields=l.util.newFieldList(()=>[{no:1,name:"enabled",kind:"scalar",T:8},{no:2,name:"min",kind:"scalar",T:13},{no:3,name:"max",kind:"scalar",T:13}]);class je extends C{constructor(e){super(),this.canSubscribe=!1,this.canPublish=!1,this.canPublishData=!1,this.canPublishSources=[],this.hidden=!1,this.recorder=!1,this.canUpdateMetadata=!1,this.agent=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new je().fromBinary(e,t)}static fromJson(e,t){return new je().fromJson(e,t)}static fromJsonString(e,t){return new je().fromJsonString(e,t)}static equals(e,t){return l.util.equals(je,e,t)}}je.runtime=l;je.typeName="livekit.ParticipantPermission";je.fields=l.util.newFieldList(()=>[{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:l.getEnumType(F),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}]);class se extends C{constructor(e){super(),this.sid="",this.identity="",this.state=Rt.JOINING,this.tracks=[],this.metadata="",this.joinedAt=N.zero,this.name="",this.version=0,this.region="",this.isPublisher=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new se().fromBinary(e,t)}static fromJson(e,t){return new se().fromJson(e,t)}static fromJsonString(e,t){return new se().fromJsonString(e,t)}static equals(e,t){return l.util.equals(se,e,t)}}se.runtime=l;se.typeName="livekit.ParticipantInfo";se.fields=l.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:l.getEnumType(Rt)},{no:4,name:"tracks",kind:"message",T:ie,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",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:je},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8}]);var Rt;(function(i){i[i.JOINING=0]="JOINING",i[i.JOINED=1]="JOINED",i[i.ACTIVE=2]="ACTIVE",i[i.DISCONNECTED=3]="DISCONNECTED"})(Rt||(Rt={}));l.util.setEnumType(Rt,"livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]);class vt extends C{constructor(e){super(),l.util.initPartial(e,this)}static fromBinary(e,t){return new vt().fromBinary(e,t)}static fromJson(e,t){return new vt().fromJson(e,t)}static fromJsonString(e,t){return new vt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(vt,e,t)}}vt.runtime=l;vt.typeName="livekit.Encryption";vt.fields=l.util.newFieldList(()=>[]);var K;(function(i){i[i.NONE=0]="NONE",i[i.GCM=1]="GCM",i[i.CUSTOM=2]="CUSTOM"})(K||(K={}));l.util.setEnumType(K,"livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]);class Ge extends C{constructor(e){super(),this.mimeType="",this.mid="",this.cid="",this.layers=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Ge().fromBinary(e,t)}static fromJson(e,t){return new Ge().fromJson(e,t)}static fromJsonString(e,t){return new Ge().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Ge,e,t)}}Ge.runtime=l;Ge.typeName="livekit.SimulcastCodecInfo";Ge.fields=l.util.newFieldList(()=>[{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:$,repeated:!0}]);class ie extends C{constructor(e){super(),this.sid="",this.type=z.AUDIO,this.name="",this.muted=!1,this.width=0,this.height=0,this.simulcast=!1,this.disableDtx=!1,this.source=F.UNKNOWN,this.layers=[],this.mimeType="",this.mid="",this.codecs=[],this.stereo=!1,this.disableRed=!1,this.encryption=K.NONE,this.stream="",l.util.initPartial(e,this)}static fromBinary(e,t){return new ie().fromBinary(e,t)}static fromJson(e,t){return new ie().fromJson(e,t)}static fromJsonString(e,t){return new ie().fromJsonString(e,t)}static equals(e,t){return l.util.equals(ie,e,t)}}ie.runtime=l;ie.typeName="livekit.TrackInfo";ie.fields=l.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:l.getEnumType(z)},{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:l.getEnumType(F)},{no:10,name:"layers",kind:"message",T:$,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:Ge,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:l.getEnumType(K)},{no:17,name:"stream",kind:"scalar",T:9}]);class $ extends C{constructor(e){super(),this.quality=q.LOW,this.width=0,this.height=0,this.bitrate=0,this.ssrc=0,l.util.initPartial(e,this)}static fromBinary(e,t){return new $().fromBinary(e,t)}static fromJson(e,t){return new $().fromJson(e,t)}static fromJsonString(e,t){return new $().fromJsonString(e,t)}static equals(e,t){return l.util.equals($,e,t)}}$.runtime=l;$.typeName="livekit.VideoLayer";$.fields=l.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:l.getEnumType(q)},{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}]);class Te extends C{constructor(e){super(),this.kind=W.RELIABLE,this.value={case:void 0},l.util.initPartial(e,this)}static fromBinary(e,t){return new Te().fromBinary(e,t)}static fromJson(e,t){return new Te().fromJson(e,t)}static fromJsonString(e,t){return new Te().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Te,e,t)}}Te.runtime=l;Te.typeName="livekit.DataPacket";Te.fields=l.util.newFieldList(()=>[{no:1,name:"kind",kind:"enum",T:l.getEnumType(W)},{no:2,name:"user",kind:"message",T:Ce,oneof:"value"},{no:3,name:"speaker",kind:"message",T:We,oneof:"value"}]);var W;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY"})(W||(W={}));l.util.setEnumType(W,"livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]);class We extends C{constructor(e){super(),this.speakers=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new We().fromBinary(e,t)}static fromJson(e,t){return new We().fromJson(e,t)}static fromJsonString(e,t){return new We().fromJsonString(e,t)}static equals(e,t){return l.util.equals(We,e,t)}}We.runtime=l;We.typeName="livekit.ActiveSpeakerUpdate";We.fields=l.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:Se,repeated:!0}]);class Se extends C{constructor(e){super(),this.sid="",this.level=0,this.active=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new Se().fromBinary(e,t)}static fromJson(e,t){return new Se().fromJson(e,t)}static fromJsonString(e,t){return new Se().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Se,e,t)}}Se.runtime=l;Se.typeName="livekit.SpeakerInfo";Se.fields=l.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]);class Ce extends C{constructor(e){super(),this.participantSid="",this.participantIdentity="",this.payload=new Uint8Array(0),this.destinationSids=[],this.destinationIdentities=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Ce().fromBinary(e,t)}static fromJson(e,t){return new Ce().fromJson(e,t)}static fromJsonString(e,t){return new Ce().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Ce,e,t)}}Ce.runtime=l;Ce.typeName="livekit.UserPacket";Ce.fields=l.util.newFieldList(()=>[{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}]);class Ee extends C{constructor(e){super(),this.participantSid="",this.trackSids=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Ee().fromBinary(e,t)}static fromJson(e,t){return new Ee().fromJson(e,t)}static fromJsonString(e,t){return new Ee().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Ee,e,t)}}Ee.runtime=l;Ee.typeName="livekit.ParticipantTracks";Ee.fields=l.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]);class Ke extends C{constructor(e){super(),this.edition=Vt.Standard,this.version="",this.protocol=0,this.region="",this.nodeId="",this.debugInfo="",l.util.initPartial(e,this)}static fromBinary(e,t){return new Ke().fromBinary(e,t)}static fromJson(e,t){return new Ke().fromJson(e,t)}static fromJsonString(e,t){return new Ke().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Ke,e,t)}}Ke.runtime=l;Ke.typeName="livekit.ServerInfo";Ke.fields=l.util.newFieldList(()=>[{no:1,name:"edition",kind:"enum",T:l.getEnumType(Vt)},{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}]);var Vt;(function(i){i[i.Standard=0]="Standard",i[i.Cloud=1]="Cloud"})(Vt||(Vt={}));l.util.setEnumType(Vt,"livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]);class He extends C{constructor(e){super(),this.sdk=qt.UNKNOWN,this.version="",this.protocol=0,this.os="",this.osVersion="",this.deviceModel="",this.browser="",this.browserVersion="",this.address="",this.network="",l.util.initPartial(e,this)}static fromBinary(e,t){return new He().fromBinary(e,t)}static fromJson(e,t){return new He().fromJson(e,t)}static fromJsonString(e,t){return new He().fromJsonString(e,t)}static equals(e,t){return l.util.equals(He,e,t)}}He.runtime=l;He.typeName="livekit.ClientInfo";He.fields=l.util.newFieldList(()=>[{no:1,name:"sdk",kind:"enum",T:l.getEnumType(qt)},{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}]);var qt;(function(i){i[i.UNKNOWN=0]="UNKNOWN",i[i.JS=1]="JS",i[i.SWIFT=2]="SWIFT",i[i.ANDROID=3]="ANDROID",i[i.FLUTTER=4]="FLUTTER",i[i.GO=5]="GO",i[i.UNITY=6]="UNITY",i[i.REACT_NATIVE=7]="REACT_NATIVE",i[i.RUST=8]="RUST",i[i.PYTHON=9]="PYTHON",i[i.CPP=10]="CPP"})(qt||(qt={}));l.util.setEnumType(qt,"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"}]);class Pe extends C{constructor(e){super(),this.resumeConnection=ye.UNSET,this.forceRelay=ye.UNSET,l.util.initPartial(e,this)}static fromBinary(e,t){return new Pe().fromBinary(e,t)}static fromJson(e,t){return new Pe().fromJson(e,t)}static fromJsonString(e,t){return new Pe().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Pe,e,t)}}Pe.runtime=l;Pe.typeName="livekit.ClientConfiguration";Pe.fields=l.util.newFieldList(()=>[{no:1,name:"video",kind:"message",T:we},{no:2,name:"screen",kind:"message",T:we},{no:3,name:"resume_connection",kind:"enum",T:l.getEnumType(ye)},{no:4,name:"disabled_codecs",kind:"message",T:ze},{no:5,name:"force_relay",kind:"enum",T:l.getEnumType(ye)}]);class we extends C{constructor(e){super(),this.hardwareEncoder=ye.UNSET,l.util.initPartial(e,this)}static fromBinary(e,t){return new we().fromBinary(e,t)}static fromJson(e,t){return new we().fromJson(e,t)}static fromJsonString(e,t){return new we().fromJsonString(e,t)}static equals(e,t){return l.util.equals(we,e,t)}}we.runtime=l;we.typeName="livekit.VideoConfiguration";we.fields=l.util.newFieldList(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:l.getEnumType(ye)}]);class ze extends C{constructor(e){super(),this.codecs=[],this.publish=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new ze().fromBinary(e,t)}static fromJson(e,t){return new ze().fromJson(e,t)}static fromJsonString(e,t){return new ze().fromJsonString(e,t)}static equals(e,t){return l.util.equals(ze,e,t)}}ze.runtime=l;ze.typeName="livekit.DisabledCodecs";ze.fields=l.util.newFieldList(()=>[{no:1,name:"codecs",kind:"message",T:ue,repeated:!0},{no:2,name:"publish",kind:"message",T:ue,repeated:!0}]);class Re extends C{constructor(e){super(),this.duration=0,this.startTimestamp=N.zero,this.endTimestamp=N.zero,this.rtpClockTicks=N.zero,this.driftSamples=N.zero,this.driftMs=0,this.clockRate=0,l.util.initPartial(e,this)}static fromBinary(e,t){return new Re().fromBinary(e,t)}static fromJson(e,t){return new Re().fromJson(e,t)}static fromJsonString(e,t){return new Re().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Re,e,t)}}Re.runtime=l;Re.typeName="livekit.RTPDrift";Re.fields=l.util.newFieldList(()=>[{no:1,name:"start_time",kind:"message",T:G},{no:2,name:"end_time",kind:"message",T:G},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"start_timestamp",kind:"scalar",T:4},{no:5,name:"end_timestamp",kind:"scalar",T:4},{no:6,name:"rtp_clock_ticks",kind:"scalar",T:4},{no:7,name:"drift_samples",kind:"scalar",T:3},{no:8,name:"drift_ms",kind:"scalar",T:1},{no:9,name:"clock_rate",kind:"scalar",T:1}]);class yt extends C{constructor(e){super(),this.duration=0,this.packets=0,this.packetRate=0,this.bytes=N.zero,this.headerBytes=N.zero,this.bitrate=0,this.packetsLost=0,this.packetLossRate=0,this.packetLossPercentage=0,this.packetsDuplicate=0,this.packetDuplicateRate=0,this.bytesDuplicate=N.zero,this.headerBytesDuplicate=N.zero,this.bitrateDuplicate=0,this.packetsPadding=0,this.packetPaddingRate=0,this.bytesPadding=N.zero,this.headerBytesPadding=N.zero,this.bitratePadding=0,this.packetsOutOfOrder=0,this.frames=0,this.frameRate=0,this.jitterCurrent=0,this.jitterMax=0,this.gapHistogram={},this.nacks=0,this.nackAcks=0,this.nackMisses=0,this.nackRepeated=0,this.plis=0,this.firs=0,this.rttCurrent=0,this.rttMax=0,this.keyFrames=0,this.layerLockPlis=0,l.util.initPartial(e,this)}static fromBinary(e,t){return new yt().fromBinary(e,t)}static fromJson(e,t){return new yt().fromJson(e,t)}static fromJsonString(e,t){return new yt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(yt,e,t)}}yt.runtime=l;yt.typeName="livekit.RTPStats";yt.fields=l.util.newFieldList(()=>[{no:1,name:"start_time",kind:"message",T:G},{no:2,name:"end_time",kind:"message",T:G},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"packets",kind:"scalar",T:13},{no:5,name:"packet_rate",kind:"scalar",T:1},{no:6,name:"bytes",kind:"scalar",T:4},{no:39,name:"header_bytes",kind:"scalar",T:4},{no:7,name:"bitrate",kind:"scalar",T:1},{no:8,name:"packets_lost",kind:"scalar",T:13},{no:9,name:"packet_loss_rate",kind:"scalar",T:1},{no:10,name:"packet_loss_percentage",kind:"scalar",T:2},{no:11,name:"packets_duplicate",kind:"scalar",T:13},{no:12,name:"packet_duplicate_rate",kind:"scalar",T:1},{no:13,name:"bytes_duplicate",kind:"scalar",T:4},{no:40,name:"header_bytes_duplicate",kind:"scalar",T:4},{no:14,name:"bitrate_duplicate",kind:"scalar",T:1},{no:15,name:"packets_padding",kind:"scalar",T:13},{no:16,name:"packet_padding_rate",kind:"scalar",T:1},{no:17,name:"bytes_padding",kind:"scalar",T:4},{no:41,name:"header_bytes_padding",kind:"scalar",T:4},{no:18,name:"bitrate_padding",kind:"scalar",T:1},{no:19,name:"packets_out_of_order",kind:"scalar",T:13},{no:20,name:"frames",kind:"scalar",T:13},{no:21,name:"frame_rate",kind:"scalar",T:1},{no:22,name:"jitter_current",kind:"scalar",T:1},{no:23,name:"jitter_max",kind:"scalar",T:1},{no:24,name:"gap_histogram",kind:"map",K:5,V:{kind:"scalar",T:13}},{no:25,name:"nacks",kind:"scalar",T:13},{no:37,name:"nack_acks",kind:"scalar",T:13},{no:26,name:"nack_misses",kind:"scalar",T:13},{no:38,name:"nack_repeated",kind:"scalar",T:13},{no:27,name:"plis",kind:"scalar",T:13},{no:28,name:"last_pli",kind:"message",T:G},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:G},{no:31,name:"rtt_current",kind:"scalar",T:13},{no:32,name:"rtt_max",kind:"scalar",T:13},{no:33,name:"key_frames",kind:"scalar",T:13},{no:34,name:"last_key_frame",kind:"message",T:G},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:G},{no:44,name:"packet_drift",kind:"message",T:Re},{no:45,name:"report_drift",kind:"message",T:Re}]);class kt extends C{constructor(e){super(),this.unixMicro=N.zero,this.ticks=0,l.util.initPartial(e,this)}static fromBinary(e,t){return new kt().fromBinary(e,t)}static fromJson(e,t){return new kt().fromJson(e,t)}static fromJsonString(e,t){return new kt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(kt,e,t)}}kt.runtime=l;kt.typeName="livekit.TimedVersion";kt.fields=l.util.newFieldList(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]);const Yt=7e3,wa=[0,300,2*2*300,3*3*300,4*4*300,Yt,Yt,Yt,Yt,Yt];class Ra{constructor(e){this._retryDelays=e!==void 0?[...e]:wa}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function p(i,e,t,n){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(u){try{d(n.next(u))}catch(h){a(h)}}function c(u){try{d(n.throw(u))}catch(h){a(h)}}function d(u){u.done?s(u.value):r(u.value).then(o,c)}d((n=n.apply(i,e||[])).next())})}function Mn(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function _t(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof Mn=="function"?Mn(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=i[s]&&function(a){return new Promise(function(o,c){a=i[s](a),r(o,c,a.done,a.value)})}}function r(s,a,o,c){Promise.resolve(c).then(function(d){s({value:d,done:o})},a)}}var gn={exports:{}},Ut=typeof Reflect=="object"?Reflect:null,An=Ut&&typeof Ut.apply=="function"?Ut.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},vi;Ut&&typeof Ut.ownKeys=="function"?vi=Ut.ownKeys:Object.getOwnPropertySymbols?vi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:vi=function(e){return Object.getOwnPropertyNames(e)};function Ia(i){console&&console.warn&&console.warn(i)}var Ir=Number.isNaN||function(e){return e!==e};function M(){M.init.call(this)}gn.exports=M;gn.exports.once=Ma;M.EventEmitter=M;M.prototype._events=void 0;M.prototype._eventsCount=0;M.prototype._maxListeners=void 0;var Ln=10;function Oi(i){if(typeof i!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof i)}Object.defineProperty(M,"defaultMaxListeners",{enumerable:!0,get:function(){return Ln},set:function(i){if(typeof i!="number"||i<0||Ir(i))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+i+".");Ln=i}});M.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};M.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Ir(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};function Nr(i){return i._maxListeners===void 0?M.defaultMaxListeners:i._maxListeners}M.prototype.getMaxListeners=function(){return Nr(this)};M.prototype.emit=function(e){for(var t=[],n=1;n0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")An(c,this,t);else for(var d=c.length,u=Lr(c,d),n=0;n0&&a.length>r&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=i,o.type=e,o.count=a.length,Ia(o)}return i}M.prototype.addListener=function(e,t){return Dr(this,e,t,!1)};M.prototype.on=M.prototype.addListener;M.prototype.prependListener=function(e,t){return Dr(this,e,t,!0)};function Na(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Or(i,e,t){var n={fired:!1,wrapFn:void 0,target:i,type:e,listener:t},r=Na.bind(n);return r.listener=t,n.wrapFn=r,r}M.prototype.once=function(e,t){return Oi(t),this.on(e,Or(this,e,t)),this};M.prototype.prependOnceListener=function(e,t){return Oi(t),this.prependListener(e,Or(this,e,t)),this};M.prototype.removeListener=function(e,t){var n,r,s,a,o;if(Oi(t),r=this._events,r===void 0)return this;if(n=r[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(s=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,s=a;break}if(s<0)return this;s===0?n.shift():Da(n,s),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit("removeListener",e,o||t)}return this};M.prototype.off=M.prototype.removeListener;M.prototype.removeAllListeners=function(e){var t,n,r;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),a;for(r=0;r=0;r--)this.removeListener(e,t[r]);return this};function Mr(i,e,t){var n=i._events;if(n===void 0)return[];var r=n[e];return r===void 0?[]:typeof r=="function"?t?[r.listener||r]:[r]:t?Oa(r):Lr(r,r.length)}M.prototype.listeners=function(e){return Mr(this,e,!0)};M.prototype.rawListeners=function(e){return Mr(this,e,!1)};M.listenerCount=function(i,e){return typeof i.listenerCount=="function"?i.listenerCount(e):Ar.call(i,e)};M.prototype.listenerCount=Ar;function Ar(i){var e=this._events;if(e!==void 0){var t=e[i];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}M.prototype.eventNames=function(){return this._eventsCount>0?vi(this._events):[]};function Lr(i,e){for(var t=new Array(e),n=0;n=t&&parseInt(n[t],10)}function Ot(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return r.apply(this,arguments);const c=d=>{const u=t(d);u&&(o.handleEvent?o.handleEvent(u):o(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),r.apply(this,[a,c])};const s=n.removeEventListener;n.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(o))return s.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function La(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(xr=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function _a(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Ur=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Fr(){if(typeof window=="object"){if(xr)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function vn(i,e){Ur&&console.warn(i+" is deprecated, please use "+e+" instead.")}function xa(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.mozGetUserMedia)e.browser="firefox",e.version=yi(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=yi(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=yi(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function _n(i){return Object.prototype.toString.call(i)==="[object Object]"}function Br(i){return _n(i)?Object.keys(i).reduce(function(e,t){const n=_n(i[t]),r=n?Br(i[t]):i[t],s=n&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):i}function Zi(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Zi(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(r=>{Zi(i,i.get(r),t)})}))}function xn(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return i.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{i.forEach(o=>{o.type===n&&o.trackId===a.id&&Zi(i,o,r)})}),r}const Un=Fr;function Jr(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const u=typeof o[d]=="object"?o[d]:{ideal:o[d]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const h=function(m,g){return m?m+g.charAt(0).toUpperCase()+g.slice(1):g==="deviceId"?"sourceId":g};if(u.ideal!==void 0){c.optional=c.optional||[];let m={};typeof u.ideal=="number"?(m[h("min",d)]=u.ideal,c.optional.push(m),m={},m[h("max",d)]=u.ideal,c.optional.push(m)):(m[h("",d)]=u.ideal,c.optional.push(m))}u.exact!==void 0&&typeof u.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",d)]=u.exact):["min","max"].forEach(m=>{u[m]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(m,d)]=u[m])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},r=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(u,h,m){h in u&&!(m in u)&&(u[m]=u[h],delete u[h])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const u=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete o.video.facingMode;let h;if(d.exact==="environment"||d.ideal==="environment"?h=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(m=>{m=m.filter(k=>k.kind==="videoinput");let g=m.find(k=>h.some(b=>k.label.toLowerCase().includes(b)));return!g&&m.length&&h.includes("back")&&(g=m[m.length-1]),g&&(o.video.deviceId=d.exact?{exact:g.deviceId}:{ideal:g.deviceId}),o.video=n(o.video),Un("chrome: "+JSON.stringify(o)),c(o)})}o.video=n(o.video)}return Un("chrome: "+JSON.stringify(o)),c(o)},s=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,d){r(o,u=>{t.webkitGetUserMedia(u,c,h=>{d&&d(s(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return r(c,d=>o(d).then(u=>{if(d.audio&&!u.getAudioTracks().length||d.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function Ua(i,e){if(!(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices)&&i.navigator.mediaDevices){if(typeof e!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}i.navigator.mediaDevices.getDisplayMedia=function(n){return e(n).then(r=>{const s=n.video&&n.video.width,a=n.video&&n.video.height,o=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:r,maxFrameRate:o||3}},s&&(n.video.mandatory.maxWidth=s),a&&(n.video.mandatory.maxHeight=a),i.navigator.mediaDevices.getUserMedia(n)})}}}function Vr(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function qr(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",r=>{let s;i.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.track.id):s={track:r.track};const a=new Event("track");a.track=r.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(r=>{let s;i.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.id):s={track:r};const a=new Event("track");a.track=r,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Ot(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function jr(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,c){let d=r.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Gr(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[n,r,s]=arguments;if(arguments.length>0&&typeof n=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof n!="function"))return e.apply(this,[]);const a=function(c){const d={};return c.result().forEach(h=>{const m={id:h.id,timestamp:h.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[h.type]||h.type};h.names().forEach(g=>{m[g]=h.stat(g)}),d[m.id]=m}),d},o=function(c){return new Map(Object.keys(c).map(d=>[d,c[d]]))};if(arguments.length>=2){const c=function(d){r(o(a(d)))};return e.apply(this,[c,n])}return new Promise((c,d)=>{e.apply(this,[function(u){c(o(a(u)))},d])}).then(r,s)}}function Wr(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=t.apply(this,[]);return s.forEach(a=>a._pc=this),s});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=n.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>xn(a,s.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const r=t.apply(this,[]);return r.forEach(s=>s._pc=this),r}),Ot(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>xn(s,r.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let r,s,a;return this.getSenders().forEach(o=>{o.track===n&&(r?a=!0:r=o)}),this.getReceivers().forEach(o=>(o.track===n&&(s?a=!0:s=o),o.track===n)),a||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Kr(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(h=>h.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),r.apply(this,arguments)}}function Hr(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Kr(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(h=>this._reverseStreams[h.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(h=>{if(this.getSenders().find(g=>g.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const h=new i.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}n.apply(this,[u])};const r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},i.RTCPeerConnection.prototype.addTrack=function(u,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const m=[].slice.call(arguments,1);if(m.length!==1||!m[0].getTracks().find(b=>b===u))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(b=>b.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const k=this._streams[h.id];if(k)k.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const b=new i.MediaStream([u]);this._streams[h.id]=b,this._reverseStreams[b.id]=h,this.addStream(b)}return this.getSenders().find(b=>b.track===u)};function s(d,u){let h=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(m=>{const g=d._reverseStreams[m],k=d._streams[g.id];h=h.replace(new RegExp(k.id,"g"),g.id)}),new RTCSessionDescription({type:u.type,sdp:h})}function a(d,u){let h=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(m=>{const g=d._reverseStreams[m],k=d._streams[g.id];h=h.replace(new RegExp(g.id,"g"),k.id)}),new RTCSessionDescription({type:u.type,sdp:h})}["createOffer","createAnswer"].forEach(function(d){const u=i.RTCPeerConnection.prototype[d],h={[d](){const m=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[k=>{const b=s(this,k);m[0].apply(null,[b])},k=>{m[1]&&m[1].apply(null,k)},arguments[2]]):u.apply(this,arguments).then(k=>s(this,k))}};i.RTCPeerConnection.prototype[d]=h[d]});const o=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:s(this,d)}}),i.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let m;Object.keys(this._streams).forEach(g=>{this._streams[g].getTracks().find(b=>u.track===b)&&(m=this._streams[g])}),m&&(m.getTracks().length===1?this.removeStream(this._reverseStreams[m.id]):m.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function en(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]})}function zr(i,e){Ot(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Fn=Object.freeze({__proto__:null,fixNegotiationNeeded:zr,shimAddTrackRemoveTrack:Hr,shimAddTrackRemoveTrackWithNative:Kr,shimGetDisplayMedia:Ua,shimGetSendersWithDtmf:jr,shimGetStats:Gr,shimGetUserMedia:Jr,shimMediaStream:Vr,shimOnTrack:qr,shimPeerConnection:en,shimSenderReceiverGetStats:Wr});function Yr(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(r,s,a){vn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a.audio,"autoGainControl","mozAutoGainControl"),r(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const o=a.apply(this,arguments);return r(o,"mozAutoGainControl","autoGainControl"),r(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o,"autoGainControl","mozAutoGainControl"),r(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Fa(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function Qr(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function tn(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=i.RTCPeerConnection.prototype[r],a={[r](){return arguments[0]=new(r==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};i.RTCPeerConnection.prototype[r]=a[r]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[s,a,o]=arguments;return n.apply(this,[s||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((u,h)=>{c.set(h,Object.assign({},u,{type:t[u.type]||u.type}))})}return c}).then(a,o)}}function Xr(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=t.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function $r(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n}),Ot(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Zr(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){vn("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function es(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function ts(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const r=n.length>0;r&&n.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(r){const{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function is(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function ns(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function rs(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Bn=Object.freeze({__proto__:null,shimAddTransceiver:ts,shimCreateAnswer:rs,shimCreateOffer:ns,shimGetDisplayMedia:Fa,shimGetParameters:is,shimGetUserMedia:Yr,shimOnTrack:Qr,shimPeerConnection:tn,shimRTCDataChannel:es,shimReceiverGetStats:$r,shimRemoveStream:Zr,shimSenderGetStats:Xr});function ss(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(r=>e.call(this,r,n)),n.getVideoTracks().forEach(r=>e.call(this,r,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function as(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(s)>=0)return;n._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function os(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(d,u){const h=arguments.length>=2?arguments[2]:arguments[0],m=t.apply(this,[h]);return u?(m.then(d,u),Promise.resolve()):m},e.createAnswer=function(d,u){const h=arguments.length>=2?arguments[2]:arguments[0],m=n.apply(this,[h]);return u?(m.then(d,u),Promise.resolve()):m};let o=function(c,d,u){const h=r.apply(this,[c]);return u?(h.then(d,u),Promise.resolve()):h};e.setLocalDescription=o,o=function(c,d,u){const h=s.apply(this,[c]);return u?(h.then(d,u),Promise.resolve()):h},e.setRemoteDescription=o,o=function(c,d,u){const h=a.apply(this,[c]);return u?(h.then(d,u),Promise.resolve()):h},e.addIceCandidate=o}function cs(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>n(ds(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,r,s){e.mediaDevices.getUserMedia(n).then(r,s)}).bind(e))}function ds(i){return i&&i.video!==void 0?Object.assign({},i,{video:Br(i.video)}):i}function us(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,r){if(n&&n.iceServers){const s=[];for(let a=0;aa.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function fs(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var Jn=Object.freeze({__proto__:null,shimAudioContext:fs,shimCallbacksAPI:os,shimConstraints:ds,shimCreateOfferLegacy:hs,shimGetUserMedia:cs,shimLocalStreamsAPI:ss,shimRTCIceServerUrls:us,shimRemoteStreamsAPI:as,shimTrackEventTransceiver:ls}),ms={exports:{}};(function(i){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(` `).map(n=>n.trim())},e.splitSections=function(t){return t.split(` m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r `)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(r=>r.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const r={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let s=8;s0?n[0].split("/")[1]:"sendrecv",uri:n[1],attributes:n.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r `},e.parseFmtp=function(t){const n={};let r;const s=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a{t.parameters[a]!==void 0?s.push(a+"="+t.parameters[a]):s.push(a)}),n+="a=fmtp:"+r+" "+s.join(";")+`\r `}return n},e.parseRtcpFb=function(t){const n=t.substring(t.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(t){let n="",r=t.payloadType;return t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{n+="a=rtcp-fb:"+r+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r `}),n},e.parseSsrcMedia=function(t){const n=t.indexOf(" "),r={ssrc:parseInt(t.substring(7,n),10)},s=t.indexOf(":",n);return s>-1?(r.attribute=t.substring(n+1,s),r.value=t.substring(s+1)):r.attribute=t.substring(n+1),r},e.parseSsrcGroup=function(t){const n=t.substring(13).split(" ");return{semantics:n.shift(),ssrcs:n.map(r=>parseInt(r,10))}},e.getMid=function(t){const n=e.matchPrefix(t,"a=mid:")[0];if(n)return n.substring(6)},e.parseFingerprint=function(t){const n=t.substring(14).split(" ");return{algorithm:n[0].toLowerCase(),value:n[1].toUpperCase()}},e.getDtlsParameters=function(t,n){return{role:"auto",fingerprints:e.matchPrefix(t+n,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,n){let r="a=setup:"+n+`\r `;return t.fingerprints.forEach(s=>{r+="a=fingerprint:"+s.algorithm+" "+s.value+`\r `}),r},e.parseCryptoLine=function(t){const n=t.substring(9).split(" ");return{tag:parseInt(n[0],10),cryptoSuite:n[1],keyParams:n[2],sessionParams:n.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r `},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const n=t.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,n){return e.matchPrefix(t+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,n){const r=e.matchPrefix(t+n,"a=ice-ufrag:")[0],s=e.matchPrefix(t+n,"a=ice-pwd:")[0];return r&&s?{usernameFragment:r.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let n="a=ice-ufrag:"+t.usernameFragment+`\r a=ice-pwd:`+t.password+`\r `;return t.iceLite&&(n+=`a=ice-lite\r `),n},e.parseRtpParameters=function(t){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");n.profile=s[2];for(let o=3;o{n.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return n.codecs.forEach(o=>{a.forEach(c=>{o.rtcpFeedback.find(u=>u.type===c.type&&u.parameter===c.parameter)||o.rtcpFeedback.push(c)})}),n},e.writeRtpDescription=function(t,n){let r="";r+="m="+t+" ",r+=n.codecs.length>0?"9":"0",r+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=n.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r `,r+=`c=IN IP4 0.0.0.0\r `,r+=`a=rtcp:9 IN IP4 0.0.0.0\r `,n.codecs.forEach(a=>{r+=e.writeRtpMap(a),r+=e.writeFmtp(a),r+=e.writeRtcpFb(a)});let s=0;return n.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(r+="a=maxptime:"+s+`\r `),n.headerExtensions&&n.headerExtensions.forEach(a=>{r+=e.writeExtmap(a)}),r},e.parseRtpEncodingParameters=function(t){const n=[],r=e.parseRtpParameters(t),s=r.fecMechanisms.indexOf("RED")!==-1,a=r.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(m=>e.parseSsrcMedia(m)).filter(m=>m.attribute==="cname"),c=o.length>0&&o[0].ssrc;let d;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(m=>m.substring(17).split(" ").map(k=>parseInt(k,10)));u.length>0&&u[0].length>1&&u[0][0]===c&&(d=u[0][1]),r.codecs.forEach(m=>{if(m.name.toUpperCase()==="RTX"&&m.parameters.apt){let g={ssrc:c,codecPayloadType:parseInt(m.parameters.apt,10)};c&&d&&(g.rtx={ssrc:d}),n.push(g),s&&(g=JSON.parse(JSON.stringify(g)),g.fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},n.push(g))}}),n.length===0&&c&&n.push({ssrc:c});let h=e.matchPrefix(t,"b=");return h.length&&(h[0].indexOf("b=TIAS:")===0?h=parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?h=parseInt(h[0].substring(5),10)*1e3*.95-50*40*8:h=void 0,n.forEach(m=>{m.maxBitrate=h})),n},e.parseRtcpParameters=function(t){const n={},r=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=s.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r `),t.mux&&(n+=`a=rtcp-mux\r `),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r `),n},e.parseMsid=function(t){let n;const r=e.matchPrefix(t,"a=msid:");if(r.length===1)return n=r[0].substring(7).split(" "),{stream:n[0],track:n[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return n=s[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){const n=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:");let s;r.length>0&&(s=parseInt(r[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const c=o[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,n){let r=[];return t.protocol!=="DTLS/SCTP"?r=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r `,`c=IN IP4 0.0.0.0\r `,"a=sctp-port:"+n.port+`\r `]:r=["m="+t.kind+" 9 "+t.protocol+" "+n.port+`\r `,`c=IN IP4 0.0.0.0\r `,"a=sctpmap:"+n.port+" "+n.protocol+` 65535\r `],n.maxMessageSize!==void 0&&r.push("a=max-message-size:"+n.maxMessageSize+`\r `),r.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,n,r){let s;const a=n!==void 0?n:2;return t?s=t:s=e.generateSessionId(),`v=0\r o=`+(r||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r s=-\r t=0 0\r `},e.getDirection=function(t,n){const r=e.splitLines(t);for(let s=0;s(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function nn(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||Ot(i,"icecandidate",e=>{if(e.candidate){const t=Ft.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function bi(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const c=Ft.splitSections(o.sdp);return c.shift(),c.some(d=>{const u=Ft.parseMLine(d);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},n=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!==d?-1:d},r=function(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},s=function(o,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const u=Ft.matchPrefix(o.sdp,"a=max-message-size:");return u.length>0?d=parseInt(u[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},a=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=n(arguments[0]),d=r(c),u=s(arguments[0],c);let h;d===0&&u===0?h=Number.POSITIVE_INFINITY:d===0||u===0?h=Math.max(d,u):h=Math.min(d,u);const m={};Object.defineProperty(m,"maxMessageSize",{get(){return h}}),this._sctp=m}return a.apply(this,arguments)}}function Ti(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,r){const s=n.send;n.send=function(){const o=arguments[0],c=o.length||o.size||o.byteLength;if(n.readyState==="open"&&r.sctp&&c>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return s.apply(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const r=t.apply(this,arguments);return e(r,this),r},Ot(i,"datachannel",n=>(e(n.channel,n.target),n))}function rn(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",r);s.dispatchEvent(a)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function sn(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(` a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(` `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(` `);i.RTCSessionDescription&&r instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return t.apply(this,arguments)}}function Si(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Ci(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var Ja=Object.freeze({__proto__:null,removeExtmapAllowMixed:sn,shimAddIceCandidateNullOrEmpty:Si,shimConnectionState:rn,shimMaxMessageSize:bi,shimParameterlessSetLocalDescription:Ci,shimRTCIceCandidate:ki,shimRTCIceCandidateRelayProtocol:nn,shimSendThrowTypeError:Ti});function Va(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Fr,n=xa(i),r={browserDetails:n,commonShim:Ja,extractVersion:yi,disableLog:La,disableWarnings:_a,sdp:Ba};switch(n.browser){case"chrome":if(!Fn||!en||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),r;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),r;t("adapter.js shimming chrome."),r.browserShim=Fn,Si(i,n),Ci(i),Jr(i,n),Vr(i),en(i,n),qr(i),Hr(i,n),jr(i),Gr(i),Wr(i),zr(i,n),ki(i),nn(i),rn(i),bi(i,n),Ti(i),sn(i,n);break;case"firefox":if(!Bn||!tn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),r;t("adapter.js shimming firefox."),r.browserShim=Bn,Si(i,n),Ci(i),Yr(i,n),tn(i,n),Qr(i),Zr(i),Xr(i),$r(i),es(i),ts(i),is(i),ns(i),rs(i),ki(i),rn(i),bi(i,n),Ti(i);break;case"safari":if(!Jn||!e.shimSafari)return t("Safari shim is not included in this adapter release."),r;t("adapter.js shimming safari."),r.browserShim=Jn,Si(i,n),Ci(i),us(i),hs(i),os(i),ss(i),as(i),ls(i),cs(i),fs(i),ki(i),nn(i),bi(i,n),Ti(i),sn(i,n);break;default:t("Unsupported browser!");break}return r}Va({window:typeof window>"u"?void 0:window});const qa=10,hi="lk_e2ee",ja="LKFrameEncryptionKey",Ga={sharedKey:!1,ratchetSalt:ja,ratchetWindowSize:8,failureTolerance:qa};var St;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(St||(St={}));var Vn;(function(i){i.KeyRatcheted="keyRatcheted"})(Vn||(Vn={}));var bt;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(bt||(bt={}));var qn;(function(i){i.Error="cryptorError"})(qn||(qn={}));function Wa(){return Ka()||an()}function an(){return typeof window.RTCRtpScriptTransform<"u"}function Ka(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class lc extends Fe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n)=>{f.debug("key ratcheted event received",{material:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Ga),e),this.on(St.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const r={key:e,participantIdentity:t,keyIndex:n};this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),r),this.emit(St.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(St.RatchetRequest,e,t)}}class Wt extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class _ extends Wt{constructor(e,t,n){super(1,e),this.status=n,this.reason=t}}class yn extends Wt{constructor(e){super(21,e??"device is unsupported")}}class be extends Wt{constructor(e){super(20,e??"track is invalid")}}class Ha extends Wt{constructor(e){super(10,e??"unsupported server")}}class J extends Wt{constructor(e){super(12,e??"unexpected connection state")}}class on extends Wt{constructor(e){super(13,e??"unable to negotiate")}}var Pi;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(Pi||(Pi={}));(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(Pi||(Pi={}));var T;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.StateChanged="connectionStateChanged",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged"})(T||(T={}));var E;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded"})(E||(E={}));var P;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished"})(P||(P={}));var S;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed"})(S||(S={}));function kn(i,e,t){var n,r,s;e===void 0&&(e=50),t===void 0&&(t={});var a=(n=t.isImmediate)!=null&&n,o=(r=t.callback)!=null&&r,c=t.maxWait,d=Date.now(),u=[];function h(){if(c!==void 0){var g=Date.now()-d;if(g+e>=c)return c-g}return e}var m=function(){var g=[].slice.call(arguments),k=this;return new Promise(function(b,w){var R=a&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,d=Date.now(),!a){var B=i.apply(k,g);o&&o(B),u.forEach(function(L){return(0,L.resolve)(B)}),u=[]}},h()),R){var I=i.apply(k,g);return o&&o(I),b(I)}u.push({resolve:b,reject:w})})};return m.cancel=function(g){s!==void 0&&clearTimeout(s),u.forEach(function(k){return(0,k.reject)(g)}),u=[]},m}const za=/version\/(\d+(\.?_?\d+)+)/i;let xi;function Ct(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof i>"u"&&typeof navigator>"u")return;const t=(i??navigator.userAgent).toLowerCase();if(xi===void 0||e){const n=Ya.find(r=>{let{test:s}=r;return s.test(t)});xi=n==null?void 0:n.describe(t)}return xi}const Ya=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:Ui(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:Ui(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:Ui(za,i),os:i.includes("mobile/")?"iOS":"macOS"}}}];function Ui(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}var Qa="1.15.5";const Xa=Qa,$a=11;class H{}H.setTimeout=function(){return setTimeout(...arguments)};H.setInterval=function(){return setInterval(...arguments)};H.clearTimeout=function(){return clearTimeout(...arguments)};H.clearInterval=function(){return clearInterval(...arguments)};class A{constructor(e,t,n,r,s){this.width=e,this.height=t,this.encoding={maxBitrate:n,maxFramerate:r,priority:s}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}const Za=["vp8","h264"],gs=["vp8","h264","vp9","av1"];function eo(i){return!!Za.find(e=>e===i)}var wi;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:2e4},i.music={maxBitrate:32e3},i.musicStereo={maxBitrate:48e3},i.musicHighQuality={maxBitrate:64e3},i.musicHighQualityStereo={maxBitrate:96e3}})(wi||(wi={}));const oi={h90:new A(160,90,9e4,20),h180:new A(320,180,16e4,20),h216:new A(384,216,18e4,20),h360:new A(640,360,45e4,20),h540:new A(960,540,8e5,25),h720:new A(1280,720,17e5,30),h1080:new A(1920,1080,3e6,30),h1440:new A(2560,1440,5e6,30),h2160:new A(3840,2160,8e6,30)},cn={h120:new A(160,120,7e4,20),h180:new A(240,180,125e3,20),h240:new A(320,240,14e4,20),h360:new A(480,360,33e4,20),h480:new A(640,480,5e5,20),h540:new A(720,540,6e5,25),h720:new A(960,720,13e5,30),h1080:new A(1440,1080,23e5,30),h1440:new A(1920,1440,38e5,30)},vs={h360fps3:new A(640,360,2e5,3,"medium"),h720fps5:new A(1280,720,4e5,5,"medium"),h720fps15:new A(1280,720,15e5,15,"medium"),h720fps30:new A(1280,720,2e6,30,"medium"),h1080fps15:new A(1920,1080,25e5,15,"medium"),h1080fps30:new A(1920,1080,4e6,30,"medium")};var Y;(function(i){i[i.PUBLISHER=0]="PUBLISHER",i[i.SUBSCRIBER=1]="SUBSCRIBER"})(Y||(Y={}));l.util.setEnumType(Y,"livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]);var It;(function(i){i[i.ACTIVE=0]="ACTIVE",i[i.PAUSED=1]="PAUSED"})(It||(It={}));l.util.setEnumType(It,"livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);var Ri;(function(i){i[i.UDP=0]="UDP",i[i.TCP=1]="TCP",i[i.TLS=2]="TLS"})(Ri||(Ri={}));l.util.setEnumType(Ri,"livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]);class Ye extends C{constructor(e){super(),this.message={case:void 0},l.util.initPartial(e,this)}static fromBinary(e,t){return new Ye().fromBinary(e,t)}static fromJson(e,t){return new Ye().fromJson(e,t)}static fromJsonString(e,t){return new Ye().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Ye,e,t)}}Ye.runtime=l;Ye.typeName="livekit.SignalRequest";Ye.fields=l.util.newFieldList(()=>[{no:1,name:"offer",kind:"message",T:Z,oneof:"message"},{no:2,name:"answer",kind:"message",T:Z,oneof:"message"},{no:3,name:"trickle",kind:"message",T:fe,oneof:"message"},{no:4,name:"add_track",kind:"message",T:he,oneof:"message"},{no:5,name:"mute",kind:"message",T:me,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ae,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ne,oneof:"message"},{no:8,name:"leave",kind:"message",T:oe,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:De,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Le,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:_e,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Q,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Oe,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ue,oneof:"message"}]);class Ie extends C{constructor(e){super(),this.message={case:void 0},l.util.initPartial(e,this)}static fromBinary(e,t){return new Ie().fromBinary(e,t)}static fromJson(e,t){return new Ie().fromJson(e,t)}static fromJsonString(e,t){return new Ie().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Ie,e,t)}}Ie.runtime=l;Ie.typeName="livekit.SignalResponse";Ie.fields=l.util.newFieldList(()=>[{no:1,name:"join",kind:"message",T:Qe,oneof:"message"},{no:2,name:"answer",kind:"message",T:Z,oneof:"message"},{no:3,name:"offer",kind:"message",T:Z,oneof:"message"},{no:4,name:"trickle",kind:"message",T:fe,oneof:"message"},{no:5,name:"update",kind:"message",T:Ze,oneof:"message"},{no:6,name:"track_published",kind:"message",T:pe,oneof:"message"},{no:8,name:"leave",kind:"message",T:oe,oneof:"message"},{no:9,name:"mute",kind:"message",T:me,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:et,oneof:"message"},{no:11,name:"room_update",kind:"message",T:tt,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:nt,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:st,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ot,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ct,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:$e,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Xe,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:dt,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:lt,oneof:"message"}]);class le extends C{constructor(e){super(),this.codec="",this.cid="",l.util.initPartial(e,this)}static fromBinary(e,t){return new le().fromBinary(e,t)}static fromJson(e,t){return new le().fromJson(e,t)}static fromJsonString(e,t){return new le().fromJsonString(e,t)}static equals(e,t){return l.util.equals(le,e,t)}}le.runtime=l;le.typeName="livekit.SimulcastCodec";le.fields=l.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]);class he extends C{constructor(e){super(),this.cid="",this.name="",this.type=z.AUDIO,this.width=0,this.height=0,this.muted=!1,this.disableDtx=!1,this.source=F.UNKNOWN,this.layers=[],this.simulcastCodecs=[],this.sid="",this.stereo=!1,this.disableRed=!1,this.encryption=K.NONE,this.stream="",l.util.initPartial(e,this)}static fromBinary(e,t){return new he().fromBinary(e,t)}static fromJson(e,t){return new he().fromJson(e,t)}static fromJsonString(e,t){return new he().fromJsonString(e,t)}static equals(e,t){return l.util.equals(he,e,t)}}he.runtime=l;he.typeName="livekit.AddTrackRequest";he.fields=l.util.newFieldList(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:l.getEnumType(z)},{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:l.getEnumType(F)},{no:9,name:"layers",kind:"message",T:$,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:le,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:l.getEnumType(K)},{no:15,name:"stream",kind:"scalar",T:9}]);class fe extends C{constructor(e){super(),this.candidateInit="",this.target=Y.PUBLISHER,l.util.initPartial(e,this)}static fromBinary(e,t){return new fe().fromBinary(e,t)}static fromJson(e,t){return new fe().fromJson(e,t)}static fromJsonString(e,t){return new fe().fromJsonString(e,t)}static equals(e,t){return l.util.equals(fe,e,t)}}fe.runtime=l;fe.typeName="livekit.TrickleRequest";fe.fields=l.util.newFieldList(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:l.getEnumType(Y)}]);class me extends C{constructor(e){super(),this.sid="",this.muted=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new me().fromBinary(e,t)}static fromJson(e,t){return new me().fromJson(e,t)}static fromJsonString(e,t){return new me().fromJsonString(e,t)}static equals(e,t){return l.util.equals(me,e,t)}}me.runtime=l;me.typeName="livekit.MuteTrackRequest";me.fields=l.util.newFieldList(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]);class Qe extends C{constructor(e){super(),this.otherParticipants=[],this.serverVersion="",this.iceServers=[],this.subscriberPrimary=!1,this.alternativeUrl="",this.serverRegion="",this.pingTimeout=0,this.pingInterval=0,this.sifTrailer=new Uint8Array(0),l.util.initPartial(e,this)}static fromBinary(e,t){return new Qe().fromBinary(e,t)}static fromJson(e,t){return new Qe().fromJson(e,t)}static fromJsonString(e,t){return new Qe().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Qe,e,t)}}Qe.runtime=l;Qe.typeName="livekit.JoinResponse";Qe.fields=l.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Gt},{no:2,name:"participant",kind:"message",T:se},{no:3,name:"other_participants",kind:"message",T:se,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Me,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:Pe},{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:Ke},{no:13,name:"sif_trailer",kind:"scalar",T:12}]);class Xe extends C{constructor(e){super(),this.iceServers=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Xe().fromBinary(e,t)}static fromJson(e,t){return new Xe().fromJson(e,t)}static fromJsonString(e,t){return new Xe().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Xe,e,t)}}Xe.runtime=l;Xe.typeName="livekit.ReconnectResponse";Xe.fields=l.util.newFieldList(()=>[{no:1,name:"ice_servers",kind:"message",T:Me,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Pe}]);class pe extends C{constructor(e){super(),this.cid="",l.util.initPartial(e,this)}static fromBinary(e,t){return new pe().fromBinary(e,t)}static fromJson(e,t){return new pe().fromJson(e,t)}static fromJsonString(e,t){return new pe().fromJsonString(e,t)}static equals(e,t){return l.util.equals(pe,e,t)}}pe.runtime=l;pe.typeName="livekit.TrackPublishedResponse";pe.fields=l.util.newFieldList(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ie}]);class $e extends C{constructor(e){super(),this.trackSid="",l.util.initPartial(e,this)}static fromBinary(e,t){return new $e().fromBinary(e,t)}static fromJson(e,t){return new $e().fromJson(e,t)}static fromJsonString(e,t){return new $e().fromJsonString(e,t)}static equals(e,t){return l.util.equals($e,e,t)}}$e.runtime=l;$e.typeName="livekit.TrackUnpublishedResponse";$e.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);class Z extends C{constructor(e){super(),this.type="",this.sdp="",l.util.initPartial(e,this)}static fromBinary(e,t){return new Z().fromBinary(e,t)}static fromJson(e,t){return new Z().fromJson(e,t)}static fromJsonString(e,t){return new Z().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Z,e,t)}}Z.runtime=l;Z.typeName="livekit.SessionDescription";Z.fields=l.util.newFieldList(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]);class Ze extends C{constructor(e){super(),this.participants=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Ze().fromBinary(e,t)}static fromJson(e,t){return new Ze().fromJson(e,t)}static fromJsonString(e,t){return new Ze().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Ze,e,t)}}Ze.runtime=l;Ze.typeName="livekit.ParticipantUpdate";Ze.fields=l.util.newFieldList(()=>[{no:1,name:"participants",kind:"message",T:se,repeated:!0}]);class ae extends C{constructor(e){super(),this.trackSids=[],this.subscribe=!1,this.participantTracks=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new ae().fromBinary(e,t)}static fromJson(e,t){return new ae().fromJson(e,t)}static fromJsonString(e,t){return new ae().fromJsonString(e,t)}static equals(e,t){return l.util.equals(ae,e,t)}}ae.runtime=l;ae.typeName="livekit.UpdateSubscription";ae.fields=l.util.newFieldList(()=>[{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:Ee,repeated:!0}]);class Ne extends C{constructor(e){super(),this.trackSids=[],this.disabled=!1,this.quality=q.LOW,this.width=0,this.height=0,this.fps=0,this.priority=0,l.util.initPartial(e,this)}static fromBinary(e,t){return new Ne().fromBinary(e,t)}static fromJson(e,t){return new Ne().fromJson(e,t)}static fromJsonString(e,t){return new Ne().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Ne,e,t)}}Ne.runtime=l;Ne.typeName="livekit.UpdateTrackSettings";Ne.fields=l.util.newFieldList(()=>[{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:l.getEnumType(q)},{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}]);class oe extends C{constructor(e){super(),this.canReconnect=!1,this.reason=ht.UNKNOWN_REASON,l.util.initPartial(e,this)}static fromBinary(e,t){return new oe().fromBinary(e,t)}static fromJson(e,t){return new oe().fromJson(e,t)}static fromJsonString(e,t){return new oe().fromJsonString(e,t)}static equals(e,t){return l.util.equals(oe,e,t)}}oe.runtime=l;oe.typeName="livekit.LeaveRequest";oe.fields=l.util.newFieldList(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:l.getEnumType(ht)}]);class De extends C{constructor(e){super(),this.trackSid="",this.layers=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new De().fromBinary(e,t)}static fromJson(e,t){return new De().fromJson(e,t)}static fromJsonString(e,t){return new De().fromJsonString(e,t)}static equals(e,t){return l.util.equals(De,e,t)}}De.runtime=l;De.typeName="livekit.UpdateVideoLayers";De.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:$,repeated:!0}]);class Oe extends C{constructor(e){super(),this.metadata="",this.name="",l.util.initPartial(e,this)}static fromBinary(e,t){return new Oe().fromBinary(e,t)}static fromJson(e,t){return new Oe().fromJson(e,t)}static fromJsonString(e,t){return new Oe().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Oe,e,t)}}Oe.runtime=l;Oe.typeName="livekit.UpdateParticipantMetadata";Oe.fields=l.util.newFieldList(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}]);class Me extends C{constructor(e){super(),this.urls=[],this.username="",this.credential="",l.util.initPartial(e,this)}static fromBinary(e,t){return new Me().fromBinary(e,t)}static fromJson(e,t){return new Me().fromJson(e,t)}static fromJsonString(e,t){return new Me().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Me,e,t)}}Me.runtime=l;Me.typeName="livekit.ICEServer";Me.fields=l.util.newFieldList(()=>[{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}]);class et extends C{constructor(e){super(),this.speakers=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new et().fromBinary(e,t)}static fromJson(e,t){return new et().fromJson(e,t)}static fromJsonString(e,t){return new et().fromJsonString(e,t)}static equals(e,t){return l.util.equals(et,e,t)}}et.runtime=l;et.typeName="livekit.SpeakersChanged";et.fields=l.util.newFieldList(()=>[{no:1,name:"speakers",kind:"message",T:Se,repeated:!0}]);class tt extends C{constructor(e){super(),l.util.initPartial(e,this)}static fromBinary(e,t){return new tt().fromBinary(e,t)}static fromJson(e,t){return new tt().fromJson(e,t)}static fromJsonString(e,t){return new tt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(tt,e,t)}}tt.runtime=l;tt.typeName="livekit.RoomUpdate";tt.fields=l.util.newFieldList(()=>[{no:1,name:"room",kind:"message",T:Gt}]);class it extends C{constructor(e){super(),this.participantSid="",this.quality=qe.POOR,this.score=0,l.util.initPartial(e,this)}static fromBinary(e,t){return new it().fromBinary(e,t)}static fromJson(e,t){return new it().fromJson(e,t)}static fromJsonString(e,t){return new it().fromJsonString(e,t)}static equals(e,t){return l.util.equals(it,e,t)}}it.runtime=l;it.typeName="livekit.ConnectionQualityInfo";it.fields=l.util.newFieldList(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:l.getEnumType(qe)},{no:3,name:"score",kind:"scalar",T:2}]);class nt extends C{constructor(e){super(),this.updates=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new nt().fromBinary(e,t)}static fromJson(e,t){return new nt().fromJson(e,t)}static fromJsonString(e,t){return new nt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(nt,e,t)}}nt.runtime=l;nt.typeName="livekit.ConnectionQualityUpdate";nt.fields=l.util.newFieldList(()=>[{no:1,name:"updates",kind:"message",T:it,repeated:!0}]);class rt extends C{constructor(e){super(),this.participantSid="",this.trackSid="",this.state=It.ACTIVE,l.util.initPartial(e,this)}static fromBinary(e,t){return new rt().fromBinary(e,t)}static fromJson(e,t){return new rt().fromJson(e,t)}static fromJsonString(e,t){return new rt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(rt,e,t)}}rt.runtime=l;rt.typeName="livekit.StreamStateInfo";rt.fields=l.util.newFieldList(()=>[{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:l.getEnumType(It)}]);class st extends C{constructor(e){super(),this.streamStates=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new st().fromBinary(e,t)}static fromJson(e,t){return new st().fromJson(e,t)}static fromJsonString(e,t){return new st().fromJsonString(e,t)}static equals(e,t){return l.util.equals(st,e,t)}}st.runtime=l;st.typeName="livekit.StreamStateUpdate";st.fields=l.util.newFieldList(()=>[{no:1,name:"stream_states",kind:"message",T:rt,repeated:!0}]);class ge extends C{constructor(e){super(),this.quality=q.LOW,this.enabled=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new ge().fromBinary(e,t)}static fromJson(e,t){return new ge().fromJson(e,t)}static fromJsonString(e,t){return new ge().fromJsonString(e,t)}static equals(e,t){return l.util.equals(ge,e,t)}}ge.runtime=l;ge.typeName="livekit.SubscribedQuality";ge.fields=l.util.newFieldList(()=>[{no:1,name:"quality",kind:"enum",T:l.getEnumType(q)},{no:2,name:"enabled",kind:"scalar",T:8}]);class at extends C{constructor(e){super(),this.codec="",this.qualities=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new at().fromBinary(e,t)}static fromJson(e,t){return new at().fromJson(e,t)}static fromJsonString(e,t){return new at().fromJsonString(e,t)}static equals(e,t){return l.util.equals(at,e,t)}}at.runtime=l;at.typeName="livekit.SubscribedCodec";at.fields=l.util.newFieldList(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ge,repeated:!0}]);class ot extends C{constructor(e){super(),this.trackSid="",this.subscribedQualities=[],this.subscribedCodecs=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new ot().fromBinary(e,t)}static fromJson(e,t){return new ot().fromJson(e,t)}static fromJsonString(e,t){return new ot().fromJsonString(e,t)}static equals(e,t){return l.util.equals(ot,e,t)}}ot.runtime=l;ot.typeName="livekit.SubscribedQualityUpdate";ot.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ge,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:at,repeated:!0}]);class Ae extends C{constructor(e){super(),this.participantSid="",this.allTracks=!1,this.trackSids=[],this.participantIdentity="",l.util.initPartial(e,this)}static fromBinary(e,t){return new Ae().fromBinary(e,t)}static fromJson(e,t){return new Ae().fromJson(e,t)}static fromJsonString(e,t){return new Ae().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Ae,e,t)}}Ae.runtime=l;Ae.typeName="livekit.TrackPermission";Ae.fields=l.util.newFieldList(()=>[{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}]);class Le extends C{constructor(e){super(),this.allParticipants=!1,this.trackPermissions=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Le().fromBinary(e,t)}static fromJson(e,t){return new Le().fromJson(e,t)}static fromJsonString(e,t){return new Le().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Le,e,t)}}Le.runtime=l;Le.typeName="livekit.SubscriptionPermission";Le.fields=l.util.newFieldList(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Ae,repeated:!0}]);class ct extends C{constructor(e){super(),this.participantSid="",this.trackSid="",this.allowed=!1,l.util.initPartial(e,this)}static fromBinary(e,t){return new ct().fromBinary(e,t)}static fromJson(e,t){return new ct().fromJson(e,t)}static fromJsonString(e,t){return new ct().fromJsonString(e,t)}static equals(e,t){return l.util.equals(ct,e,t)}}ct.runtime=l;ct.typeName="livekit.SubscriptionPermissionUpdate";ct.fields=l.util.newFieldList(()=>[{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}]);class _e extends C{constructor(e){super(),this.publishTracks=[],this.dataChannels=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new _e().fromBinary(e,t)}static fromJson(e,t){return new _e().fromJson(e,t)}static fromJsonString(e,t){return new _e().fromJsonString(e,t)}static equals(e,t){return l.util.equals(_e,e,t)}}_e.runtime=l;_e.typeName="livekit.SyncState";_e.fields=l.util.newFieldList(()=>[{no:1,name:"answer",kind:"message",T:Z},{no:2,name:"subscription",kind:"message",T:ae},{no:3,name:"publish_tracks",kind:"message",T:pe,repeated:!0},{no:4,name:"data_channels",kind:"message",T:xe,repeated:!0},{no:5,name:"offer",kind:"message",T:Z}]);class xe extends C{constructor(e){super(),this.label="",this.id=0,this.target=Y.PUBLISHER,l.util.initPartial(e,this)}static fromBinary(e,t){return new xe().fromBinary(e,t)}static fromJson(e,t){return new xe().fromJson(e,t)}static fromJsonString(e,t){return new xe().fromJsonString(e,t)}static equals(e,t){return l.util.equals(xe,e,t)}}xe.runtime=l;xe.typeName="livekit.DataChannelInfo";xe.fields=l.util.newFieldList(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:l.getEnumType(Y)}]);class Q extends C{constructor(e){super(),this.scenario={case:void 0},l.util.initPartial(e,this)}static fromBinary(e,t){return new Q().fromBinary(e,t)}static fromJson(e,t){return new Q().fromJson(e,t)}static fromJsonString(e,t){return new Q().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Q,e,t)}}Q.runtime=l;Q.typeName="livekit.SimulateScenario";Q.fields=l.util.newFieldList(()=>[{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:l.getEnumType(Ri),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"}]);class Ue extends C{constructor(e){super(),this.timestamp=N.zero,this.rtt=N.zero,l.util.initPartial(e,this)}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 l.util.equals(Ue,e,t)}}Ue.runtime=l;Ue.typeName="livekit.Ping";Ue.fields=l.util.newFieldList(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]);class dt extends C{constructor(e){super(),this.lastPingTimestamp=N.zero,this.timestamp=N.zero,l.util.initPartial(e,this)}static fromBinary(e,t){return new dt().fromBinary(e,t)}static fromJson(e,t){return new dt().fromJson(e,t)}static fromJsonString(e,t){return new dt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(dt,e,t)}}dt.runtime=l;dt.typeName="livekit.Pong";dt.fields=l.util.newFieldList(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]);class Tt extends C{constructor(e){super(),this.regions=[],l.util.initPartial(e,this)}static fromBinary(e,t){return new Tt().fromBinary(e,t)}static fromJson(e,t){return new Tt().fromJson(e,t)}static fromJsonString(e,t){return new Tt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(Tt,e,t)}}Tt.runtime=l;Tt.typeName="livekit.RegionSettings";Tt.fields=l.util.newFieldList(()=>[{no:1,name:"regions",kind:"message",T:ut,repeated:!0}]);class ut extends C{constructor(e){super(),this.region="",this.url="",this.distance=N.zero,l.util.initPartial(e,this)}static fromBinary(e,t){return new ut().fromBinary(e,t)}static fromJson(e,t){return new ut().fromJson(e,t)}static fromJsonString(e,t){return new ut().fromJsonString(e,t)}static equals(e,t){return l.util.equals(ut,e,t)}}ut.runtime=l;ut.typeName="livekit.RegionInfo";ut.fields=l.util.newFieldList(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]);class lt extends C{constructor(e){super(),this.trackSid="",this.err=ai.SE_UNKNOWN,l.util.initPartial(e,this)}static fromBinary(e,t){return new lt().fromBinary(e,t)}static fromJson(e,t){return new lt().fromJson(e,t)}static fromJsonString(e,t){return new lt().fromJsonString(e,t)}static equals(e,t){return l.util.equals(lt,e,t)}}lt.runtime=l;lt.typeName="livekit.SubscriptionResponse";lt.fields=l.util.newFieldList(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:l.getEnumType(ai)}]);function to(i){if(!(typeof i>"u"))return typeof structuredClone=="function"?structuredClone(i):JSON.parse(JSON.stringify(i))}const io=5e3,Qt=[];class y extends Fe.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=y.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),io):this.handleAppVisibilityChanged()},this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=y.Source.Unknown}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===y.Kind.Video&&(t="video"),this.attachedElements.length===0&&y.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Qt.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&Qt.splice(Qt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),xt(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),r=n.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?S.AudioPlaybackStarted:S.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?S.AudioPlaybackFailed:S.VideoPlaybackFailed,s):s.name==="AbortError"?f.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):f.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&n.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(S.ElementAttached,e),e}detach(e){try{if(e){Bt(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(S.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Bt(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(S.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Qt.forEach(n=>{n.parentElement||(t=!1)}),t&&Qt.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden"})}addAppVisibilityListener(){ne()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){ne()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function xt(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(r=>{t.removeTrack(r)}),t.addTrack(i)),(!Nt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Nt()||jt())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Bt(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function r(d){switch(d){case e.Audio:return z.AUDIO;case e.Video:return z.VIDEO;default:return z.DATA}}i.kindToProto=r;function s(d){switch(d){case z.AUDIO:return e.Audio;case z.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=s;function a(d){switch(d){case t.Camera:return F.CAMERA;case t.Microphone:return F.MICROPHONE;case t.ScreenShare:return F.SCREEN_SHARE;case t.ScreenShareAudio:return F.SCREEN_SHARE_AUDIO;default:return F.UNKNOWN}}i.sourceToProto=a;function o(d){switch(d){case F.CAMERA:return t.Camera;case F.MICROPHONE:return t.Microphone;case F.SCREEN_SHARE:return t.ScreenShare;case F.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function c(d){switch(d){case It.ACTIVE:return n.Active;case It.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(y||(y={}));function ys(i,e,t){var n;const r=(n=to(i))!==null&&n!==void 0?n:{};return r.audio===!0&&(r.audio={}),r.video===!0&&(r.video={}),r.audio&&dn(r.audio,e),r.video&&dn(r.video,t),r}function dn(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Mi(i){const e={};if(i.video)if(typeof i.video=="object"){const t={},n=t,r=i.video;Object.keys(r).forEach(s=>{switch(s){case"resolution":dn(n,r.resolution);break;default:n[s]=r[s]}}),e.video=t}else e.video=i.video;else e.video=!1;return i.audio?typeof i.audio=="object"?e.audio=i.audio:e.audio=!0:e.audio=!1,e}function no(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return p(this,void 0,void 0,function*(){const t=ks();if(t){const n=t.createAnalyser();n.fftSize=2048;const r=n.frequencyBinCount,s=new Uint8Array(r);t.createMediaStreamSource(new MediaStream([i.mediaStreamTrack])).connect(n),yield ft(e),n.getByteTimeDomainData(s);const o=s.some(c=>c!==128&&c!==0);return t.close(),!o}return!1})}function ks(){const i=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(i)return new i({latencyHint:"interactive"})}function ro(i){return i===y.Source.Microphone?"audioinput":i===y.Source.Camera?"videoinput":void 0}function so(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&(n=typeof n=="boolean"?{}:n,Nt()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio}}function bs(i){const e=i.split("/")[1].toLowerCase();if(!gs.includes(e))throw Error("Video codec not supported: ".concat(e));return e}function ao(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new pe({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}const oo="|",jn="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function co(i){const e=i.split(oo);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function ft(i){return p(this,void 0,void 0,function*(){return new Promise(e=>H.setTimeout(e,i))})}function Gn(){return"addTransceiver"in RTCPeerConnection.prototype}function Wn(){return"addTrack"in RTCPeerConnection.prototype}function uo(){if(!("getCapabilities"in RTCRtpSender)||Nt())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function lo(){if(!("getCapabilities"in RTCRtpSender)||jt())return!1;if(Nt()){const t=Ct();if(t!=null&&t.version&&bn(t.version,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function ii(i){return i==="av1"||i==="vp9"}function un(i){return document?(i||(i=document.createElement("audio")),"setSinkId"in i):!1}const ho={Chrome:"100",Safari:"15",Firefox:"100"};function fo(i){if(!ne()||!("setCodecPreferences"in i))return!1;const e=Ct();if(!(e!=null&&e.name)||!e.version)return!1;const t=ho[e.name];return t?bn(e.version,t)>=0:!1}function jt(){var i;return((i=Ct())===null||i===void 0?void 0:i.name)==="Firefox"}function mo(){var i;return((i=Ct())===null||i===void 0?void 0:i.name)==="Chrome"}function Nt(){var i;return((i=Ct())===null||i===void 0?void 0:i.name)==="Safari"}function Ts(){return ne()?/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function ne(){return typeof document<"u"}function Dt(){return navigator.product=="ReactNative"}function ln(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function Ss(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Cs(){if(!Dt())return;let i=Ss();if(i)return i.platform}function Kn(){if(ne())return window.devicePixelRatio;if(Dt()){let i=Ss();if(i)return i.devicePixelRatio}return 1}function bn(i,e){const t=i.split("."),n=e.split("."),r=Math.min(t.length,n.length);for(let s=0;so)return 1;if(a(Fi||(Fi=new ResizeObserver(po)),Fi);let Bi=null;const zn=()=>(Bi||(Bi=new IntersectionObserver(go,{root:null,rootMargin:"0px"})),Bi);function vo(){var i;const e=new He({sdk:qt.JS,protocol:$a,version:Xa});return Dt()&&(e.os=(i=Cs())!==null&&i!==void 0?i:""),e}function Yn(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=i,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(i/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const a=r.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Xt;function Ji(){if(!Xt){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[Xt]=n.stream.getAudioTracks(),!Xt)throw Error("Could not get empty media stream audio track");Xt.enabled=!1}return Xt.clone()}class Es{constructor(e,t){this.onFinally=t,this.promise=new Promise((n,r)=>p(this,void 0,void 0,function*(){this.resolve=n,this.reject=r,e&&(yield e(n,r))})).finally(()=>{var n;return(n=this.onFinally)===null||n===void 0?void 0:n.call(this)})}}class ve{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}}function yo(i){return gs.includes(i)}function Pt(i){if(typeof i=="string")return i;if(Array.isArray(i))return i[0];if(i.exact)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function ko(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Qn(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}const Xn="default";class X{static getInstance(){return this.instance===void 0&&(this.instance=new X),this.instance}getDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var n;return p(this,void 0,void 0,function*(){if(((n=X.userMediaPromiseMap)===null||n===void 0?void 0:n.size)>0){f.debug("awaiting getUserMedia promise");try{e?yield X.userMediaPromiseMap.get(e):yield Promise.all(X.userMediaPromiseMap.values())}catch{f.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(t&&!(Nt()&&this.hasDeviceInUse(e))&&(r.length===0||r.some(a=>{const o=a.label==="",c=e?a.kind===e:!0;return o&&c}))){const a={video:e!=="audioinput"&&e!=="audiooutput",audio:e!=="videoinput"},o=yield navigator.mediaDevices.getUserMedia(a);r=yield navigator.mediaDevices.enumerateDevices(),o.getTracks().forEach(c=>{c.stop()})}return e&&(r=r.filter(s=>s.kind===e)),r})}normalizeDeviceId(e,t,n){return p(this,void 0,void 0,function*(){if(t!==Xn)return t;const s=(yield this.getDevices(e)).find(a=>a.groupId===n&&a.deviceId!==Xn);return s==null?void 0:s.deviceId})}hasDeviceInUse(e){return e?X.userMediaPromiseMap.has(e):X.userMediaPromiseMap.size>0}}X.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];X.userMediaPromiseMap=new Map;const bo=1e3;class ci extends y{get constraints(){return this._constraints}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;super(e,t),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>f.debug("track mute bounce got cancelled by an unmute event")),this.debouncedTrackMuteHandler=kn(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(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(S.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new ve,this.pauseUpstreamLock=new ve,this.processorLock=new ve,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==y.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Bt(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop()),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());let n;if(this.processor&&e&&this.processorElement){if(f.debug("restarting processor"),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");xt(e,this.processorElement),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&(yield this.sender.replaceTrack(n??e)),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{xt(n??e,r)}))})}waitForDimensions(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:bo;var t;return p(this,void 0,void 0,function*(){if(this.kind===y.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((t=Ct())===null||t===void 0?void 0:t.os)==="iOS"&&(yield ft(10));const n=Date.now();for(;Date.now()-n1&&arguments[1]!==void 0?arguments[1]:!0;return p(this,void 0,void 0,function*(){if(!this.sender)throw new be("unable to replace an unpublished track");return f.debug("replace MediaStreamTrack"),yield this.setMediaStreamTrack(e),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this})}restart(e){return p(this,void 0,void 0,function*(){e||(e=this._constraints),f.debug("restarting track with constraints",e);const t={audio:!1,video:!1};this.kind===y.Kind.Video?t.video=e:t.audio=e,this.attachedElements.forEach(s=>{Bt(this.mediaStreamTrack,s)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(t)).getTracks()[0];return r.addEventListener("ended",this.handleEnded),f.debug("re-acquired MediaStreamTrack"),yield this.setMediaStreamTrack(r),this._constraints=e,this.emit(S.Restarted,this),this})}setTrackMuted(e){f.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted")),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?S.Muted:S.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Ts()&&(f.debug("visibility changed, is in Background: ".concat(this.isInBackground)),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(f.debug("track needs to be reacquired, restarting ".concat(this.source)),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return p(this,void 0,void 0,function*(){const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){f.warn("unable to pause upstream for an unpublished track");return}this._isUpstreamPaused=!0,this.emit(S.UpstreamPaused,this);const t=Ct();if((t==null?void 0:t.name)==="Safari"&&bn(t.version,"12.0")<0)throw new yn("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{e()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){f.warn("unable to resume upstream for an unpublished track");return}this._isUpstreamPaused=!1,this.emit(S.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{e()}})}getRTCStatsReport(){var e;return p(this,void 0,void 0,function*(){return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var n,r;return p(this,void 0,void 0,function*(){const s=yield this.processorLock.lock();try{if(f.debug("setting up processor"),this.processor&&(yield this.stopProcessor()),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement=(n=this.processorElement)!==null&&n!==void 0?n:document.createElement(this.kind),this.processorElement.muted=!0,xt(this._mediaStreamTrack,this.processorElement),this.processorElement.play().catch(o=>f.error("failed to play processor element",{error:o}));const a={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement};if(yield e.init(a),this.processor=e,this.processor.processedTrack){for(const o of this.attachedElements)o!==this.processorElement&&t&&(Bt(this._mediaStreamTrack,o),xt(this.processor.processedTrack,o));yield(r=this.sender)===null||r===void 0?void 0:r.replaceTrack(this.processor.processedTrack)}}finally{s()}})}getProcessor(){return this.processor}stopProcessor(){var e,t;return p(this,void 0,void 0,function*(){this.processor&&(f.debug("stopping processor"),(e=this.processor.processedTrack)===null||e===void 0||e.stop(),yield this.processor.destroy(),this.processor=void 0,(t=this.processorElement)===null||t===void 0||t.remove(),this.processorElement=void 0,yield this.restart())})}}class To extends Fe.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,r;const{kind:s,data:a}=t.data;switch(s){case"error":f.error(a.error.message),this.emit(bt.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(this.encryptionEnabled!==a.enabled&&a.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(bt.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(bt.ParticipantEncryptionStatusChanged,a.enabled,o)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"ratchetKey":this.keyProvider.emit(St.KeyRatcheted,a.material,a.keyIndex);break}},this.onWorkerError=t=>{f.error("e2ee worker encountered an error:",{error:t.error}),this.emit(bt.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!Wa())throw new yn("tried to setup end-to-end encryption on an unsupported browser");if(f.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions()}};this.worker&&(f.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){f.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?f.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(P.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(T.TrackPublished,(n,r)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==K.NONE,r.identity)),e.on(T.ConnectionStateChanged,n=>{n===O.Connected&&e.participants.forEach(r=>{r.tracks.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==K.NONE,r.identity)})})}).on(T.TrackUnsubscribed,(n,r,s)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:n.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(T.TrackSubscribed,(n,r,s)=>{this.setupE2EEReceiver(n,s.identity,r.trackInfo)}).on(T.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity),t.getKeys().forEach(n=>{this.postKey(n)})}),e.localParticipant.on(E.LocalTrackPublished,n=>p(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),t.on(St.SetKey,n=>this.postKey(n)).on(St.RatchetRequest,(n,r)=>this.postRatchetRequest(n,r))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:t,keyIndex:r}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}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,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?bs(n.mimeType):void 0)}}setupE2EESender(e,t){if(!(e instanceof ci)||!t){t||f.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,r){return p(this,void 0,void 0,function*(){if(this.worker){if(an()){const s={kind:"decode",participantIdentity:n,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(hi in e&&r){const c={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(c);return}let s=e.writableStream,a=e.readableStream;if(!s||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(o,[a,s])}e[hi]=!0}})}handleSender(e,t,n){var r;if(!(hi in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(an()){f.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{f.info("initialize encoded streams");const s=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[s.readable,s.writable])}e[hi]=!0}}}var ni;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(ni||(ni={}));class So{constructor(){this.pendingTasks=new Map,this.taskMutex=new ve,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ni.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ni.RUNNING,yield e()}finally{t.status=ni.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}const Co=["syncState","trickle","offer","answer","simulate","leave"];function Eo(i){const e=Co.indexOf(i.case)>=0;return f.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var j;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(j||(j={}));class Tn{get currentState(){return this.state}get isDisconnected(){return this.state===j.DISCONNECTING||this.state===j.DISCONNECTED}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.rtt=0,this.state=j.DISCONNECTED,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.useJSON=e,this.requestQueue=new So,this.queuedRequests=[],this.closingLock=new ve,this.connectionLock=new ve,this.state=j.DISCONNECTED}join(e,t,n,r){return p(this,void 0,void 0,function*(){return this.state=j.CONNECTING,this.options=n,yield this.connect(e,t,n,r)})}reconnect(e,t,n,r){return p(this,void 0,void 0,function*(){if(!this.options){f.warn("attempted to reconnect without signal options being set, ignoring");return}return this.state=j.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}))})}connect(e,t,n,r){this.connectOptions=n,e=ko(e),e=e.replace(/\/$/,""),e+="/rtc";const s=vo(),a=Po(t,s,n);return new Promise((o,c)=>p(this,void 0,void 0,function*(){const d=yield this.connectionLock.lock();try{const u=()=>p(this,void 0,void 0,function*(){this.close(),clearTimeout(h),c(new _("room connection has been cancelled (signal)"))}),h=setTimeout(()=>{this.close(),c(new _("room connection has timed out (signal)"))},n.websocketTimeout);r!=null&&r.aborted&&u(),r==null||r.addEventListener("abort",u),f.debug("connecting to ".concat(e+a)),this.ws&&(yield this.close()),this.ws=new WebSocket(e+a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=m=>p(this,void 0,void 0,function*(){if(this.state!==j.CONNECTED){clearTimeout(h);try{const g=yield fetch("http".concat(e.substring(2),"/validate").concat(a));if(g.status.toFixed(0).startsWith("4")){const k=yield g.text();c(new _(k,0,g.status))}else c(new _("Internal error",2,g.status))}catch{c(new _("server was not reachable",1))}return}this.handleWSError(m)}),this.ws.onmessage=m=>p(this,void 0,void 0,function*(){var g,k,b,w;let R;if(typeof m.data=="string"){const I=JSON.parse(m.data);R=Ie.fromJson(I)}else if(m.data instanceof ArrayBuffer)R=Ie.fromBinary(new Uint8Array(m.data));else{f.error("could not decode websocket message: ".concat(typeof m.data));return}if(this.state!==j.CONNECTED){let I=!1;if(((g=R.message)===null||g===void 0?void 0:g.case)==="join"?(this.state=j.CONNECTED,r==null||r.removeEventListener("abort",u),this.pingTimeoutDuration=R.message.value.pingTimeout,this.pingIntervalDuration=R.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(f.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),o(R.message.value)):this.state===j.RECONNECTING?(this.state=j.CONNECTED,r==null||r.removeEventListener("abort",u),this.startPingInterval(),((k=R.message)===null||k===void 0?void 0:k.case)==="reconnect"?o((b=R.message)===null||b===void 0?void 0:b.value):(o(),I=!0)):n.reconnect||c(new _("did not receive join response, got ".concat((w=R.message)===null||w===void 0?void 0:w.case," instead"))),!I)return}this.signalLatency&&(yield ft(this.signalLatency)),this.handleSignalResponse(R)}),this.ws.onclose=m=>{f.warn("websocket closed",{ev:m}),this.handleOnClose(m.reason)}}finally{d()}}))}close(){return p(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();try{if(this.state=j.DISCONNECTING,this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const t=new Promise(n=>{this.ws?this.ws.onclose=()=>{n()}:n()});this.ws.readyState1&&arguments[1]!==void 0?arguments[1]:!1;return p(this,void 0,void 0,function*(){if(!t&&!Eo(e)&&this.state===j.RECONNECTING){this.queuedRequests.push(()=>p(this,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield ft(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN){f.error("cannot send signal request before connected, type: ".concat(e==null?void 0:e.case));return}const r=new Ye({message:e});try{this.useJSON?this.ws.send(r.toJsonString()):this.ws.send(r.toBinary())}catch(s){f.error("error sending signal message",{error:s})}})}handleSignalResponse(e){var t,n;const r=e.message;if(r==null){f.debug("received unsupported message");return}let s=!1;if(r.case==="answer"){const a=$n(r.value);this.onAnswer&&this.onAnswer(a)}else if(r.case==="offer"){const a=$n(r.value);this.onOffer&&this.onOffer(a)}else if(r.case==="trickle"){const a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=r.value.speakers)!==null&&n!==void 0?n:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):f.debug("unsupported message",r));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return p(this,void 0,void 0,function*(){if(this.state===j.DISCONNECTED)return;const t=this.onClose;yield this.close(),f.debug("websocket connection closed: ".concat(e)),t&&t(e)})}handleWSError(e){f.error("websocket error",e)}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){f.warn("ping timeout duration not set");return}this.pingTimeout=H.setTimeout(()=>{f.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&H.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){f.warn("ping interval duration not set");return}f.debug("start ping interval"),this.pingInterval=H.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){f.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&H.clearInterval(this.pingInterval)}}function $n(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function Ii(i){return new Z({sdp:i.sdp,type:i.type})}function Po(i,e,t){var n;const r=new URLSearchParams;return r.set("access_token",i),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",Dt()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),t.publishOnly!==void 0&&r.set("publish",t.publishOnly),t.adaptiveStream&&r.set("adaptive_stream","1"),t.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&r.set("network",navigator.connection.type),"?".concat(r.toString())}var Ps={},ws={exports:{}},Zn=ws.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(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.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(i){return i.address!=null?"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(i){return i.subtype!=null?"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(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.sessionConfig!=null?"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(i){var e="candidate:%s %d %s %d %s %d typ %s";return e+=i.raddr!=null?" raddr %s rport %d":"%v%v",e+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(e+=" generation %d"),e+=i["network-id"]!=null?" network-id %d":"%v",e+=i["network-cost"]!=null?" network-cost %d":"%v",e}},{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(i){var e="ssrc:%d";return i.attribute!=null&&(e+=" %s",i.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(i){return i.maxMessageSize!=null?"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(i){return i.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(i){return"imageattr:%s %s %s"+(i.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(i){return"simulcast:%s %s"+(i.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(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var e="mediaclk:";return e+=i.id!=null?"id=%s %s":"%v%s",e+=i.mediaClockValue!=null?"=%s":"",e+=i.rateNumerator!=null?" rate=%s":"",e+=i.rateDenominator!=null?"/%s":"",e}},{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"]}]};Object.keys(Zn).forEach(function(i){var e=Zn[i];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var Rs=ws.exports;(function(i){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,u){if(u&&!d)c[u]=e(o[1]);else for(var h=0;h1&&(o[d[0]]=void 0),o};i.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(o){return o.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(o){for(var c=[],d=o.split(" ").map(e),u=0;u=n)return r;var s=t[e];switch(e+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},$t=function(i,e,t){var n=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,r=[i+"="+n];if(e.names)for(var s=0;s1&&arguments[1]!==void 0?arguments[1]:{};super(),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=kn(n=>p(this,void 0,void 0,function*(){this.emit(Jt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(n)n(r);else throw r}}),100),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.config=e,this.mediaConstraints=t,this._pc=this.createPC()}createPC(){const e=mo()?new RTCPeerConnection(this.config,this.mediaConstraints):new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){var t;return p(this,void 0,void 0,function*(){let n;if(e.type==="offer"){let{stereoMids:r,nackMids:s}=Lo(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=ei((t=e.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{s.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||s.mid!=a.transceiver.mid)return!1;let o=0;if(s.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0)return!0;let c=!1;for(const d of s.fmtp)if(d.payload===o){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&s.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),n=qi(r)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Jt.NegotiationComplete),e.sdp&&ei(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(Jt.RTPVideoPayloadTypes,s.rtp)}))})}createAndSendOffer(e){var t;return p(this,void 0,void 0,function*(){if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(f.debug("restarting ICE"),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const s=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&s)yield this._pc.setRemoteDescription(s);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){f.warn("could not createOffer with closed peer connection");return}f.debug("starting to negotiate");const n=yield this.pc.createOffer(e),r=ei((t=n.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{s.type==="audio"?ir(s,[],[]):s.type==="video"&&(Ao(s),this.trackBitrates.some(a=>{if(!s.msid||!a.cid||!s.msid.includes(a.cid))return!1;let o=0;if(s.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0)return!0;let c=!1;for(const d of s.fmtp)if(d.payload===o){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(Math.round(a.maxbr*er))),d.config.includes("x-google-max-bitrate")||(d.config+=";x-google-max-bitrate=".concat(a.maxbr)),c=!0;break}return c||s.fmtp.push({payload:o,config:"x-google-start-bitrate=".concat(Math.round(a.maxbr*er),";x-google-max-bitrate=").concat(a.maxbr)}),!0}))}),yield this.setMungedSDP(n,qi(r)),this.onOffer(n)})}createAndSetAnswer(){var e;return p(this,void 0,void 0,function*(){const t=yield this.pc.createAnswer(),n=ei((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(r=>{r.type==="audio"&&ir(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,qi(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new J("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 J("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){var e;return p(this,void 0,void 0,function*(){if(!this._pc)return;let t="";const n=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),n.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,n){return p(this,void 0,void 0,function*(){if(t){const r=e.sdp;e.sdp=t;try{f.debug("setting munged ".concat(n?"remote":"local"," description")),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){f.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:s,sdp:t}),e.sdp=r}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const a={error:s,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),f.error("unable to set ".concat(e.type),a),new on(s)}})}}function ir(i,e,t){let n=0;i.rtp.some(r=>r.codec==="opus"?(n=r.payload,!0):!1),n>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(i.mid)&&!i.rtcpFb.some(r=>r.payload===n&&r.type==="nack")&&i.rtcpFb.push({payload:n,type:"nack"}),e.includes(i.mid)&&i.fmtp.some(r=>r.payload===n?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Ao(i){var e,t,n,r;const s=(t=(e=i.rtp[0])===null||e===void 0?void 0:e.codec)===null||t===void 0?void 0:t.toLowerCase();if(!ii(s))return;let a=0;((n=i.ext)===null||n===void 0?void 0:n.some(c=>c.uri===jn?!0:(c.value>a&&(a=c.value),!1)))||(r=i.ext)===null||r===void 0||r.push({value:a+1,uri:jn})}function Lo(i){var e;const t=[],n=[],r=ei((e=i.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&n.push(a.mid),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:n}}const hn="vp8",_o={audioBitrate:wi.music.maxBitrate,audioPreset:wi.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:vs.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:hn,backupCodec:!0},Is={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},Ns={resolution:oi.h720.resolution},xo={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ra,disconnectOnPageLeave:!0,expWebAudioMix:!1},Sn={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var V;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(V||(V={}));class Uo{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t){this.peerConnectionTimeout=Sn.peerConnectionTimeout,this.updateState=()=>{var r;const s=this.state,a=this.requiredTransports.map(o=>o.getConnectionState());a.every(o=>o==="connected")?this.state=V.CONNECTED:a.some(o=>o==="failed")?this.state=V.FAILED:a.some(o=>o==="connecting")?this.state=V.CONNECTING:a.every(o=>o==="closed")?this.state=V.CLOSED:a.some(o=>o==="closed")?this.state=V.CLOSING:a.every(o=>o==="new")&&(this.state=V.NEW),s!==this.state&&(f.debug("pc state change: from ".concat(V[s]," to ").concat(V[this.state])),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t;const n={optional:[{googDscp:!0}]};this.publisher=new tr(e,n),this.subscriber=new tr(e),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,Y.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,Y.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,r)},this.subscriber.onTrack=r=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,r)},this.publisher.onOffer=r=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,r)},this.state=V.NEW,this.connectionLock=new ve}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return p(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){f.warn("could not removeTrack",{error:n})}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){t===Y.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return p(this,void 0,void 0,function*(){return f.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.getSignallingState().toString()}),yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){var n;return p(this,void 0,void 0,function*(){const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(f.debug("negotiation required, start negotiating"),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new Promise((t,n)=>p(this,void 0,void 0,function*(){const r=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),n("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(Jt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Jt.NegotiationComplete,()=>{clearTimeout(r),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(r),n(a)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Y.PUBLISHER?this.publisher.getConnectedAddress():e===Y.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return p(this,void 0,void 0,function*(){if(e.getConnectionState()!=="connected")return new Promise((s,a)=>p(this,void 0,void 0,function*(){const o=()=>{f.warn("abort transport connection"),H.clearTimeout(c),a(new _("room connection has been cancelled",3))};t!=null&&t.signal.aborted&&o(),t==null||t.signal.addEventListener("abort",o);const c=H.setTimeout(()=>{t==null||t.signal.removeEventListener("abort",o),a(new _("could not establish pc connection"))},n);for(;this.state!==V.CONNECTED;)if(yield ft(50),t!=null&&t.signal.aborted){a(new _("room connection has been cancelled",3));return}H.clearTimeout(c),t==null||t.signal.removeEventListener("abort",o),s()}))})}}const nr="_lossy",rr="_reliable",Fo=2*1e3,sr="leave-reconnect";var ce;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(ce||(ce={}));class Bo extends Fe.EventEmitter{get isClosed(){return this._isClosed}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Sn.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=ce.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.handleDataChannel=t=>{let{channel:n}=t;return p(this,void 0,void 0,function*(){if(n){if(n.label===rr)this.reliableDCSub=n;else if(n.label===nr)this.lossyDCSub=n;else return;f.debug("on data channel ".concat(n.id,", ").concat(n.label)),n.onmessage=this.handleDataMessage}})},this.handleDataMessage=t=>p(this,void 0,void 0,function*(){var n,r;const s=yield this.dataProcessLock.lock();try{let a;if(t.data instanceof ArrayBuffer)a=t.data;else if(t.data instanceof Blob)a=yield t.data.arrayBuffer();else{f.error("unsupported data type",t.data);return}const o=Te.fromBinary(new Uint8Array(a));((n=o.value)===null||n===void 0?void 0:n.case)==="speaker"?this.emit(P.ActiveSpeakersUpdate,o.value.value.speakers):((r=o.value)===null||r===void 0?void 0:r.case)==="user"&&this.emit(P.DataPacketReceived,o.value.value,o.kind)}finally{s()}}),this.handleDataError=t=>{const r=t.currentTarget.maxRetransmits===0?"lossy":"reliable";if(t instanceof ErrorEvent&&t.error){const{error:s}=t.error;f.error("DataChannel error on ".concat(r,": ").concat(t.message),s)}else f.error("Unknown DataChannel error on ".concat(r),t)},this.handleBufferedAmountLow=t=>{const r=t.currentTarget.maxRetransmits===0?W.LOSSY:W.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;f.warn("".concat(t," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=o=>{f.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(o,"ms. giving up")),this.emit(P.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(a===null){r(s);return}t===sr&&(a=0),f.debug("reconnecting in ".concat(a,"ms")),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=H.setTimeout(()=>this.attemptReconnect(n),a)},this.waitForRestarted=()=>new Promise((t,n)=>{this.pcState===ce.Connected&&t();const r=()=>{this.off(P.Disconnected,s),t()},s=()=>{this.off(P.Restarted,r),n()};this.once(P.Restarted,r),this.once(P.Disconnected,s)}),this.updateAndEmitDCBufferStatus=t=>{const n=this.isBufferStatusLow(t);typeof n<"u"&&n!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,n),this.emit(P.DCBufferStatusChanged,n,t))},this.isBufferStatusLow=t=>{const n=this.dataChannelForKind(t);if(n)return n.bufferedAmount<=n.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===j.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Be.RR_SIGNAL_DISCONNECTED))},this.client=new Tn,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new ve,this.dataProcessLock=new ve,this.dcBufferStatus=new Map([[W.LOSSY,!0],[W.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(P.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(P.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(P.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(P.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(P.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(P.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(P.StreamStateChanged,t)}join(e,t,n,r){return p(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,n,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=s.clientConfiguration,s}catch(s){if(s instanceof _&&s.reason===1&&(f.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.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})}cleanupClient(){return p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new be("a track with the same ID has already been published");return new Promise((t,n)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new _("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),n(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(t){f.warn("failed to remove track",{error:t,method:"removeTrack"})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){var e;return p(this,void 0,void 0,function*(){return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){var t;return p(this,void 0,void 0,function*(){if(this.pcManager&&this.pcManager.currentState!==V.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const n=this.makeRTCConfiguration(e);this.pcManager=new Uo(n,e.subscriberPrimary),this.emit(P.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,a)=>p(this,void 0,void 0,function*(){if(f.debug("primary PC state changed ".concat(r)),r===V.CONNECTED){const o=this.pcState===ce.New;this.pcState=ce.Connected,o&&this.emit(P.Connected,e)}else r===V.FAILED&&this.pcState===ce.Connected&&(this.pcState=ce.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Be.RR_SUBSCRIBER_FAILED:Be.RR_PUBLISHER_FAILED))}),this.pcManager.onTrack=r=>{this.emit(P.MediaTrackAdded,r.track,r.streams[0],r.receiver)},this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>p(this,void 0,void 0,function*(){this.pcManager&&(f.debug("received server answer",{RTCSdpType:e.type}),yield this.pcManager.setPublisherAnswer(e))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(f.trace("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>p(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{if(f.debug("received trackPublishedResponse",e),!this.pendingTrackResolvers[e.cid]){f.error("missing track resolver for ".concat(e.cid));return}const{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(P.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(P.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Be.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{e!=null&&e.canReconnect?(this.fullReconnectOnNext=!0,this.handleDisconnect(sr)):(this.emit(P.Disconnected,e==null?void 0:e.reason),this.close()),f.trace("leave request",{leave:e})}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(f.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const r=[];e.iceServers.forEach(s=>{const a={urls:s.urls};s.username&&(a.username=s.username),s.credential&&(a.credential=s.credential),r.push(a)}),n.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ye.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}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(nr,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(rr,{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)}setPreferredCodec(e,t,n){if(!("getCapabilities"in RTCRtpSender))return;const r=RTCRtpSender.getCapabilities(t);if(!r)return;f.debug("get capabilities",r);const s=[],a=[],o=[];r.codecs.forEach(c=>{const d=c.mimeType.toLowerCase();if(d==="audio/opus"){s.push(c);return}if(!(d==="video/".concat(n))){o.push(c);return}if(n==="h264"){c.sdpFmtpLine&&c.sdpFmtpLine.includes("profile-level-id=42e01f")?s.push(c):a.push(c);return}s.push(c)}),fo(e)&&e.setCodecPreferences(s.concat(a,o))}createSender(e,t,n){return p(this,void 0,void 0,function*(){if(Gn())return yield this.createTransceiverRTCRtpSender(e,t,n);if(Wn())return f.warn("using add-track fallback"),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new J("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,r){return p(this,void 0,void 0,function*(){if(Gn())return this.createSimulcastTransceiverSender(e,t,n,r);if(Wn())return f.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new J("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new J("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream);const s={direction:"sendonly",streams:r};n&&(s.sendEncodings=n);const a=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s);return e.kind===y.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(a,e.kind,t.videoCodec),e.codec=t.videoCodec),a.sender})}createSimulcastTransceiverSender(e,t,n,r){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new J("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(n.videoCodec)return this.setPreferredCodec(a,e.kind,n.videoCodec),e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new J("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){var t,n,r;return p(this,void 0,void 0,function*(){if(!this._isClosed&&!this.attemptingReconnect){(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===ye.DISABLED||((r=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&r!==void 0?r:V.NEW)===V.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof J?(f.debug("received unrecoverable error",{error:s}),a=!1):s instanceof fi||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Be.RR_UNKNOWN):(f.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(P.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){f.warn("encountered error in reconnect policy",{error:t})}return null}restartConnection(e){var t,n,r;return p(this,void 0,void 0,function*(){try{if(!this.url||!this.token)throw new J("could not reconnect, url or token not saved");f.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(P.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw f.warn("attempted connection restart, without signal options present"),new fi;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof _&&a.reason===0?new J("could not reconnect, token might be expired"):new fi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.client.setReconnected(),this.emit(P.SignalRestarted,s),yield this.waitForPCReconnected(),(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(P.Restarted)}catch(s){const a=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){var t;return p(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new J("could not reconnect, url or token not saved");if(!this.pcManager)throw new J("publisher and subscriber connections unset");f.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(P.Resuming);try{this.setupSignalClientCallbacks();const n=yield this.client.reconnect(this.url,this.token,this.participantSid,e);if(n){const r=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(r)}}catch(n){let r="";throw n instanceof Error&&(r=n.message,f.error(n.message)),n instanceof _&&n.reason===0?new J("could not reconnect, token might be expired"):new fi(r)}if(this.emit(P.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(P.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new J("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=ce.Reconnecting,f.debug("waiting for peer connection to reconnect");try{if(yield ft(Fo),!this.pcManager)throw new J("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ce.Connected}catch(e){throw this.pcState=ce.Disconnected,new _("could not establish PC connection, ".concat(e.message))}})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const r=this.dataChannelForKind(t);r&&r.send(n),this.updateAndEmitDCBufferStatus(t)})}ensureDataTransportConnected(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;var n;return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new J("PC manager is closed");const r=t?this.pcManager.subscriber:this.pcManager.publisher,s=t?"Subscriber":"Publisher";if(!r)throw new _("".concat(s," connection not set"));!t&&!this.pcManager.publisher.isICEConnected&&this.pcManager.publisher.getICEConnectionState()!=="checking"&&this.negotiate();const a=this.dataChannelForKind(e,t);if((a==null?void 0:a.readyState)==="open")return;const o=new Date().getTime()+this.peerConnectionTimeout;for(;new Date().getTime()p(this,void 0,void 0,function*(){if(!this.pcManager){t(new on("PC manager is closed"));return}this.pcManager.requirePublisher();const n=new AbortController,r=()=>{n.abort(),f.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(P.Closing,r),this.pcManager.publisher.once(Jt.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const c=o.codec.toLowerCase();yo(c)&&a.set(o.payload,c)}),this.emit(P.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(n),e()}catch(s){s instanceof on&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Be.RR_UNKNOWN),t(s)}finally{this.off(P.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===W.LOSSY)return this.lossyDCSub;if(e===W.RELIABLE)return this.reliableDCSub}else{if(e===W.LOSSY)return this.lossyDC;if(e===W.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,r;if(!this.pcManager){f.warn("sync state cannot be sent without peer connection setup");return}const s=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(r=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array;e.forEach(d=>{d.isDesired!==o&&c.push(d.trackSid)}),this.client.sendSyncState(new _e({answer:s?Ii({sdp:s.sdp,type:s.type}):void 0,offer:a?Ii({sdp:a.sdp,type:a.type}):void 0,subscription:new ae({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:ao(t),dataChannels:this.dataChannelsInfo()}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,r)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new xe({label:n.label,id:n.id,target:r}))};return t(this.dataChannelForKind(W.LOSSY),Y.PUBLISHER),t(this.dataChannelForKind(W.RELIABLE),Y.PUBLISHER),t(this.dataChannelForKind(W.LOSSY,!0),Y.SUBSCRIBER),t(this.dataChannelForKind(W.RELIABLE,!0),Y.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&H.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ne()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){ne()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class fi extends Error{}class ar{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return ln(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(r=>r.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),f.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){const t=yield fetch("".concat(Jo(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new _("Could not fetch region settings: ".concat(t.statusText),t.status===401?0:void 0,t.status)})}}function Jo(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}const Cn=2e3;function Ai(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}class ee extends ci{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,y.Kind.Audio,t,n),this.stopOnMute=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(a){f.error("could not get audio sender stats",{error:a});return}s&&this.prevStats&&(this._currentBitrate=Ai(s,this.prevStats)),this.prevStats=s}),this.audioContext=r,this.checkForSilence()}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Pt(e)===this.mediaStreamTrack.getSettings().deviceId)})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.source===y.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(f.debug("stopping mic track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Pt(this._constraints.deviceId);return this.source===y.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(f.debug("reacquiring mic track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const n=Mi({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){ne()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Cn)))}setProcessor(e){var t;return p(this,void 0,void 0,function*(){const n=yield this.processorLock.lock();try{if(!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");if(this.processor&&(yield this.stopProcessor()),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};f.debug("setting up audio processor ".concat(e.name)),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack))}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){var e;return p(this,void 0,void 0,function*(){if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(r=>{r.type==="outbound-rtp"&&(n={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),n})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield no(this);return e&&(this.isMuted||f.warn("silence detected on local audio track"),this.emit(S.AudioSilenceDetected)),e})}}function Ds(i,e){switch(i.kind){case"audio":return new ee(i,e,!1);case"video":return new re(i,e,!1);default:throw new be("unsupported track type: ".concat(i.kind))}}const Vo=Object.values(oi),qo=Object.values(cn),jo=Object.values(vs),Go=[oi.h180,oi.h360],Wo=[cn.h180,cn.h360],Ko=i=>[{scaleResolutionDownBy:2,fps:3}].map(t=>{var n;return new A(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/t.fps)))),t.fps,i.encoding.priority)}),fn=["q","h","f"];function mn(i,e,t,n){var r,s;let a=n==null?void 0:n.videoEncoding;i&&(a=n==null?void 0:n.screenShareEncoding);const o=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,d=n==null?void 0:n.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=zo(i,e,t,d),f.debug("using video encoding",a));const u=new A(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&ii(d)){f.debug("using svc with scalabilityMode ".concat(c));const g=new Os(c),k=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));for(let b=0;b0){const g=h[0];h.length>1&&([,m]=h);const k=Math.max(e,t);if(k>=960&&m)return ji(e,t,[g,m,u]);if(k>=480)return ji(e,t,[g,u])}return ji(e,t,[u])}function Ho(i,e,t){var n,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&f.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=i.mediaStreamTrack.getSettings(),c=(n=o.width)!==null&&n!==void 0?n:(r=i.dimensions)===null||r===void 0?void 0:r.width,d=(s=o.height)!==null&&s!==void 0?s:(a=i.dimensions)===null||a===void 0?void 0:a.height;return mn(i.source===y.Source.ScreenShare,c,d,t)}function zo(i,e,t,n){const r=Yo(i,e,t);let{encoding:s}=r[0];const a=Math.max(e,t);for(let o=0;o=a)break}if(n)switch(n){case"av1":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function Yo(i,e,t){if(i)return jo;const n=e>t?e/t:t/e;return Math.abs(n-16/9)n?t/n:n/t;return Math.abs(r-16/9){if(s>=fn.length)return;const a=Math.min(i,e),c={rid:fn[s],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate};r.encoding.maxFramerate&&(c.maxFramerate=r.encoding.maxFramerate);const d=jt()||s===0;r.encoding.priority&&d&&(c.priority=r.encoding.priority,c.networkPriority=r.encoding.priority),n.push(c)}),Dt()&&Cs()==="ios"){let r;n.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let s=!0;n.forEach(a=>{var o;a.maxFramerate!=r&&(s&&(s=!1,f.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),f.info('Setting framerate of encoding "'.concat((o=a.rid)!==null&&o!==void 0?o:"",'" to ').concat(r)),a.maxFramerate=r)})}return n}function cr(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:r}=t;return n.maxBitrate>r.maxBitrate?1:n.maxBitrater.maxFramerate?1:-1:0})}class Os{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((e=this.suffix)!==null&&e!==void 0?e:"")}}const Qo=5e3;class re extends ci{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;super(e,y.Kind.Video,t,n),this.simulcastCodecs=new Map,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(a){f.error("could not get audio sender stats",{error:a});return}const s=new Map(r.map(a=>[a.rid,a]));if(this.prevStats){let a=0;s.forEach((o,c)=>{var d;const u=(d=this.prevStats)===null||d===void 0?void 0:d.get(c);a+=Ai(o,u)}),this._currentBitrate=a}this.prevStats=s}),this.senderLock=new ve}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ne())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Cn))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});var t,n,r,s,a;return p(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var o=!0,c=_t(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)s=d.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(u){n={error:u}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});var t,n,r,s,a;return p(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var o=!0,c=_t(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){s=d.value,o=!1;const u=s;yield(a=u.sender)===null||a===void 0?void 0:a.replaceTrack(u.mediaStreamTrack)}}catch(u){n={error:u}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.source===y.Source.Camera&&!this.isUserProvided&&(f.debug("stopping camera track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.source===y.Source.Camera&&!this.isUserProvided&&(f.debug("reacquiring camera track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){var e;return p(this,void 0,void 0,function*(){if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,framesSent:r.framesSent,timestamp:r.timestamp,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges},o=n.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t})}setPublishingQuality(e){const t=[];for(let n=q.LOW;n<=q.HIGH;n+=1)t.push(new ge({quality:n,enabled:n<=e}));f.debug("setting publishing quality. max quality ".concat(e)),this.setPublishingLayers(t)}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Pt(e)?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Pt(e)===this._mediaStreamTrack.getSettings().deviceId)})}restartTrack(e){var t,n,r,s;return p(this,void 0,void 0,function*(){let a;if(e){const u=Mi({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a);try{for(var o=!0,c=_t(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){s=d.value,o=!1;const u=s;u.sender&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){n={error:u}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});var r,s,a,o,c,d;return p(this,void 0,void 0,function*(){if(yield n.setProcessor.call(this,e,t),!((c=this.processor)===null||c===void 0)&&c.processedTrack)try{for(var u=!0,h=_t(this.simulcastCodecs.values()),m;m=yield h.next(),r=m.done,!r;u=!0)o=m.value,u=!1,yield(d=o.sender)===null||d===void 0?void 0:d.replaceTrack(this.processor.processedTrack)}catch(g){s={error:g}}finally{try{!u&&!r&&(a=h.return)&&(yield a.call(h))}finally{if(s)throw s.error}}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Qo))}setPublishingCodecs(e){var t,n,r,s,a,o,c;return p(this,void 0,void 0,function*(){if(f.debug("setting publishing codecs",{codecs:e,currentCodec:this.codec}),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,n=_t(e);r=yield n.next(),s=r.done,!s;t=!0){c=r.value,t=!1;const u=c;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const h=this.simulcastCodecs.get(u.codec);if(f.debug("try setPublishingCodec for ".concat(u.codec),h),!h||!h.sender){for(const m of u.qualities)if(m.enabled){d.push(u.codec);break}}else h.encodings&&(f.debug("try setPublishingLayersForSender ".concat(u.codec)),yield dr(h.sender,h.encodings,u.qualities,this.senderLock))}}}catch(u){a={error:u}}finally{try{!t&&!s&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e){return p(this,void 0,void 0,function*(){f.debug("setting publishing layers",e),!(!this.sender||!this.encodings)&&(yield dr(this.sender,this.encodings,e,this.senderLock))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Ts()&&this.isInBackground&&this.source===y.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function dr(i,e,t,n){return p(this,void 0,void 0,function*(){const r=yield n.lock();f.debug("setPublishingLayersForSender",{sender:i,qualities:t,senderEncodings:e});try{const s=i.getParameters(),{encodings:a}=s;if(!a)return;if(a.length!==e.length){f.warn("cannot set publishing layers, encodings mismatch");return}let o=!1;!1&&a[0].scalabilityMode||a.forEach((d,u)=>{var h;let m=(h=d.rid)!==null&&h!==void 0?h:"";m===""&&(m="q");const g=Ms(m),k=t.find(b=>b.quality===g);k&&d.active!==k.enabled&&(o=!0,d.active=k.enabled,f.debug("setting layer ".concat(k.quality," to ").concat(d.active?"enabled":"disabled")),jt()&&(k.enabled?(d.scaleResolutionDownBy=e[u].scaleResolutionDownBy,d.maxBitrate=e[u].maxBitrate,d.maxFrameRate=e[u].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))}),o&&(s.encodings=a,f.debug("setting encodings",s.encodings),yield i.setParameters(s))}finally{r()}})}function Ms(i){switch(i){case"f":return q.HIGH;case"h":return q.MEDIUM;case"q":return q.LOW;default:return q.HIGH}}function ur(i,e,t,n){if(!t)return[new $({quality:q.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const r=t[0].scalabilityMode,s=new Os(r),a=[];for(let o=0;o{var s,a,o;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let d=Ms((a=r.rid)!==null&&a!==void 0?a:"");return new $({quality:d,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}class As extends y{constructor(e,t,n,r){super(e,n),this.sid=t,this.receiver=r}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?S.Muted:S.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver=void 0,this._currentBitrate=0,this.emit(S.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){var e;return p(this,void 0,void 0,function*(){return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Cn))}}class ri extends As{constructor(e,t,n,r,s){super(e,t,y.Kind.Audio,n),this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Ai(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Dt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Dt())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(un(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&un(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(f.debug("using audio context mapping"),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 n=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{n.connect(r),n=r}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(S.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(S.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const Gi=100;class si extends As{constructor(e,t,n,r){super(e,t,y.Kind.Video,n),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=Ai(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=kn(()=>{this.updateDimensions()},Gi),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Bt(this._mediaStreamTrack,t):xt(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Xo(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):f.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream){f.warn("stopObservingElementInfo ignored");return}const t=this.elementInfos.filter(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(n=s.codecId,t={type:"video",framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&n!==""&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const n=this.elementInfos.reduce((o,c)=>Math.max(o,c.visibilityChangedAt||0),0),r=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,s=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!r||s;if(this.lastVisible!==a){if(!a&&Date.now()-n{this.updateVisibility()},Gi);return}this.lastVisible=a,this.emit(S.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let n=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,c=a.height()*s;o+c>n+r&&(n=o,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:n,height:r},this.emit(S.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Kn():t||(Kn()>2?2:1)}}class Xo{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var r;const{target:s,isIntersecting:a}=n;s===this.element&&(this.isIntersecting=a,this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var n;this.isPiP=!0,(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=!1,(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??lr(e),this.isPiP=ne()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=lr(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;(e=this.handleResize)===null||e===void 0||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,zn().observe(this.element),Hn().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;(e=zn())===null||e===void 0||e.unobserve(this.element),(t=Hn())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function lr(i){let e=i.offsetTop,t=i.offsetLeft;const n=i.offsetWidth,r=i.offsetHeight,{hidden:s}=i,{opacity:a,display:o}=getComputedStyle(i);for(;i.offsetParent;)i=i.offsetParent,e+=i.offsetTop,t+=i.offsetLeft;return ewindow.pageYOffset&&t+n>window.pageXOffset&&!s&&(a!==""?parseFloat(a)>0:!0)&&o!=="none"}class Je extends Fe.EventEmitter{constructor(e,t,n){super(),this.metadataMuted=!1,this.encryption=K.NONE,this.handleMuted=()=>{this.emit(S.Muted)},this.handleUnmuted=()=>{this.emit(S.Unmuted)},this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=y.Source.Unknown}setTrack(e){this.track&&(this.track.off(S.Muted,this.handleMuted),this.track.off(S.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(S.Muted,this.handleMuted),e.on(S.Unmuted,this.handleUnmuted))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==K.NONE}get audioTrack(){if(this.track instanceof ee||this.track instanceof ri)return this.track}get videoTrack(){if(this.track instanceof re||this.track instanceof si)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=y.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===y.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,f.debug("update publication info",{info:e})}}(function(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(i.PermissionStatus||(i.PermissionStatus={}))})(Je||(Je={}));class Ni extends Je{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n){super(e,t.sid,t.name),this.track=void 0,this.handleTrackEnded=()=>{this.emit(S.Ended)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&this.track.off(S.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(S.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return p(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){var e;return p(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){var e;return p(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){var e;return p(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}}var pt;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(pt||(pt={}));function $o(i){switch(i){case qe.EXCELLENT:return pt.Excellent;case qe.GOOD:return pt.Good;case qe.POOR:return pt.Poor;case qe.LOST:return pt.Lost;default:return pt.Unknown}}class Ls extends Fe.EventEmitter{get isEncrypted(){return this.tracks.size>0&&Array.from(this.tracks.values()).every(e=>e.isEncrypted)}get isAgent(){var e,t;return(t=(e=this.permissions)===null||e===void 0?void 0:e.agent)!==null&&t!==void 0?t:!1}constructor(e,t,n,r){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=pt.Unknown,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){for(const[,t]of this.tracks)if(t.source===e)return t}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrack(y.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(y.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrack(y.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,f.trace("update participant info",{info:e}),!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(E.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(E.ParticipantNameChanged,e)}setPermissions(e){var t,n,r,s,a;const o=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])});return this.permissions=e,c&&this.emit(E.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(E.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=$o(e),t!==this._connectionQuality&&this.emit(E.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach(t=>(t.track instanceof ri||t.track instanceof ee)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(S.Muted,()=>{this.emit(E.TrackMuted,e)}),e.on(S.Unmuted,()=>{this.emit(E.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.tracks.set(e.trackSid,e),e.kind){case y.Kind.Audio:this.audioTracks.set(e.trackSid,e);break;case y.Kind.Video:this.videoTracks.set(e.trackSid,e);break}}}function Zo(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ae({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}class _s extends Je{constructor(e,t,n){super(e,t.sid,t.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=q.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(S.Ended,r)},this.handleVisibilityChange=r=>{f.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),{trackSid:this.trackSid}),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{f.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),{trackSid:this.trackSid}),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new ae({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Ee({participantSid:"",trackSids:[this.trackSid]})]});this.emit(S.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Je.SubscriptionStatus.Unsubscribed:super.isSubscribed?Je.SubscriptionStatus.Subscribed:Je.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Je.PermissionStatus.Allowed:Je.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(this.track instanceof si&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof si&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(S.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(S.VisibilityChanged,this.handleVisibilityChange),r.off(S.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(S.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(S.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(S.VisibilityChanged,this.handleVisibilityChange),e.on(S.Ended,this.handleEnded),this.emit(S.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(S.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?S.Muted:S.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(S.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(S.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===y.Kind.Video&&this.isAdaptiveStream?(f.warn("adaptive stream is enabled, cannot change video track settings",{trackSid:this.trackSid}),!1):this.isDesired?!0:(f.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof si&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ne({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=q.HIGH,this.emit(S.UpdateSettings,e)}}class di extends Ls{static fromParticipantInfo(e,t){return new di(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,n,r,s){super(t,n||"",r,s),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(S.UpdateSettings,t=>{f.debug("send update settings",t),this.signalClient.sendUpdateTrackSettings(t)}),e.on(S.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(S.SubscriptionPermissionChanged,t=>{this.emit(E.TrackSubscriptionPermissionChanged,e,t)}),e.on(S.SubscriptionStatusChanged,t=>{this.emit(E.TrackSubscriptionStatusChanged,e,t)}),e.on(S.Subscribed,t=>{this.emit(E.TrackSubscribed,t,e)}),e.on(S.Unsubscribed,t=>{this.emit(E.TrackUnsubscribed,t,e)}),e.on(S.SubscriptionFailed,t=>{this.emit(E.TrackSubscriptionFailed,e.trackSid,t)})}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:y.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrack(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:y.Source.Microphone;const t=this.getTrack(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,s,a){let o=this.getTrackPublication(t);if(o||t.startsWith("TR")||this.tracks.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(a===0){f.error("could not find published track",{participant:this.sid,trackSid:t}),this.emit(E.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,s,a-1)},150);return}if(e.readyState==="ended"){f.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:t}),this.emit(E.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new si(e,t,r,s):d=new ri(e,t,r,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(n),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&d instanceof ri&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(r=>{var s;let a=this.getTrackPublication(r.sid);if(a)a.updateInfo(r);else{const o=y.kindFromProto(r.type);if(!o)return;a=new _s(o,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe),a.updateInfo(r),n.set(r.sid,a);const c=Array.from(this.tracks.values()).find(d=>d.source===(a==null?void 0:a.source));c&&a.source!==y.Source.Unknown&&f.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),{oldTrack:c,newTrack:a,participant:this,participantInfo:e}),this.addTrackPublication(a)}t.set(r.sid,a)}),this.tracks.forEach(r=>{t.has(r.trackSid)||(f.trace("detected removed track on remote participant, unpublishing",{publication:r,participantSid:this.sid}),this.unpublishTrack(r.trackSid,!0))}),n.forEach(r=>{this.emit(E.TrackPublished,r)}),!0}unpublishTrack(e,t){const n=this.tracks.get(e);if(!n)return;const{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.tracks.delete(e),n.kind){case y.Kind.Audio:this.audioTracks.delete(e);break;case y.Kind.Video:this.videoTracks.delete(e);break}t&&this.emit(E.TrackUnpublished,n)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTracks.forEach(n=>{var r;n.track instanceof ri&&t.push(n.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r{this.reconnectFuture||(this.reconnectFuture=new Es)},this.handleReconnected=()=>{var s,a;(a=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||a===void 0||a.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch(o=>f.warn(o)),(a=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||a===void 0||a.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{f.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>Zo(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,a)=>{if(a===void 0&&(a=!0),!s.sid){f.error("could not update mute status for unpublished track",s);return}this.engine.updateMuteStatus(s.sid,a)},this.onTrackUpstreamPaused=s=>{f.debug("upstream paused"),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{f.debug("upstream resumed"),this.onTrackMuted(s,s.isMuted)},this.handleSubscribedQualityUpdate=s=>p(this,void 0,void 0,function*(){var a,o,c,d,u,h;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const m=this.videoTracks.get(s.trackSid);if(!m){f.warn("received subscribed quality update for unknown track",{method:"handleSubscribedQualityUpdate",sid:s.trackSid});return}if(s.subscribedCodecs.length>0){if(!m.videoTrack)return;const w=yield m.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var g=!0,k=_t(w),b;b=yield k.next(),a=b.done,!a;g=!0){d=b.value,g=!1;const R=d;eo(R)&&(f.debug("publish ".concat(R," for ").concat(m.videoTrack.sid)),yield this.publishAdditionalCodecForTrack(m.videoTrack,R,m.options))}}catch(R){o={error:R}}finally{try{!g&&!a&&(c=k.return)&&(yield c.call(k))}finally{if(o)throw o.error}}}else s.subscribedQualities.length>0&&(yield(h=m.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const a=this.tracks.get(s.trackSid);if(!a){f.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:s.trackSid});return}this.unpublishTrack(a.track)},this.handleTrackEnded=s=>p(this,void 0,void 0,function*(){if(s.source===y.Source.ScreenShare||s.source===y.Source.ScreenShareAudio)f.debug("unpublishing local track due to TrackEnded",{track:s.sid}),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(s instanceof ee||s instanceof re)try{if(ne())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:s.source===y.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw f.warn("user has revoked access to ".concat(s.source)),a.onchange=()=>{a.state!=="denied"&&(s.isMuted||s.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(f.debug("track ended, attempting to use a different device"),yield s.restartTrack())}catch{f.warn("could not restart track, muting instead"),yield s.mute()}}),this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==K.NONE}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(P.RemoteMute,(t,n)=>{const r=this.tracks.get(t);!r||!r.track||(n?r.mute():r.unmute())}),this.engine.on(P.Connected,this.handleReconnected).on(P.SignalRestarted,this.handleReconnected).on(P.SignalResumed,this.handleReconnected).on(P.Restarting,this.handleReconnecting).on(P.Resuming,this.handleReconnecting).on(P.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(P.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(P.Disconnected,this.handleDisconnected)}setMetadata(e){var t;this.engine.client.sendUpdateLocalMetadata(e,(t=this.name)!==null&&t!==void 0?t:"")}setName(e){var t;this.engine.client.sendUpdateLocalMetadata((t=this.metadata)!==null&&t!==void 0?t:"",e)}setCameraEnabled(e,t,n){return this.setTrackEnabled(y.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(y.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(y.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(E.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?K.GCM:K.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,r){var s,a;return p(this,void 0,void 0,function*(){f.debug("setTrackEnabled",{source:e,enabled:t});let o=this.getTrack(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){f.info("skipping duplicate published source",{source:e});return}this.pendingPublishing.add(e);try{switch(e){case y.Source.Camera:c=yield this.createTracks({video:(s=n)!==null&&s!==void 0?s:!0});break;case y.Source.Microphone:c=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case y.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new be(e)}const d=[];for(const h of c)f.info("publishing track",{localTrack:h}),d.push(this.publishTrack(h,r));[o]=yield Promise.all(d)}catch(d){throw c==null||c.forEach(u=>{u.stop()}),d instanceof Error&&!(d instanceof be)&&this.emit(E.MediaDevicesError,d),d}finally{this.pendingPublishing.delete(e)}}else if(o&&o.track)if(e===y.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrack(y.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(y.Source.Camera)||this.pendingPublishing.has(y.Source.Microphone))){this.pendingPublishing.add(y.Source.Camera),this.pendingPublishing.add(y.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(y.Source.Camera),this.pendingPublishing.delete(y.Source.Microphone)}}})}createTracks(e){var t,n;return p(this,void 0,void 0,function*(){const r=ys(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults),s=Mi(r);let a;try{a=yield navigator.mediaDevices.getUserMedia(s)}catch(o){throw o instanceof Error&&(s.audio&&(this.microphoneError=o),s.video&&(this.cameraError=o)),o}return s.audio&&(this.microphoneError=void 0,this.emit(E.AudioStreamAcquired)),s.video&&(this.cameraError=void 0),a.getTracks().map(o=>{const c=o.kind==="audio";c?e.audio:e.video;let d;const u=c?s.audio:s.video;typeof u!="boolean"&&(d=u);const h=Ds(o,d);return h.kind===y.Kind.Video?h.source=y.Source.Camera:h.kind===y.Kind.Audio&&(h.source=y.Source.Microphone),h.mediaStream=a,h})})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new yn("getDisplayMedia not supported");const t=so(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new be("no video track found");const s=new re(r[0],void 0,!1);s.source=y.Source.ScreenShare;const a=[s];if(n.getAudioTracks().length>0){this.emit(E.AudioStreamAcquired);const o=new ee(n.getAudioTracks()[0],void 0,!1,this.audioContext);o.source=y.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){var n,r,s,a;return p(this,void 0,void 0,function*(){yield(n=this.reconnectFuture)===null||n===void 0?void 0:n.promise,e instanceof ci&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e));let o;if(e instanceof MediaStreamTrack)o=e.getConstraints();else{o=e.constraints;let g;switch(e.source){case y.Source.Microphone:g="audioinput";break;case y.Source.Camera:g="videoinput"}g&&this.activeDeviceMap.has(g)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(g)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new ee(e,o,!0,this.audioContext);break;case"video":e=new re(e,o,!0);break;default:throw new be("unsupported MediaStreamTrack kind ".concat(e.kind))}e instanceof ee&&e.setAudioContext(this.audioContext);let c;if(this.tracks.forEach(g=>{g.track&&g.track===e&&(c=g)}),c)return f.warn("track has already been published, skipping"),c;const d="channelCount"in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,u=(r=t==null?void 0:t.forceStereo)!==null&&r!==void 0?r:d;u&&(t||(t={}),t.dtx===void 0&&f.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),t.red===void 0&&f.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(s=t.dtx)!==null&&s!==void 0||(t.dtx=!1),(a=t.red)!==null&&a!==void 0||(t.red=!1));const h=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);Nt()&&this.roomOptions.e2ee&&(f.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari"),h.simulcast=!1),h.source&&(e.source=h.source);const m=this.publish(e,h,u);this.pendingPublishPromises.set(e,m);try{return yield m}catch(g){throw g}finally{this.pendingPublishPromises.delete(e)}})}publish(e,t,n){var r,s,a,o,c,d,u,h,m,g,k,b,w;return p(this,void 0,void 0,function*(){Array.from(this.tracks.values()).find(x=>e instanceof ci&&x.source===e.source)&&e.source!==y.Source.Unknown&&f.info("publishing a second track with the same source: ".concat(e.source)),t.stopMicTrackOnMute&&e instanceof ee&&(e.stopOnMute=!0),e.source===y.Source.ScreenShare&&jt()&&(t.simulcast=!1),t.videoCodec==="av1"&&!uo()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!lo()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=hn);const I=t.videoCodec;e.on(S.Muted,this.onTrackMuted),e.on(S.Unmuted,this.onTrackUnmuted),e.on(S.Ended,this.handleTrackEnded),e.on(S.UpstreamPaused,this.onTrackUpstreamPaused),e.on(S.UpstreamResumed,this.onTrackUpstreamResumed);const B=new he({cid:e.mediaStreamTrack.id,name:t.name,type:y.kindToProto(e.kind),muted:e.isMuted,source:y.sourceToProto(e.source),disableDtx:!(!((r=t.dtx)!==null&&r!==void 0)||r),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream});let L;if(e.kind===y.Kind.Video){let x={width:0,height:0};try{x=yield e.waitForDimensions()}catch{const ke=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:oi.h720.resolution;x={width:ke.width,height:ke.height},f.error("could not determine track dimensions, using defaults",x)}B.width=x.width,B.height=x.height,e instanceof re&&(ii(I)&&(e.source===y.Source.ScreenShare&&I==="vp9"&&(t.scalabilityMode="L1T3"),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),B.simulcastCodecs=[new le({codec:I,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:hn}),t.backupCodec&&I!==t.backupCodec.codec&&B.encryption===K.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),B.simulcastCodecs.push(new le({codec:t.backupCodec.codec,cid:""})))),L=mn(e.source===y.Source.ScreenShare,B.width,B.height,t),B.layers=ur(B.width,B.height,L,ii(t.videoCodec))}else e.kind===y.Kind.Audio&&(L=[{maxBitrate:(u=(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate)!==null&&u!==void 0?u:t.audioBitrate,priority:(m=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&m!==void 0?m:"high",networkPriority:(k=(g=t.audioPreset)===null||g===void 0?void 0:g.priority)!==null&&k!==void 0?k:"high"}]);if(!this.engine||this.engine.isClosed)throw new J("cannot publish track when not connected");const Mt=yield this.engine.addTrack(B);let Et;if(Mt.codecs.forEach(x=>{Et===void 0&&(Et=x.mimeType)}),Et&&e.kind===y.Kind.Video){const x=bs(Et);x!==I&&(f.debug("falling back to server selected codec",{codec:x}),t.videoCodec=x,L=mn(e.source===y.Source.ScreenShare,B.width,B.height,t))}const At=new Ni(e.kind,Mt,e);if(At.options=t,e.sid=Mt.sid,!this.engine.pcManager)throw new J("pcManager is not ready");if(f.debug("publishing ".concat(e.kind," with encodings"),{encodings:L,trackInfo:Mt}),e.sender=yield this.engine.createSender(e,t,L),L)if(jt()&&e.kind===y.Kind.Audio){let x;for(const D of this.engine.pcManager.publisher.getTransceivers())if(D.sender===e.sender){x=D;break}x&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:x,codec:"opus",maxbr:!((b=L[0])===null||b===void 0)&&b.maxBitrate?L[0].maxBitrate/1e3:0})}else e.codec&&ii(e.codec)&&(!((w=L[0])===null||w===void 0)&&w.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:B.cid,codec:e.codec,maxbr:L[0].maxBitrate/1e3});return yield this.engine.negotiate(),e instanceof re?e.startMonitor(this.engine.client):e instanceof ee&&e.startMonitor(),this.addTrackPublication(At),this.emit(E.LocalTrackPublished,At),At})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){var r;return p(this,void 0,void 0,function*(){if(this.encryptionType!==K.NONE)return;let s;if(this.tracks.forEach(h=>{h.track&&h.track===e&&(s=h)}),!s)throw new be("track is not published");if(!(e instanceof re))throw new be("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),n),o=Ho(e,t,a);if(!o){f.info("backup codec has been disabled, ignoring request to add additional codec for track");return}const c=e.addSimulcastTrack(t,o),d=new he({cid:c.mediaStreamTrack.id,type:y.kindToProto(e.kind),muted:e.isMuted,source:y.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=ur(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new J("cannot publish track when not connected");const u=yield this.engine.addTrack(d);yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate(),f.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:u})})}unpublishTrack(e,t){var n,r;return p(this,void 0,void 0,function*(){const s=this.getPublicationForTrack(e);if(f.debug("unpublishing track",{track:e,method:"unpublishTrack"}),!s||!s.track){f.warn("track was not unpublished because no publication was found",{track:e,method:"unpublishTrack"});return}e=s.track,e.off(S.Muted,this.onTrackMuted),e.off(S.Unmuted,this.onTrackUnmuted),e.off(S.Ended,this.handleTrackEnded),e.off(S.UpstreamPaused,this.onTrackUpstreamPaused),e.off(S.UpstreamResumed,this.onTrackUpstreamResumed),t===void 0&&(t=(r=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t&&e.stop();let a=!1;const o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentStatethis.unpublishTrack(n)))).filter(n=>n instanceof Ni)})}republishAllTracks(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return p(this,void 0,void 0,function*(){const n=[];this.tracks.forEach(r=>{r.track&&(e&&(r.options=Object.assign(Object.assign({},r.options),e)),n.push(r))}),yield Promise.all(n.map(r=>p(this,void 0,void 0,function*(){const s=r.track;yield this.unpublishTrack(s,!1),t&&!s.isMuted&&(s instanceof ee||s instanceof re)&&!s.isUserProvided&&(f.debug("restarting existing track",{track:r.trackSid}),yield s.restartTrack()),yield this.publishTrack(s,r.options)})))})}publishData(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return p(this,void 0,void 0,function*(){const r=Array.isArray(n)?n:n==null?void 0:n.destination,s=[],a=Array.isArray(n)?void 0:n.topic;r!==void 0&&r.forEach(c=>{c instanceof di?s.push(c.sid):s.push(c)});const o=new Te({kind:t,value:{case:"user",value:new Ce({participantSid:this.sid,payload:e,destinationSids:s,topic:a})}});yield this.engine.sendDataPacket(o,t)})}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var n,r;const s=this.tracks.get(t.sid);if(s){const a=s.isMuted||((r=(n=s.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(f.debug("updating server mute state after reconcile",{sid:t.sid,muted:a}),this.engine.client.sendMuteTrack(t.sid,a))}}),!0)}getPublicationForTrack(e){let t;return this.tracks.forEach(n=>{const r=n.track;r&&(e instanceof MediaStreamTrack?(r instanceof ee||r instanceof re)&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}}var O;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting"})(O||(O={}));const ec=2*1e3;class tc extends Fe.EventEmitter{constructor(e){var t,n;super(),t=this,this.state=O.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.connect=(r,s,a)=>p(this,void 0,void 0,function*(){var o;const c=yield this.disconnectLock.lock();if(this.state===O.Connected)return f.info("already connected to room ".concat(this.name)),c(),Promise.resolve();if(this.connectFuture)return c(),this.connectFuture.promise;this.setAndEmitConnectionState(O.Connecting),((o=this.regionUrlProvider)===null||o===void 0?void 0:o.getServerUrl().toString())!==r&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ln(new URL(r))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new ar(r,s):this.regionUrlProvider.updateToken(s),this.regionUrlProvider.fetchRegionSettings().catch(h=>{f.warn("could not fetch region settings",{error:h})}));const d=(h,m,g)=>p(this,void 0,void 0,function*(){var k;this.abortController&&this.abortController.abort();const b=new AbortController;this.abortController=b,c==null||c();try{yield this.attemptConnection(g??r,s,a,b),this.abortController=void 0,h()}catch(w){if(this.regionUrlProvider&&w instanceof _&&w.reason!==3&&w.reason!==0){let R=null;try{R=yield this.regionUrlProvider.getNextBestRegionUrl((k=this.abortController)===null||k===void 0?void 0:k.signal)}catch(I){if(I instanceof _&&(I.status===401||I.reason===3)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(I);return}}R?(f.info("Initial connection failed with ConnectionError: ".concat(w.message,". Retrying with another region: ").concat(R)),yield d(h,m,R)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(w))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(w)}}),u=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Es((h,m)=>{d(h,m,u)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(r,s,a,o,c,d)=>p(this,void 0,void 0,function*(){const u=yield a.join(r,s,{autoSubscribe:o.autoSubscribe,publishOnly:o.publishOnly,adaptiveStream:typeof c.adaptiveStream=="object"?!0:c.adaptiveStream,maxRetries:o.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:o.websocketTimeout},d.signal);let h=u.serverInfo;if(h||(h={version:u.serverVersion,region:u.serverRegion}),f.debug("connected to Livekit Server ".concat(Object.entries(h).map(m=>{let[g,k]=m;return"".concat(g,": ").concat(k)}).join(", "))),!u.serverVersion)throw new Ha("unknown server version");return u.serverVersion==="0.15.1"&&this.options.dynacast&&(f.debug("disabling dynacast due to server version"),c.dynacast=!1),u}),this.applyJoinResponse=r=>{const s=r.participant;this.localParticipant.sid=s.sid,this.localParticipant.identity=s.identity,this.handleParticipantUpdates([s,...r.otherParticipants]),r.room&&this.handleRoomUpdate(r.room),this.options.e2ee&&this.e2eeManager&&this.e2eeManager.setSifTrailer(r.sifTrailer)},this.attemptConnection=(r,s,a,o)=>p(this,void 0,void 0,function*(){var c,d;this.state===O.Reconnecting?(f.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),!((c=this.regionUrlProvider)===null||c===void 0)&&c.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Sn),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const u=yield this.connectSignal(r,s,this.engine,this.connOptions,this.options,o);this.applyJoinResponse(u),this.setupLocalParticipantEvents(),this.emit(T.SignalConnected)}catch(u){yield this.engine.close(),this.recreateEngine();const h=new _("could not establish signal connection");throw u instanceof Error&&(h.message="".concat(h.message,": ").concat(u.message)),u instanceof _&&(h.reason=u.reason,h.status=u.status),f.debug("error trying to establish signal connection",{error:u}),h}if(o.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new _("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,o)}catch(u){throw yield this.engine.close(),this.recreateEngine(),u}ne()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ne()&&(document.addEventListener("freeze",this.onPageLeave),(d=navigator.mediaDevices)===null||d===void 0||d.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(O.Connected),this.emit(T.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return p(t,void 0,void 0,function*(){var s,a,o,c;const d=yield this.disconnectLock.lock();try{if(this.state===O.Disconnected){f.debug("already disconnected");return}f.info("disconnect from room",{identity:this.localParticipant.identity}),(this.state===O.Connecting||this.state===O.Reconnecting)&&(f.warn("abort connection attempt"),(s=this.abortController)===null||s===void 0||s.abort(),(o=(a=this.connectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,new _("Client initiated disconnect")),this.connectFuture=void 0),!((c=this.engine)===null||c===void 0)&&c.client.isDisconnected||(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(r,ht.CLIENT_INITIATED),this.engine=void 0}finally{d()}})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const r=[],s=Ct();if(s&&s.os==="iOS"){const a="livekit-dummy-audio-el";let o=document.getElementById(a);if(!o){o=document.createElement("audio"),o.id=a,o.autoplay=!0,o.hidden=!0;const c=Ji();c.enabled=!0;const d=new MediaStream([c]);o.srcObject=d,document.addEventListener("visibilitychange",()=>{o&&(o.srcObject=document.hidden?null:d)}),document.body.append(o),this.once(T.Disconnected,()=>{o==null||o.remove()})}r.push(o)}this.participants.forEach(a=>{a.audioTracks.forEach(o=>{o.track&&o.track.attachedElements.forEach(c=>{r.push(c)})})});try{yield Promise.all([this.acquireAudioContext(),...r.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const r=[];for(const s of this.participants.values())s.videoTracks.forEach(a=>{var o;(o=a.track)===null||o===void 0||o.attachedElements.forEach(c=>{r.includes(c)||r.push(c)})});yield Promise.all(r.map(s=>s.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(s=>{s.name==="NotAllowedError"?this.handleVideoPlaybackFailed():f.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile();for(const r of this.participants.values())this.handleParticipantDisconnected(r.sid,r);this.setAndEmitConnectionState(O.Reconnecting)&&this.emit(T.Reconnecting)},this.handleSignalRestarted=r=>p(this,void 0,void 0,function*(){f.debug("signal reconnected to server",{region:r.serverRegion}),this.cachedParticipantSids=[],this.applyJoinResponse(r);try{const s=[];this.localParticipant.tracks.forEach(a=>{a.track&&s.push(a)}),yield Promise.all(s.map(a=>p(this,void 0,void 0,function*(){const o=a.track;this.localParticipant.unpublishTrack(o,!1),o.isMuted||((o instanceof ee||o instanceof re)&&o.source!==y.Source.ScreenShare&&o.source!==y.Source.ScreenShareAudio&&!o.isUserProvided&&(f.debug("restarting existing track",{track:a.trackSid}),yield o.restartTrack()),f.debug("publishing new track",{track:a.trackSid}),yield this.localParticipant.publishTrack(o,a.options))})))}catch(s){f.error("error trying to re-publish tracks after reconnection",{error:s})}try{yield this.engine.waitForRestarted(),f.debug("fully reconnected to server",{region:r.serverRegion})}catch{return}this.setAndEmitConnectionState(O.Connected),this.emit(T.Reconnected),this.registerConnectionReconcile(),this.participants.forEach(s=>{this.emit(T.ParticipantConnected,s)})}),this.handleParticipantUpdates=r=>{r.forEach(s=>{if(s.identity===this.localParticipant.identity){this.localParticipant.updateInfo(s);return}const a=this.identityToSid.get(s.identity);a&&a!==s.sid&&this.handleParticipantDisconnected(a,this.participants.get(a));let o=this.participants.get(s.sid);const c=!o;s.state===Rt.DISCONNECTED?this.handleParticipantDisconnected(s.sid,o):(o=this.getOrCreateParticipant(s.sid,s),c||o.updateInfo(s))})},this.handleActiveSpeakersUpdate=r=>{const s=[],a={};r.forEach(o=>{if(a[o.sid]=!0,o.sid===this.localParticipant.sid)this.localParticipant.audioLevel=o.level,this.localParticipant.setIsSpeaking(!0),s.push(this.localParticipant);else{const c=this.participants.get(o.sid);c&&(c.audioLevel=o.level,c.setIsSpeaking(!0),s.push(c))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach(o=>{a[o.sid]||(o.audioLevel=0,o.setIsSpeaking(!1))}),this.activeSpeakers=s,this.emitWhenConnected(T.ActiveSpeakersChanged,s)},this.handleSpeakersChanged=r=>{const s=new Map;this.activeSpeakers.forEach(o=>{s.set(o.sid,o)}),r.forEach(o=>{let c=this.participants.get(o.sid);o.sid===this.localParticipant.sid&&(c=this.localParticipant),c&&(c.audioLevel=o.level,c.setIsSpeaking(o.active),o.active?s.set(o.sid,c):s.delete(o.sid))});const a=Array.from(s.values());a.sort((o,c)=>c.audioLevel-o.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(T.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=r=>{r.streamStates.forEach(s=>{const a=this.participants.get(s.participantSid);if(!a)return;const o=a.getTrackPublication(s.trackSid);!o||!o.track||(o.track.streamState=y.streamStateFromProto(s.state),a.emit(E.TrackStreamStateChanged,o,o.track.streamState),this.emitWhenConnected(T.TrackStreamStateChanged,o,o.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=r=>{const s=this.participants.get(r.participantSid);if(!s)return;const a=s.getTrackPublication(r.trackSid);a&&a.setAllowed(r.allowed)},this.handleSubscriptionError=r=>{const s=Array.from(this.participants.values()).find(o=>o.tracks.has(r.trackSid));if(!s)return;const a=s.getTrackPublication(r.trackSid);a&&a.setSubscriptionError(r.err)},this.handleDataPacket=(r,s)=>{const a=this.participants.get(r.participantSid);this.emit(T.DataReceived,r.payload,a,s,r.topic),a==null||a.emit(E.DataReceived,r.payload,s)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(T.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=r=>{f.warn("could not playback audio",r),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(T.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(T.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(T.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){this.emit(T.MediaDevicesChanged)}),this.handleRoomUpdate=r=>{const s=this.roomInfo;this.roomInfo=r,s&&s.metadata!==r.metadata&&this.emitWhenConnected(T.RoomMetadataChanged,r.metadata),(s==null?void 0:s.activeRecording)!==r.activeRecording&&this.emitWhenConnected(T.RecordingStatusChanged,r.activeRecording)},this.handleConnectionQualityUpdate=r=>{r.updates.forEach(s=>{if(s.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(s.quality);return}const a=this.participants.get(s.participantSid);a&&a.setConnectionQuality(s.quality)})},this.onLocalParticipantMetadataChanged=r=>{this.emit(T.ParticipantMetadataChanged,r,this.localParticipant)},this.onLocalParticipantNameChanged=r=>{this.emit(T.ParticipantNameChanged,r,this.localParticipant)},this.onLocalTrackMuted=r=>{this.emit(T.TrackMuted,r,this.localParticipant)},this.onLocalTrackUnmuted=r=>{this.emit(T.TrackUnmuted,r,this.localParticipant)},this.onLocalTrackPublished=r=>p(this,void 0,void 0,function*(){var s;this.emit(T.LocalTrackPublished,r,this.localParticipant),r.track instanceof ee&&(yield r.track.checkForSilence())&&this.emit(T.LocalAudioSilenceDetected,r);const a=yield(s=r.track)===null||s===void 0?void 0:s.getDeviceId(),o=ro(r.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(T.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=r=>{this.emit(T.LocalTrackUnpublished,r,this.localParticipant)},this.onLocalConnectionQualityChanged=r=>{this.emit(T.ConnectionQualityChanged,r,this.localParticipant)},this.onMediaDevicesError=r=>{this.emit(T.MediaDevicesError,r)},this.onLocalParticipantPermissionsChanged=r=>{this.emit(T.ParticipantPermissionsChanged,r,this.localParticipant)},this.setMaxListeners(100),this.participants=new Map,this.cachedParticipantSids=[],this.identityToSid=new Map,this.options=Object.assign(Object.assign({},xo),e),this.options.audioCaptureDefaults=Object.assign(Object.assign({},Is),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Ns),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},_o),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new ve,this.localParticipant=new hr("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Pt(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Pt(this.options.audioCaptureDefaults.deviceId)),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&this.switchActiveDevice("audiooutput",Pt(this.options.audioOutput.deviceId)).catch(r=>f.warn("Could not set audio output: ".concat(r.message))),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&(this.e2eeManager=new To(this.options.e2ee),this.e2eeManager.on(bt.ParticipantEncryptionStatusChanged,(t,n)=>{n instanceof hr&&(this.isE2EEEnabled=t),this.emit(T.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(bt.EncryptionError,t=>this.emit(T.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}get sid(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.sid)!==null&&t!==void 0?t:""}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Bo(this.options),this.engine.on(P.ParticipantUpdate,this.handleParticipantUpdates).on(P.RoomUpdate,this.handleRoomUpdate).on(P.SpeakersChanged,this.handleSpeakersChanged).on(P.StreamStateChanged,this.handleStreamStateUpdate).on(P.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(P.SubscriptionError,this.handleSubscriptionError).on(P.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(P.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(P.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(P.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(P.DataPacketReceived,this.handleDataPacket).on(P.Resuming,()=>{this.clearConnectionReconcile(),this.setAndEmitConnectionState(O.Reconnecting)&&this.emit(T.Reconnecting),this.cachedParticipantSids=Array.from(this.participants.keys())}).on(P.Resumed,()=>{this.setAndEmitConnectionState(O.Connected),this.emit(T.Reconnected),this.registerConnectionReconcile(),this.updateSubscriptions(),Array.from(this.participants.values()).filter(t=>!this.cachedParticipantSids.includes(t.sid)).forEach(t=>this.emit(T.ParticipantConnected,t)),this.cachedParticipantSids=[]}).on(P.SignalResumed,()=>{this.state===O.Reconnecting&&this.sendSyncState()}).on(P.Restarting,this.handleRestarting).on(P.SignalRestarted,this.handleSignalRestarted).on(P.DCBufferStatusChanged,(e,t)=>{this.emit(T.DCBufferStatusChanged,e,t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return X.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===O.Disconnected){f.debug("prepareConnection to ".concat(e));try{if(ln(new URL(e))&&t){this.regionUrlProvider=new ar(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===O.Disconnected&&(this.regionUrl=n,yield fetch(Qn(n),{method:"HEAD"}),f.debug("prepared connection to ".concat(n)))}else yield fetch(Qn(e),{method:"HEAD"})}catch(n){f.warn("could not prepare connection",{error:n})}}})}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);if(t)return this.participants.get(t)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let n=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new Q({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Q({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Q({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Q({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new Q({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>p(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new oe({reason:ht.CLIENT_INITIATED,canReconnect:!0}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Q({scenario:{case:"subscriberBandwidth",value:BigInt(t)}});break}r&&(this.engine.client.sendSimulateScenario(r),n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveAudioOutputDevice(){var e,t;return(t=(e=this.options.audioOutput)===null||e===void 0?void 0:e.deviceId)!==null&&t!==void 0?t:""}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;var r,s,a;return p(this,void 0,void 0,function*(){let o=!1,c=!0;const d=n?{exact:t}:t;if(e==="audioinput"){const u=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=d,o=u!==d;const h=Array.from(this.localParticipant.audioTracks.values()).filter(m=>m.source===y.Source.Microphone);try{c=(yield Promise.all(h.map(m=>{var g;return(g=m.audioTrack)===null||g===void 0?void 0:g.setDeviceId(d)}))).every(m=>m===!0)}catch(m){throw this.options.audioCaptureDefaults.deviceId=u,m}}else if(e==="videoinput"){const u=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=d,o=u!==d;const h=Array.from(this.localParticipant.videoTracks.values()).filter(m=>m.source===y.Source.Camera);try{c=(yield Promise.all(h.map(m=>{var g;return(g=m.videoTrack)===null||g===void 0?void 0:g.setDeviceId(d)}))).every(m=>m===!0)}catch(m){throw this.options.videoCaptureDefaults.deviceId=u,m}}else if(e==="audiooutput"){if(!un()&&!this.options.expWebAudioMix||this.options.expWebAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");(r=(a=this.options).audioOutput)!==null&&r!==void 0||(a.audioOutput={});const u=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t,o=u!==d;try{this.options.expWebAudioMix?(s=this.audioContext)===null||s===void 0||s.setSinkId(t):yield Promise.all(Array.from(this.participants.values()).map(h=>h.setAudioOutput({deviceId:t})))}catch(h){throw this.options.audioOutput.deviceId=u,h}}return o&&c&&(this.localParticipant.activeDeviceMap.set(e,t),this.emit(T.ActiveDeviceChanged,e,t)),c})}setupLocalParticipantEvents(){this.localParticipant.on(E.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(E.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(E.TrackMuted,this.onLocalTrackMuted).on(E.TrackUnmuted,this.onLocalTrackUnmuted).on(E.LocalTrackPublished,this.onLocalTrackPublished).on(E.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(E.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(E.MediaDevicesError,this.onMediaDevicesError).on(E.AudioStreamAcquired,this.startAudio).on(E.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===O.Connecting||this.state===O.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),h()},h=()=>{this.off(T.Reconnected,u),this.off(T.Connected,u),this.off(T.Disconnected,h)};this.once(T.Reconnected,u),this.once(T.Connected,u),this.once(T.Disconnected,h);return}if(this.state===O.Disconnected){f.warn("skipping incoming track after Room disconnected");return}const r=co(t.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){f.warn("tried to create RemoteParticipant for local participant");return}const c=this.participants.get(s);if(!c){f.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s));return}let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={}),c.addSubscribedMediaTrack(e,o,t,n,d)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.state!==O.Disconnected){this.regionUrl=void 0;try{this.participants.forEach(r=>{r.tracks.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.tracks.forEach(r=>{var s,a;r.track&&this.localParticipant.unpublishTrack(r.track,e),e&&((s=r.track)===null||s===void 0||s.detach(),(a=r.track)===null||a===void 0||a.stop())}),this.localParticipant.off(E.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(E.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(E.TrackMuted,this.onLocalTrackMuted).off(E.TrackUnmuted,this.onLocalTrackUnmuted).off(E.LocalTrackPublished,this.onLocalTrackPublished).off(E.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(E.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(E.MediaDevicesError,this.onMediaDevicesError).off(E.AudioStreamAcquired,this.startAudio).off(E.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.expWebAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),ne()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(O.Disconnected),this.emit(T.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.participants.delete(e),t&&(this.identityToSid.delete(t.identity),t.tracks.forEach(n=>{t.unpublishTrack(n.trackSid,!0)}),this.emit(T.ParticipantDisconnected,t))}acquireAudioContext(){var e,t;return p(this,void 0,void 0,function*(){if(typeof this.options.expWebAudioMix!="boolean"&&this.options.expWebAudioMix.audioContext?this.audioContext=this.options.expWebAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=ks())!==null&&e!==void 0?e:void 0),this.audioContext&&this.audioContext.state==="suspended")try{yield this.audioContext.resume()}catch(r){f.warn(r)}this.options.expWebAudioMix&&this.participants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext);const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(T.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let r;return t?r=di.fromParticipantInfo(this.engine.client,t):r=new di(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&r.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>f.warn("Could not set audio output: ".concat(s.message))),r}getOrCreateParticipant(e,t){if(this.participants.has(e))return this.participants.get(e);const n=this.createParticipant(e,t);return this.participants.set(e,n),this.identityToSid.set(t.identity,t.sid),this.emitWhenConnected(T.ParticipantConnected,n),n.on(E.TrackPublished,r=>{this.emitWhenConnected(T.TrackPublished,r,n)}).on(E.TrackSubscribed,(r,s)=>{r.kind===y.Kind.Audio?(r.on(S.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(S.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===y.Kind.Video&&(r.on(S.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(S.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(T.TrackSubscribed,r,s,n)}).on(E.TrackUnpublished,r=>{this.emit(T.TrackUnpublished,r,n)}).on(E.TrackUnsubscribed,(r,s)=>{this.emit(T.TrackUnsubscribed,r,s,n)}).on(E.TrackSubscriptionFailed,r=>{this.emit(T.TrackSubscriptionFailed,r,n)}).on(E.TrackMuted,r=>{this.emitWhenConnected(T.TrackMuted,r,n)}).on(E.TrackUnmuted,r=>{this.emitWhenConnected(T.TrackUnmuted,r,n)}).on(E.ParticipantMetadataChanged,r=>{this.emitWhenConnected(T.ParticipantMetadataChanged,r,n)}).on(E.ParticipantNameChanged,r=>{this.emitWhenConnected(T.ParticipantNameChanged,r,n)}).on(E.ConnectionQualityChanged,r=>{this.emitWhenConnected(T.ConnectionQualityChanged,r,n)}).on(E.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(T.ParticipantPermissionsChanged,r,n)}).on(E.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(T.TrackSubscriptionStatusChanged,r,s,n)}).on(E.TrackSubscriptionFailed,(r,s)=>{this.emit(T.TrackSubscriptionFailed,r,n,s)}).on(E.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(T.TrackSubscriptionPermissionChanged,r,s,n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.participants.values()).reduce((n,r)=>(n.push(...r.getTracks()),n),[]),t=this.localParticipant.getTracks();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.participants.values())for(const t of e.videoTracks.values())t.isSubscribed&&t instanceof _s&&t.emitTrackUpdate()}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=H.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,f.warn("detected connection state mismatch",{numFailures:e}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ht.STATE_MISMATCH))):e=0},ec)}clearConnectionReconcile(){this.connectionReconcileInterval&&H.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(T.ConnectionStateChanged,this.state),!0)}emitWhenConnected(e){if(this.state===O.Connected){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r1?t-1:0),r=1;r2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=de.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new tc(n.roomOptions),this.connectOptions=n.connectOptions,n.errorsAsWarnings&&(this.errorsAsWarnings=n.errorsAsWarnings)}run(e){return p(this,void 0,void 0,function*(){if(this.status!==de.IDLE)throw Error("check is running already");this.setStatus(de.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==de.SKIPPED&&this.setStatus(this.isSuccess()?de.SUCCESS:de.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(){return p(this,void 0,void 0,function*(){return this.room.state===O.Connected?this.room:(yield this.room.connect(this.url,this.token),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==O.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(de.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function xs(i){var e,t;return p(this,void 0,void 0,function*(){i??(i={}),(e=i.audio)!==null&&e!==void 0||(i.audio=!0),(t=i.video)!==null&&t!==void 0||(i.video=!0);const n=ys(i,Is,Ns),r=Mi(n),s=navigator.mediaDevices.getUserMedia(r);i.audio&&(X.userMediaPromiseMap.set("audioinput",s),s.catch(()=>X.userMediaPromiseMap.delete("audioinput"))),i.video&&(X.userMediaPromiseMap.set("videoinput",s),s.catch(()=>X.userMediaPromiseMap.delete("videoinput")));const a=yield s;return a.getTracks().map(o=>{const c=o.kind==="audio";c?i.audio:i.video;let d;const u=c?r.audio:r.video;typeof u!="boolean"&&(d=u),d?d.deviceId=o.getSettings().deviceId:d={deviceId:o.getSettings().deviceId};const h=Ds(o,d);return h.kind===y.Kind.Video?h.source=y.Source.Camera:h.kind===y.Kind.Audio&&(h.source=y.Source.Microphone),h.mediaStream=a,h})})}function ic(i){return p(this,void 0,void 0,function*(){return(yield xs({audio:!1,video:i}))[0]})}function nc(i){return p(this,void 0,void 0,function*(){return(yield xs({audio:i,video:!1}))[0]})}class rc extends Kt{get description(){return"Can publish audio"}perform(){var e;return p(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield nc();t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&a.mediaType==="audio"&&(s=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class sc extends Kt{get description(){return"Can publish video"}perform(){var e;return p(this,void 0,void 0,function*(){const t=yield this.connect(),n=yield ic();t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&a.mediaType==="video"&&(s=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}}class ac extends Kt{get description(){return"Resuming connection after interruption"}perform(){var e;return p(this,void 0,void 0,function*(){const t=yield this.connect();let n=!1,r=!1,s;const a=new Promise(c=>{setTimeout(c,5e3),s=c});t.on(T.Reconnecting,()=>{n=!0}).on(T.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const o=t.engine.client.onClose;if(o&&o(""),yield a,n){if(!r||t.state!==O.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class oc extends Kt{get description(){return"Can connect via TURN"}perform(){var e,t;return p(this,void 0,void 0,function*(){const n=new Tn,r=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,a=!1,o=!1;for(let c of r.iceServers)for(let d of c.urls)d.startsWith("turn:")?(a=!0,o=!0):d.startsWith("turns:")&&(a=!0,o=!0,s=!0),d.startsWith("stun:")&&(o=!0);o?a&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class cc extends Kt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(T.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const a=new RTCIceCandidate(r);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(dc(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),f.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function dc(i){const e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class uc extends Kt{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,n;return p(this,void 0,void 0,function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Tn;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===Vt.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=s.serverInfo)===null||n===void 0?void 0:n.region)),yield r.close()})}}class hc extends Fe.EventEmitter{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:de.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==de.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token),r=a=>{this.updateCheck(t,a)};n.on("update",r);const s=yield n.run();return n.off("update",r),s})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(uc)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(cc)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(oc)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(ac)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(rc)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(sc)})}}export{O as C,hr as L,Pi as M,E as P,T as R,y as T,ri as a,_s as b,tc as c};