PageSourceSearch

https://innovationskonferenz-wien.at/_next/static/chunks/3zqdl8v1vojla.js

js innovationskonferenz-wien.at collected 2026-10-05 20:13:18 UTC 471,048 bytes, 4 lines download raw bytes

1;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="a78c52f5-23bf-a9a9-052f-b052728ef4fe")}catch(e){}}();
2(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,899183,e=>{"use strict";let t,i,n,r,a;var s,o,c,l,d,u,h,p,m,g,f,v,b,k,y,T,S,C,E,w,P,R,I,D,_,O,M,x,A,N,L,U,j,F,B,q,V,H,W,G,z,K,J,Q,Y,X,Z,$,ee,et,ei,en,er,ea,es,eo,ec,el,ed,eu,eh,ep,em,eg,ef,ev,eb,ek,ey,eT,eS,eC,eE,ew,eP,eR,eI,eD,e_,eO,eM,ex,eA,eN,eL,eU,ej,eF,eB,eq,eV,eH,eW,eG,ez,eK,eJ=e.i(400726);try{var eQ="u">typeof window?window:e.g;eQ._sentryModuleMetadata=eQ._sentryModuleMetadata||{},eQ._sentryModuleMetadata[(new eQ.Error).stack]=Object.assign({},eQ._sentryModuleMetadata[(new eQ.Error).stack],{"_sentryBundlerPluginAppKey:sentry-b2match-next-app":!0})}catch(e){}var eY=Object.defineProperty,eX=(e,t,i)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?eY(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i};class eZ{constructor(){eX(this,"_locking"),eX(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;let t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function e$(e,t){if(!e)throw Error(t)}function e0(e){if("number"!=typeof e)throw Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>0x7fffffff||e<-0x80000000)throw Error("invalid int 32: "+e)}function e1(e){if("number"!=typeof e)throw Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>0xffffffff||e<0)throw Error("invalid uint 32: "+e)}function e2(e){if("number"!=typeof e)throw Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error("invalid float 32: "+e)}let e3=Symbol("@bufbuild/protobuf/enum-type");function e4(e,t,i,n){e[e3]=e9(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function e9(e,t,i){let n=Object.create(null),r=Object.create(null),a=[];for(let e of t){let t=e6(e);a.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:a,findName:e=>n[e],findNumber:e=>r[e]}}function e6(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class e8{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){let i=this.getType(),n=i.runtime.json,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){let t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){let t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;return JSON.stringify(this.toJson(e),null,null!=(t=null==e?void 0:e.prettySpaces)?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function e5(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,(128&i)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}throw Error("invalid varint")}function e7(e,t,i){for(let n=0;n<28;n+=7){let r=e>>>n,a=r>>>7!=0||0!=t,s=(a?128|r:r)&255;if(i.push(s),!a)return}let n=e>>>28&15|(7&t)<<4,r=t>>3!=0;if(i.push((r?128|n:n)&255),r){for(let e=3;e<31;e+=7){let n=t>>>e,r=n>>>7!=0,a=(r?128|n:n)&255;if(i.push(a),!r)return}i.push(t>>>31&1)}}function te(e){let t="-"===e[0];t&&(e=e.slice(1));let i=0,n=0;function r(t,r){let a=Number(e.slice(t,r));n*=1e6,(i=1e6*i+a)>=0x100000000&&(n+=i/0x100000000|0,i%=0x100000000)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?tn(i,n):ti(i,n)}function tt(e,t){if({lo:e,hi:t}={lo:e>>>0,hi:t>>>0},t<=2097151)return String(0x100000000*t+e);let i=0xffffff&e,n=(e>>>24|t<<8)&0xffffff,r=t>>16&65535,a=i+6777216*n+6710656*r,s=n+8147497*r,o=2*r;return a>=1e7&&(s+=Math.floor(a/1e7),a%=1e7),s>=1e7&&(o+=Math.floor(s/1e7),s%=1e7),o.toString()+tr(s)+tr(a)}function ti(e,t){return{lo:0|e,hi:0|t}}function tn(e,t){return t=~t,e?e=~e+1:t+=1,ti(e,t)}let tr=e=>{let t=String(e);return"0000000".slice(t.length)+t};function ta(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function ts(){let e=this.buf[this.pos++],t=127&e;if((128&e)==0||(t|=(127&(e=this.buf[this.pos++]))<<7,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<14,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<21,(128&e)==0))return this.assertBounds(),t;
2t|=(15&(e=this.buf[this.pos++]))<<28;for(let t=5;(128&e)!=0&&t<10;t++)e=this.buf[this.pos++];if((128&e)!=0)throw Error("invalid varint");return this.assertBounds(),t>>>0}let to=function(){let e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof eJ.default||"object"!=typeof eJ.default.env||"1"!==eJ.default.env.BUF_BIGINT_DISABLE)){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){let n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw Error("int64 invalid: ".concat(e));return n},uParse(e){let t="bigint"==typeof e?e:BigInt(e);if(t>r||t<n)throw Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}let t=e=>e$(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>e$(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),te(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),te(e)),dec:(e,t)=>{let i,n,r;return(n=0x80000000&(i=ti(e,t)).hi)&&(i=tn(i.lo,i.hi)),r=tt(i.lo,i.hi),n?"-"+r:r},uDec:(e,t)=>tt(e,t)}}();function tc(e,t,i){if(t===i)return!0;if(e==ee.BYTES){if(!(t instanceof Uint8Array)||!(i instanceof Uint8Array)||t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case ee.UINT64:case ee.FIXED64:case ee.INT64:case ee.SFIXED64:case ee.SINT64:return t==i}return!1}function tl(e,t){switch(e){case ee.BOOL:return!1;case ee.UINT64:case ee.FIXED64:case ee.INT64:case ee.SFIXED64:case ee.SINT64:return 0==t?to.zero:"0";case ee.DOUBLE:case ee.FLOAT:return 0;case ee.BYTES:return new Uint8Array(0);case ee.STRING:return"";default:return 0}}function td(e,t){switch(e){case ee.BOOL:return!1===t;case ee.STRING:return""===t;case ee.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(s=ee||(ee={}))[s.DOUBLE=1]="DOUBLE",s[s.FLOAT=2]="FLOAT",s[s.INT64=3]="INT64",s[s.UINT64=4]="UINT64",s[s.INT32=5]="INT32",s[s.FIXED64=6]="FIXED64",s[s.FIXED32=7]="FIXED32",s[s.BOOL=8]="BOOL",s[s.STRING=9]="STRING",s[s.BYTES=12]="BYTES",s[s.UINT32=13]="UINT32",s[s.SFIXED32=15]="SFIXED32",s[s.SFIXED64=16]="SFIXED64",s[s.SINT32=17]="SINT32",s[s.SINT64=18]="SINT64",(o=et||(et={}))[o.BIGINT=0]="BIGINT",o[o.STRING=1]="STRING",(c=ei||(ei={}))[c.Varint=0]="Varint",c[c.Bit64=1]="Bit64",c[c.LengthDelimited=2]="LengthDelimited",c[c.StartGroup=3]="StartGroup",c[c.EndGroup=4]="EndGroup",c[c.Bit32=5]="Bit32";class tu{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(e1(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return e0(e),ta(e,this.buf),this}bool(e){return this.buf.push(+!!e),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){e2(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){e1(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){e0(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return e0(e),ta(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=to.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=to.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=to.enc(e);return e7(t.lo,t.hi,this.buf),this}sint64(e){let t=to.enc(e),i=t.hi>>31;return e7(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=to.uEnc(e);return e7(t.lo,t.hi,this.buf),this}}class th{constructor(e,t){this.varint64=e5,this.uint32=ts,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;
2if(t<=0||i<0||i>5)throw Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ei.Varint:for(;128&this.buf[this.pos++];);break;case ei.Bit64:this.pos+=4;case ei.Bit32:this.pos+=4;break;case ei.LengthDelimited:let n=this.uint32();this.pos+=n;break;case ei.StartGroup:for(;;){let[e,i]=this.tag();if(i===ei.EndGroup){if(void 0!==t&&e!==t)throw Error("invalid end group tag");break}this.skip(i,e)}break;default:throw Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return to.dec(...this.varint64())}uint64(){return to.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,to.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return to.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return to.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 tp(e){let t=e.field.localName,i=Object.create(null);return i[t]=function(e){let t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return tl(t.T,t.L);case"message":let i=t.T,n=new i;return i.fieldWrapper?i.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let tm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),tg=[];for(let e=0;e<tm.length;e++)tg[tm[e].charCodeAt(0)]=e;tg[45]=tm.indexOf("+"),tg[95]=tm.indexOf("/");let tf={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i=new Uint8Array(t),n=0,r=0,a,s=0;for(let t=0;t<e.length;t++){if(void 0===(a=tg[e.charCodeAt(t)]))switch(e[t]){case"=":r=0;case"\n":case"\r":case"	":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:s=a,r=1;break;case 1:i[n++]=s<<2|(48&a)>>4,s=a,r=2;break;case 2:i[n++]=(15&s)<<4|(60&a)>>2,s=a,r=3;break;case 3:i[n++]=(3&s)<<6|a,r=0}}if(1==r)throw Error("invalid base64 string.");return i.subarray(0,n)},enc(e){let t="",i=0,n,r=0;for(let a=0;a<e.length;a++)switch(n=e[a],i){case 0:t+=tm[n>>2],r=(3&n)<<4,i=1;break;case 1:t+=tm[r|n>>4],r=(15&n)<<2,i=2;break;case 2:t+=tm[r|n>>6],t+=tm[63&n],i=0}return i&&(t+=tm[r],t+="=",1==i&&(t+="=")),t}};function tv(e,t){let i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function tb(e,t){e$(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function tk(e,t){let i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":if(e.opt||e.req)return void 0!==t[i];if("enum"==e.kind)return t[i]!==e.T.values[0].no;return!td(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function ty(e,t){let i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?tl(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function tT(e,t){if(null===e||"object"!=typeof e||!Object.getOwnPropertyNames(e8.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;let i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function tS(e,t){return tT(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}ee.DOUBLE,ee.FLOAT,ee.INT64,ee.UINT64,ee.INT32,ee.UINT32,ee.BOOL,ee.STRING,ee.BYTES;let tC={ignoreUnknownFields:!1},tE={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},tw=Symbol(),tP=Symbol();function tR(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function tI(e,t,i,n,r){let a=i.localName;if(i.repeated){if(e$("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tR(t)));let s=e[a];for(let e of t){if(null===e)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tR(e)));switch(i.kind){case"message":s.push(i.T.fromJson(e,n));break;case"enum":let t=t_(i.T,e,n.ignoreUnknownFields,!0);t!==tP&&s.push(t);break;case"scalar":try{s.push(tD(i.T,e,i.L,!0))}catch(n){let t="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tR(e));throw n instanceof Error&&n.message.length>0&&(t+=": ".concat(n.message)),Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tR(t)));let s=e[a];for(let[e,a]of Object.entries(t)){let o;if(null===a)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: map value null"));try{o=function(e,t){if(e===ee.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return tD(e,t,et.BIGINT,!0).toString()}(i.K,e)}catch(n){let e="cannot decode map key for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tR(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}switch(i.V.kind){case"message":s[o]=i.V.T.fromJson(a,n);break;
2case"enum":let c=t_(i.V.T,a,n.ignoreUnknownFields,!0);c!==tP&&(s[o]=c);break;case"scalar":try{s[o]=tD(i.V.T,a,et.BIGINT,!0)}catch(n){let e="cannot decode map value for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tR(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:a},a="value"),i.kind){case"message":let s=i.T;if(null===t&&"google.protobuf.Value"!=s.typeName)return;let o=e[a];tT(o)?o.fromJson(t,n):(e[a]=o=s.fromJson(t,n),s.fieldWrapper&&!i.oneof&&(e[a]=s.fieldWrapper.unwrapField(o)));break;case"enum":let c=t_(i.T,t,n.ignoreUnknownFields,!1);switch(c){case tw:ty(i,e);break;case tP:break;default:e[a]=c}break;case"scalar":try{let n=tD(i.T,t,i.L,!1);n===tw?ty(i,e):e[a]=n}catch(n){let e="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tR(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}function tD(e,t,i,n){if(null===t)return n?tl(e,i):tw;switch(e){case ee.DOUBLE:case ee.FLOAT:if("NaN"===t)return NaN;if("Infinity"===t)return 1/0;if("-Infinity"===t)return-1/0;if(""===t||"string"==typeof t&&t.trim().length!==t.length||"string"!=typeof t&&"number"!=typeof t)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==ee.FLOAT&&e2(r),r;case ee.INT32:case ee.FIXED32:case ee.SFIXED32:case ee.SINT32:case ee.UINT32:let a;if("number"==typeof t?a=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(a=Number(t)),void 0===a)break;return e==ee.UINT32||e==ee.FIXED32?e1(a):e0(a),a;case ee.INT64:case ee.SFIXED64:case ee.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;let s=to.parse(t);return i?s.toString():s;case ee.FIXED64:case ee.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;let o=to.uParse(t);return i?o.toString():o;case ee.BOOL:if("boolean"!=typeof t)break;return t;case ee.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw Error("invalid UTF8")}return t;case ee.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return tf.dec(t)}throw Error()}function t_(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:tw;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":let r=e.findName(t);if(void 0!==r)return r.no;if(i)return tP}throw Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(tR(t)))}function tO(e,t,i){if("map"==e.kind){e$("object"==typeof t&&null!=t);let n={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(let[t,i]of r)n[t.toString()]=tx(e.V.T,i);break;case"message":for(let[e,t]of r)n[e.toString()]=t.toJson(i);break;case"enum":let a=e.V.T;for(let[e,t]of r)n[e.toString()]=tM(a,t,i.enumAsInteger)}return i.emitDefaultValues||r.length>0?n:void 0}if(e.repeated){e$(Array.isArray(t));let n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(tx(e.T,t[i]));break;case"enum":for(let r=0;r<t.length;r++)n.push(tM(e.T,t[r],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return tx(e.T,t);case"enum":return tM(e.T,t,i.enumAsInteger);case"message":return tS(e.T,t).toJson(i)}}function tM(e,t,i){var n;if(e$("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;let r=e.findNumber(t);return null!=(n=null==r?void 0:r.name)?n:t}function tx(e,t){switch(e){case ee.INT32:case ee.SFIXED32:case ee.SINT32:case ee.FIXED32:case ee.UINT32:return e$("number"==typeof t),t;case ee.FLOAT:case ee.DOUBLE:if(e$("number"==typeof t),Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";return t;case ee.STRING:return e$("string"==typeof t),t;case ee.BOOL:return e$("boolean"==typeof t),t;case ee.UINT64:case ee.FIXED64:case ee.INT64:case ee.SFIXED64:case ee.SINT64:return e$("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case ee.BYTES:return e$(t instanceof Uint8Array),tf.enc(t)}}let tA=Symbol("@bufbuild/protobuf/unknown-fields"),tN={readUnknownFields:!0,readerFactory:e=>new th(e)},tL={writeUnknownFields:!0,writerFactory:()=>new tu};function tU(e,t,i,n,r){let{repeated:a,localName:s}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=s&&delete e.value,e.case=s,s="value"),i.kind){case"scalar":case"enum":let o="enum"==i.kind?ee.INT32:i.T,c=tB;if("scalar"==i.kind&&i.L>0&&(c=tF),a){let i=e[s];if(n==ei.LengthDelimited&&o!=ee.STRING&&o!=ee.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,o))}else i.push(c(t,o))}else e[s]=c(t,o);break;case"message":let l=i.T;
2a?e[s].push(tj(t,new l,r,i)):tT(e[s])?tj(t,e[s],r,i):(e[s]=tj(t,new l,r,i),!l.fieldWrapper||i.oneof||i.repeated||(e[s]=l.fieldWrapper.unwrapField(e[s])));break;case"map":let[d,u]=function(e,t,i){let n,r,a=t.uint32(),s=t.pos+a;for(;t.pos<s;){let[a]=t.tag();switch(a){case 1:n=tB(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=tB(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=tj(t,new e.V.T,i,void 0)}}}if(void 0===n&&(n=tl(e.K,et.BIGINT)),"string"!=typeof n&&"number"!=typeof n&&(n=n.toString()),void 0===r)switch(e.V.kind){case"scalar":r=tl(e.V.T,et.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[n,r]}(i,t,r);e[s][d]=u}}function tj(e,t,i,n){let r=t.getType().runtime.bin,a=null==n?void 0:n.delimited;return r.readMessage(t,e,a?n.no:e.uint32(),i,a),t}function tF(e,t){let i=tB(e,t);return"bigint"==typeof i?i.toString():i}function tB(e,t){switch(t){case ee.STRING:return e.string();case ee.BOOL:return e.bool();case ee.DOUBLE:return e.double();case ee.FLOAT:return e.float();case ee.INT32:return e.int32();case ee.INT64:return e.int64();case ee.UINT64:return e.uint64();case ee.FIXED64:return e.fixed64();case ee.BYTES:return e.bytes();case ee.FIXED32:return e.fixed32();case ee.SFIXED32:return e.sfixed32();case ee.SFIXED64:return e.sfixed64();case ee.SINT64:return e.sint64();case ee.UINT32:return e.uint32();case ee.SINT32:return e.sint32()}}function tq(e,t,i,n){e$(void 0!==t);let r=e.repeated;switch(e.kind){case"scalar":case"enum":let a="enum"==e.kind?ee.INT32:e.T;if(r)if(e$(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,ei.LengthDelimited).fork();let[,r]=tW(t);for(let t=0;t<n.length;t++)e[r](n[t]);e.join()}(i,a,e.no,t);else for(let n of t)tH(i,a,e.no,n);else tH(i,a,e.no,t);break;case"message":if(r)for(let r of(e$(Array.isArray(t)),t))tV(i,n,e,r);else tV(i,n,e,t);break;case"map":for(let[r,a]of(e$("object"==typeof t&&null!=t),Object.entries(t)))!function(e,t,i,n,r){e.tag(i.no,ei.LengthDelimited),e.fork();let a=n;switch(i.K){case ee.INT32:case ee.FIXED32:case ee.UINT32:case ee.SFIXED32:case ee.SINT32:a=Number.parseInt(n);break;case ee.BOOL:e$("true"==n||"false"==n),a="true"==n}switch(tH(e,i.K,1,a),i.V.kind){case"scalar":tH(e,i.V.T,2,r);break;case"enum":tH(e,ee.INT32,2,r);break;case"message":e$(void 0!==r),e.tag(2,ei.LengthDelimited).bytes(r.toBinary(t))}e.join()}(i,n,e,r,a)}}function tV(e,t,i,n){let r=tS(i.T,n);i.delimited?e.tag(i.no,ei.StartGroup).raw(r.toBinary(t)).tag(i.no,ei.EndGroup):e.tag(i.no,ei.LengthDelimited).bytes(r.toBinary(t))}function tH(e,t,i,n){e$(void 0!==n);let[r,a]=tW(t);e.tag(i,r)[a](n)}function tW(e){let t=ei.Varint;switch(e){case ee.BYTES:case ee.STRING:t=ei.LengthDelimited;break;case ee.DOUBLE:case ee.FIXED64:case ee.SFIXED64:t=ei.Bit64;break;case ee.FIXED32:case ee.SFIXED32:case ee.FLOAT:t=ei.Bit32}return[t,ee[e].toLowerCase()]}function tG(e){if(void 0===e)return e;if(tT(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function tz(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class tK{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){let e;this.members=[];let t=this.members;for(let i of this.list())i.oneof?i.oneof!==e&&(e=i.oneof,t.push(e)):t.push(i)}return this.members}}function tJ(e,t){let i=tY(e);return t?i:t0(t$(i))}let tQ=tY;function tY(e){let t=!1,i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}let tX=new Set(["constructor","toString","toJSON","valueOf"]),tZ=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),t$=e=>{if(tZ.has(e))return"".concat(e,"$");return e},t0=e=>{if(tX.has(e))return"".concat(e,"$");return e};class t1{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=function(e){return tJ(e,!1)}(e)}addField(e){e$(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}let t2=(l=e=>new tK(e,e=>(function(e){var t,i,n,r,a,s;let o,c=[];for(let l of"function"==typeof e?e():e){if(l.localName=tJ(l.name,void 0!==l.oneof),l.jsonName=null!=(t=l.jsonName)?t:tQ(l.name),l.repeated=null!=(i=l.repeated)&&i,"scalar"==l.kind&&(l.L=null!=(n=l.L)?n:et.BIGINT),l.delimited=null!=(r=l.delimited)&&r,l.req=null!=(a=l.req)&&a,l.opt=null!=(s=l.opt)&&s,void 0===l.packed&&(l.packed="enum"==l.kind||"scalar"==l.kind&&l.T!=ee.BYTES&&l.T!=ee.STRING),void 0!==l.oneof){let e="string"==typeof l.oneof?l.oneof:l.oneof.name;o&&o.name==e||(o=new t1(e)),l.oneof=o,o.addField(l)}c.push(l)}return c})(e)),d=e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let i=t.localName;if(t.repeated){e[i]=[];continue}switch(t.kind){case"oneof":e[i]={case:void 0};break;case"enum":e[i]=0;break;case"map":e[i]={};break;case"scalar":e[i]=tl(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},tC),e):tC},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},tE),e):tE},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(tR(t)));n=null!=n?n:new e;let r=new Map,a=i.typeRegistry;for(let[s,o]of Object.entries(t)){let t=e.fields.findJsonName(s);if(t){if(t.oneof){if(null===o&&"scalar"==t.kind)continue;let i=r.get(t.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(s,'"'));r.set(t.oneof,s)}tI(n,o,t,i,e)}else{let t=!1;if((null==a?void 0:a.findExtension)&&s.startsWith("[")&&s.endsWith("]")){let r=a.findExtension(s.substring(1,s.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;let[e,a]=tp(r);tI(e,o,r.field,i,r),function(e,t,i,n){tb(t,e);let r=t.runtime.bin.makeReadOptions(n),a=t.runtime.bin.makeWriteOptions(n);if(tv(e,t)){let i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);for(let t of(e.getType().runtime.bin.discardUnknownFields(e),i))e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let s=a.writerFactory(),o=t.field;o.opt||o.repeated||"enum"!=o.kind&&"scalar"!=o.kind||(o=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(o,i,s,a);let c=r.readerFactory(s.finish());for(;c.pos<c.len;){let[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}(n,r,a(),i)}}if(!t&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(s,'" is unknown'))}}return n},writeMessage(e,t){let i,n=e.getType(),r={};try{for(i of n.fields.byNumber()){if(!tk(i,e)){var a;if(i.req)throw"required field not set";if(!t.emitDefaultValues||!((a=i).repeated||"map"==a.kind||!a.oneof&&"message"!=a.kind&&!a.opt&&!
2a.req))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],s=tO(i,n,t);void 0!==s&&(r[t.useProtoFieldName?i.name:i.jsonName]=s)}let s=t.typeRegistry;if(null==s?void 0:s.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let a=s.findExtensionFor(n.typeName,i.no);if(a&&tv(e,a)){let i=function(e,t,i){tb(t,e);let n=t.runtime.bin.makeReadOptions(i),r=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,s]=tp(t);for(let e of r)t.runtime.bin.readField(a,n.readerFactory(e.data),t.field,e.wireType,n);return s()}(e,a,t),n=tO(a.field,i,t);void 0!==n&&(r[a.field.jsonName]=n)}}}catch(r){let e=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw Error(e+(t.length>0?": ".concat(t):""))}return r},readScalar:(e,t,i)=>tD(e,t,null!=i?i:et.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t&&(i||td(e,t)))return tx(e,t)},debug:tR},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},tN),e):tN},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},tL),e):tL},listUnknownFields(e){var t;return null!=(t=e[tA])?t:[]},discardUnknownFields(e){delete e[tA]},writeUnknownFields(e,t){let i=e[tA];if(i)for(let e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){Array.isArray(e[tA])||(e[tA]=[]),e[tA].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,r){let a,s,o=e.getType(),c=r?t.len:t.pos+i;for(;t.pos<c&&([a,s]=t.tag(),!0!==r||s!=ei.EndGroup);){let i=o.fields.find(a);if(!i){let i=t.skip(s,a);n.readUnknownFields&&this.onUnknownField(e,a,s,i);continue}tU(e,t,i,s,n)}if(r&&(s!=ei.EndGroup||a!==i))throw Error("invalid end group tag")},readField:tU,writeMessage(e,t,i){let n=e.getType();for(let r of n.fields.byNumber()){if(!tk(r,e)){if(r.req)throw Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}let a=r.oneof?e[r.oneof.localName].value:e[r.localName];tq(r,a,t,i)}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&tq(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:e4,initPartial(e,t){if(void 0!==e)for(let i of t.getType().fields.byMember()){let n=i.localName;if(null!=e[n])switch(i.kind){case"oneof":let r=e[n].case;if(void 0===r)continue;let a=i.findField(r),s=e[n].value;a&&"message"==a.kind&&!tT(s,a.T)?s=new a.T(s):a&&"scalar"===a.kind&&a.T===ee.BYTES&&(s=tz(s)),t[n]={case:r,value:s};break;case"scalar":case"enum":let o=e[n];i.T===ee.BYTES&&(o=i.repeated?o.map(tz):tz(o)),t[n]=o;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===ee.BYTES)for(let[i,r]of Object.entries(e[n]))t[n][i]=tz(r);else Object.assign(t[n],e[n]);break;case"message":let c=i.V.T;for(let i of Object.keys(e[n])){let r=e[n][i];c.fieldWrapper||(r=new c(r)),t[n][i]=r}}break;case"message":let l=i.T;if(i.repeated)t[n]=e[n].map(e=>tT(e,l)?e:new l(e));else{let i=e[n];l.fieldWrapper?"google.protobuf.BytesValue"===l.typeName?t[n]=tz(i):t[n]=i:t[n]=tT(i,l)?i:new l(i)}}}},equals:(e,t,i)=>t===i||!!t&&!!i&&e.fields.byMember().every(e=>{let n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,r[i]));case"scalar":return n.every((t,i)=>tc(e.T,t,r[i]));case"enum":return n.every((e,t)=>tc(ee.INT32,e,r[t]))}throw Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let a=n,s=r;return e.T.fieldWrapper&&(void 0===a||tT(a)||(a=e.T.fieldWrapper.wrapField(a)),void 0===s||tT(s)||(s=e.T.fieldWrapper.wrapField(s))),e.T.equals(a,s);case"enum":return tc(ee.INT32,n,r);case"scalar":return tc(e.T,n,r);case"oneof":if(n.case!==r.case)return!1;let o=e.findField(n.case);if(void 0===o)return!0;switch(o.kind){case"message":return o.T.equals(n.value,r.value);case"enum":return tc(ee.INT32,n.value,r.value);case"scalar":return tc(o.T,n.value,r.value)}throw Error("oneof cannot contain ".concat(o.kind));case"map":let c=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":let l=e.V.T;return c.every(e=>l.equals(n[e],r[e]));case"enum":return c.every(e=>tc(ee.INT32,n[e],r[e]));case"scalar":let d=e.V.T;return c.every(e=>tc(d,n[e],r[e]))}}}),clone(e){let t=e.getType(),i=new t;for(let n of t.fields.byMember()){let t,r=e[n.localName];if(n.repeated)t=r.map(tG);else if("map"==n.kind)for(let[e,a]of(t=i[n.localName],Object.entries(r)))t[e]=tG(a);else t="oneof"==n.kind?n.findField(r.case)?{case:r.case,value:tG(r.value)}:{case:void 0}:tG(r);i[n.localName]=t}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return i}}),{newFieldList:l,initFields:d}),makeMessageType(e,t,i){var n,r;let a,s;return n=this,Object.setPrototypeOf((s=({[a=null!=(r=null==i?void 0:i.localName)?r:e.substring(e.lastIndexOf(".")+1)]:function(e){n.util.initFields(this),n.util.initPartial(e,this)}})[a]).prototype,new e8),Object.assign(s,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary:(e,t)=>new s().fromBinary(e,t),fromJson:(e,t)=>new s().fromJson(e,t),fromJsonString:(e,t)=>
2new s().fromJsonString(e,t),equals:(e,t)=>n.util.equals(s,e,t)}),s},makeEnum:function(e,t,i){let n={};for(let e of t){let t=e6(e);n[t.localName]=t.no,n[t.no]=t.localName}return e4(n,e,t),n},makeEnumType:e9,getEnumType:function(e){let t=e[e3];return e$(t,"missing enum type on enum object"),t},makeExtension(e,t,i){var n;let r;return n=this,{typeName:e,extendee:t,get field(){if(!r){let t="function"==typeof i?i():i;t.name=e.split(".").pop(),t.jsonName="[".concat(e,"]"),r=n.util.newFieldList([t]).list()[0]}return r},runtime:n}}});class t3 extends e8{constructor(e){super(),this.seconds=to.zero,this.nanos=0,t2.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(t2.json.debug(e)));let i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");let n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=to.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){let t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return t3.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new t3({seconds:to.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new t3().fromBinary(e,t)}static fromJson(e,t){return new t3().fromJson(e,t)}static fromJsonString(e,t){return new t3().fromJsonString(e,t)}static equals(e,t){return t2.util.equals(t3,e,t)}}t3.runtime=t2,t3.typeName="google.protobuf.Timestamp",t3.fields=t2.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);let t4=t2.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:t3},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:t9,repeated:!0},{no:5,name:"events",kind:"message",T:t8,repeated:!0}]),t9=t2.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:t6,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),t6=t2.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:t3},{no:3,name:"value",kind:"scalar",T:2}]),t8=t2.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:t3},{no:7,name:"normalized_end_timestamp",kind:"message",T:t3,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),t5=t2.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),t7=t2.makeEnum("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"}]),ie=t2.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),it=t2.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),ii=t2.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),ir=t2.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),ia=t2.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),is=t2.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),io=t2.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ic=t2.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"},{no:16,name:"AGENT_ERROR"}]),il=t2.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),id=t2.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),iu=t2.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),ih=t2.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"}]),ip=t2.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:im,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:iX}]),im=t2.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),ig=t2.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:t2.getEnumType(ir),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}]),iv=t2.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:t2.getEnumType(ib)},{no:4,name:"tracks",kind:"message",T:iC,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:ig},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:t2.getEnumType(ik)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:t2.getEnumType(ic)},{no:18,name:"kind_details",kind:"enum",T:t2.getEnumType(iy),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:iE,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5}]),ib=t2.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ik=t2.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),iy=t2.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"}]),iT=t2.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),iS=t2.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:iP,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:t2.getEnumType(iR)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),iC=t2.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:t2.getEnumType(ii)},{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:t2.getEnumType(ir)},{no:10,name:"layers",kind:"message",T:iP,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:iS,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:t2.getEnumType(iT)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:iX},{no:19,name:"audio_features",kind:"enum",T:t2.getEnumType(iu),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:t2.getEnumType(it)},{no:21,name:"packet_trailer_features",kind:"enum",T:t2.getEnumType(ih),repeated:!0}]),iE=t2.makeMessageType("livekit.DataTrackInfo",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:t2.getEnumType(iT)}]),iw=t2.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),iP=t2.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:t2.getEnumType(ia)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}]),iR=t2.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),iI=t2.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:t2.getEnumType(iD)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:iA,oneof:"value"},{no:3,name:"speaker",kind:"message",T:iM,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:iN,oneof:"value"},{no:7,name:"transcription",kind:"message",T:iL,oneof:"value"},{no:8,name:"metrics",kind:"message",T:t4,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:ij,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:iF,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:iB,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:iq,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:i1,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:i2,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:i3,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:i_,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),iD=t2.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),i_=t2.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:t2.getEnumType(iT)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),iO=t2.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:iA,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:ij,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:iF,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:iB,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:iq,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:i1,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:i2,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:i3,oneof:"value"}]),iM=t2.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:ix,repeated:!0}]),ix=t2.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),iA=t2.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),iN=t2.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),iL=t2.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:iU,repeated:!0}]),iU=t2.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),ij=t2.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),iF=t2.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13},{no:6,name:"compressed_payload",kind:"scalar",T:12}]),iB=t2.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),iq=t2.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:iV,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),iV=t2.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),iH=t2.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"part
2icipant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),iW=t2.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:t2.getEnumType(iG)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),iG=t2.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),iz=t2.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:t2.getEnumType(iK)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9},{no:12,name:"client_protocol",kind:"scalar",T:5}]),iK=t2.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),iJ=t2.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:iQ},{no:2,name:"screen",kind:"message",T:iQ},{no:3,name:"resume_connection",kind:"enum",T:t2.getEnumType(io)},{no:4,name:"disabled_codecs",kind:"message",T:iY},{no:5,name:"force_relay",kind:"enum",T:t2.getEnumType(io)}]),iQ=t2.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:t2.getEnumType(io)}]),iY=t2.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:im,repeated:!0},{no:2,name:"publish",kind:"message",T:im,repeated:!0}]),iX=t2.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),iZ=t2.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),i$=t2.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:t2.getEnumType(iZ)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),i0=t2.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),i1=t2.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:t2.getEnumType(iT)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:i$,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:i0,oneof:"content_header"}],{localName:"DataStream_Header"}),i2=t2.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),i3=t2.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),i4=t2.makeMessageType("livekit.FilterParams",()=>[{no:1,name:"include_events",kind:"scalar",T:9,repeated:!0},{no:2,name:"exclude_events",kind:"scalar",T:9,repeated:!0}]),i9=t2.makeMessageType("livekit.WebhookConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9},{no:3,name:"filter_params",kind:"message",T:i4}]),i6=t2.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),i8=t2.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),i5=t2.makeMessageType("livekit.RoomAgentDispatch",()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9},{no:3,name:"restart_policy",kind:"enum",T:t2.getEnumType(i8)}]),i7=t2.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),ne=t2.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),nt=t2.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ni=t2.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:nb,oneof:"message"},{no:2,name:"answer",kind:"message",T:nb,oneof:"message"},{no:3,name:"trickle",kind:"message",T:nh,oneof:"message"},{no:4,name:"add_track",kind:"message",T:na,oneof:"message"},{no:5,name:"mute",kind:"message",T:np,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ny,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:nC,oneof:"message"},{no:8,name:"leave",kind:"message",T:nP,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:nI,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:nV,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:nG,oneof:"message"},{no:13,name:"simulate",kind:"message",T:nJ,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:nD,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:nQ,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:nE,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:nw,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:ns,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:nc,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:nT,oneof:"message"}]),nn=t2.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:nm,oneof:"message"},{no:2,name:"answer",kind:"message",T:nb,oneof:"message"},{no:3,name:"offer",kind:"message",T:nb,oneof:"message"},{no:4,name:"trickle",kind:"message",T:nh,oneof:"message"},{no:5,name:"update",kind:"message",T:nk,oneof:"message"},{no:6,name:"track_published",kind:"message",T:nf,oneof:"message"},{no:8,name:"leave",kind:"message",T:nP,oneof:"message"},{no:9,name:"mute",kind:"message",T:np,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:nO,oneof:"message"},{no:11,name:"room_update",kind:"message",T:nM,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:nA,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:nL,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:nF,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:nH,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:nv,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:ng,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:nY,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:n$,oneof:"message"},{no:22,name:"request_response",kind:"message",T:n0,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:n2,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:nW,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:n8,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:nB,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:no,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:nl,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:nd,oneof:"message"}]),nr=t2.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:iP,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:t2.getEnumType(iR)}]),na=t2.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:t2.getEnumType(ii)},{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:t2.getEnumType(ir)},{no:9,name:"layers",kind:"message",T:iP,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:nr,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:t2.getEnumType(iT)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:t2.getEnumType(it)},{no:17,name:"audio_features",kind:"enum",T:t2.getEnumType(iu),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:t2.getEnumType(ih),repeated:!0}]),ns=t2.makeMessageType("livekit.PublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:t2.getEnumType(iT)}]),no=t2.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:iE}]),nc=t2.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),nl=t2.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:iE}]),nd=t2.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:nu}}]),nu=t2.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}],{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),nh=t2.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:t2.getEnumType(i7)},{no:3,name:"final",kind:"scalar",T:8}]),np=t2.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),nm=t2.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:ip},{no:2,name:"participant",kind:"message",T:iv},{no:3,name:"other_participants",kind:"message",T:iv,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:n_,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:iJ},{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:iW},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:im,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),ng=t2.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:n_,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:iJ},{no:3,name:"server_info",kind:"message",T:iW},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),nf=t2.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:iC}]),nv=t2.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),nb=t2.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),nk=t2.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:iv,repeated:!0}]),ny=t2.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:iH,repeated:!0}]),nT=t2.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:nS,repeated:!0}]),nS=t2.makeMessageType("livekit.UpdateDataSubscription.Update",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:iw}],{localName:"UpdateDataSubscription_Update"}),nC=t2.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:t2.getEnumType(ia)},{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}]),nE=t2.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:t2.getEnumType(iu),repeated:!0}]),nw=t2.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),nP=t2.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:t2.getEnumType(ic)},{no:3,name:"action",kind:"enum",T:t2.getEnumType(nR)},{no:4,name:"regions",kind:"message",T:nX}]),nR=t2.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),nI=t2.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:iP,repeated:!0}]),nD=t2.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),n_=t2.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),nO=t2.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:ix,repeated:!0}]),nM=t2.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:ip}]),nx=t2.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:t2.getEnumType(is)},{no:3,name:"score",kind:"scalar",T:2}]),nA=t2.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:nx,repeated:!0}]),nN=t2.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:t2.getEnumType(ne)}]),nL=t2.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:nN,repeated:!0}]),nU=t2.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:t2.getEnumType(ia)},{no:2,name:"enabled",kind:"scalar",T:8}]),nj=t2.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:nU,repeated:!0}]),nF=t2.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:nU,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:nj,repeated:!0}]),nB=t2.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:i6,repeated:!0}]),nq=t2.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"partici
2pant_identity",kind:"scalar",T:9}]),nV=t2.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:nq,repeated:!0}]),nH=t2.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),nW=t2.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:ip},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:iv},{no:4,name:"other_participants",kind:"message",T:iv,repeated:!0}]),nG=t2.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:nb},{no:2,name:"subscription",kind:"message",T:ny},{no:3,name:"publish_tracks",kind:"message",T:nf,repeated:!0},{no:4,name:"data_channels",kind:"message",T:nK,repeated:!0},{no:5,name:"offer",kind:"message",T:nb},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:nz,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:no,repeated:!0}]),nz=t2.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),nK=t2.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:t2.getEnumType(i7)}]),nJ=t2.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:t2.getEnumType(nt),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),nQ=t2.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),nY=t2.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),nX=t2.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:nZ,repeated:!0}]),nZ=t2.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),n$=t2.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:t2.getEnumType(id)}]),n0=t2.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:t2.getEnumType(n1)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:nh,oneof:"request"},{no:5,name:"add_track",kind:"message",T:na,oneof:"request"},{no:6,name:"mute",kind:"message",T:np,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:nD,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:nE,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:nw,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:ns,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:nc,oneof:"request"}]),n1=t2.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),n2=t2.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),n3=t2.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}]),n4=t2.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:iz},{no:2,name:"connection_settings",kind:"message",T:n3},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:na,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:nb},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:t2.getEnumType(il)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:nG}]),n9=t2.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:t2.getEnumType(n6)},{no:2,name:"join_request",kind:"scalar",T:12}]),n6=t2.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),n8=t2.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]),n5=t2.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),n7=t2.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),re=t2.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),rt=t2.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),ri=t2.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),rn=t2.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),rr=t2.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),ra=t2.makeMessageType("livekit.EncodingOptions",()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:t2.getEnumType(t5)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:t2.getEnumType(t7)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5}]),rs=t2.makeMessageType("livekit.StreamOutput",()=>[{no:1,name:"protocol",kind:"enum",T:t2.getEnumType(re)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}]),ro=t2.makeMessageType("livekit.SegmentedFileOutput",()=>[{no:1,name:"protocol",kind:"enum",T:t2.getEnumType(rt)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:t2.getEnumType(ri)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:rl,oneof:"output"},{no:6,name:"gcp",kind:"message",T:rd,oneof:"output"},{no:7,name:"azure",kind:"message",T:ru,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:rh,oneof:"output"}]),rc=t2.makeMessageType("livekit.ImageOutput",()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:t2.getEnumType(rn)},{no:6,name:"image_codec",kind:"enum",T:t2.getEnumType(ie)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:rl,oneof:"output"},{no:9,name:"gcp",kind:"message",T:rd,oneof:"output"},{no:10,name:"azure",kind:"message",T:ru,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:rh,oneof:"output"}]),rl=t2.makeMessageType("livekit.S3Upload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:11,name:"session_token",kind:"scalar",T:9},{no:12,name:"assume_role_arn",kind:"scalar",T:9},{no:13,name:"assume_role_external_id",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9},{no:10,name:"proxy",kind:"message",T:rp}]),rd=t2.makeMessageType("livekit.GCPUpload",()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"proxy",kind:"message",T:rp}]),ru=t2.makeMessageType("livekit.AzureBlobUpload",()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}]),rh=t2.makeMessageType("livekit.AliOSSUpload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}]),rp=t2.makeMessageType("livekit.ProxyConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"password",kind:"scalar",T:9}]),rm=t2.makeMessageType("livekit.AutoParticipantEgress",()=>[{no:1,name:"preset",kind:"enum",T:t2.getEnumType(n5),oneof:"options"},{no:2,name:"advanced",kind:"message",T:ra,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:rv,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:ro,repeated:!0}]),rg=t2.makeMessageType("livekit.AutoTrackEgress",()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:rl,oneof:"output"},{no:3,name:"gcp",kind:"message",T:rd,oneof:"output"},{no:4,name:"azure",kind:"message",T:ru,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:rh,oneof:"output"}]),rf=t2.makeMessageType("livekit.RoomCompositeEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:15,name:"audio_mixing",kind:"enum",T:t2.getEnumType(rr)},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:rv,oneof:"output"},{no:7,name:"stream",kind:"message",T:rs,oneof:"output"},{no:10,name:"segments",kind:"message",T:ro,oneof:"output"},{no:8,name:"preset",kind:"enum",T:t2.getEnumType(n5),oneof:"options"},{no:9,name:"advanced",kind:"message",T:ra,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:rv,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:rs,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:ro,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:rc,repeated:!0},{no:16,name:"webhooks",kind:"message",T:i9,repeated:!0}]),rv=t2.makeMessageType("livekit.EncodedFileOutput",()=>[{no:1,name:"file_type",kind:"enum",T:t2.getEnumType(n7)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:rl,oneof:"output"},{no:4,name:"gcp",kind:"message",T:rd,oneof:"output"},{no:5,name:"azure",kind:"message",T:ru,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:rh,oneof:"output"}]),rb=t2.makeMessageType("livekit.RoomEgress",()=>[{no:1,name:"room",kind:"message",T:rf},{no:3,name:"participant",kind:"message",T:rm},{no:2,name:"tracks",kind:"message",T:rg}]);()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:3,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:11,name:"metadata",kind:"scalar",T:9},{no:5,name:"egress",kind:"message",T:rb},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8},{no:10,name:"agents",kind:"message",T:i5,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}];var rk={exports:{}},ry=rk.exports,rT=function(){var e;return en?rk.exports:(en=1,e=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],r={},a=null;function s(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),r=0;r<n.length;r++){var a=n[r];this[a]=r<i?e:this.methodFactory(a,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function l(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function d(n,r,a){var c;return"debug"===(c=n)&&(c="log"),typeof console!==t&&("trace"===c&&i?o:void 0!==console[c]?s(console,c):void 0!==console.log?s(console,"log"):e)||l.apply(this,arguments)}function u(e,i){var s,o,l,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;
2throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||d,u.getLevel=function(){return null!=l?l:null!=o?o:s},u.setLevel=function(e,i){return l=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{window.localStorage[h]=i;return}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(l),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){if(l=null,typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(a!==u&&(s=m(a.getLevel())),c.call(u),a===u)for(var e in r)r[e].rebuild()},s=m(a?a.getLevel():"WARN");var g=p();null!=g&&(l=m(g)),c.call(u)}(a=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new u(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return r},a.default=a,a},rk.exports?rk.exports=e():ry.log=e(),rk.exports)}();(u=er||(er={}))[u.trace=0]="trace",u[u.debug=1]="debug",u[u.info=2]="info",u[u.warn=3]="warn",u[u.error=4]="error",u[u.silent=5]="silent",(h=ea||(ea={})).Default="livekit",h.Room="livekit-room",h.TokenSource="livekit-token-source",h.Participant="livekit-participant",h.Track="livekit-track",h.Publication="livekit-track-publication",h.Engine="livekit-engine",h.Signal="livekit-signal",h.PCManager="livekit-pc-manager",h.PCTransport="livekit-pc-transport",h.E2EE="lk-e2ee",h.DataTracks="livekit-data-tracks";let rS=rT.getLogger("livekit");function rC(e){let t=rT.getLogger(e);return t.setDefaultLevel(rS.getLevel()),t}Object.values(ea).map(e=>rT.getLogger(e)),rS.setDefaultLevel(er.info);let rE=rT.getLogger("lk-e2ee"),rw=[0,300,1200,2700,4800,7e3,7e3,7e3,7e3,7e3];function rP(e,t,i,n){return new(i||(i=Promise))(function(r,a){function s(e){try{c(n.next(e))}catch(e){a(e)}}function o(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(s,o)}c((n=n.apply(e,t||[])).next())})}function rR(e){return this instanceof rR?(this.v=e,this):new rR(e)}function rI(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,r){var a,s,o;a=n,s=r,o=(t=e[i](t)).done,Promise.resolve(t.value).then(function(e){a({value:e,done:o})},s)})}}}"function"==typeof SuppressedError&&SuppressedError;var rD={exports:{}},r_=function(){if(es)return rD.exports;es=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}rD.exports=r,rD.exports.once=function(e,t){return new Promise(function(i,n){var r,a,s;function o(i){e.removeListener(t,c),n(i)}function c(){"function"==typeof e.removeListener&&e.removeListener("error",o),i([].slice.call(arguments))}m(e,t,c,{once:!0}),"error"!==t&&(r=e,a=o,s={once:!0},"function"==typeof r.on&&m(r,"error",a,s))})},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function s(e){if("function"!=typeof e)throw TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){if(s(i),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),c=a[t]),void 0===c)c=a[t]=i,++e._eventsCount;else if("function"==typeof c?c=a[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(r=o(e))>0&&c.length>r&&!c.warned){c.warned=!0;var r,a,c,l=Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,console&&console.warn&&console.warn(l)}return e}function l(){if(!this.fired)return(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0==arguments.length)?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=l.bind(n);return r.listener=i,n.wrapFn=r,r}function u(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):p(r,r.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else if("function"==typeof e.addEventListener)e.addEventListener(t,function r(a){n.once&&e.removeEventListener(t,r),i(a)});else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a}
2,set:function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),r.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,a=this._events;if(void 0!==a)r=r&&void 0===a.error;else if(!r)return!1;if(r){if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var s,o=Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=a[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else for(var l=c.length,d=p(c,l),n=0;n<l;++n)i(d[n],this,t);return!0},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,r,a,o;if(s(t),void 0===(n=this._events)||void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,a=i.length-1;a>=0;a--)if(i[a]===t||i[a].listener===t){o=i[a].listener,r=a;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0==arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0==arguments.length){var r,a=Object.keys(i);for(n=0;n<a.length;++n)"removeListener"!==(r=a[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},rD.exports}();let rO=!0,rM=!0;function rx(e,t,i){let n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function rA(e,t,i){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);let a=e=>{let t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,a),r.apply(this,[e,a])};let a=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(i))return a.apply(this,arguments);let n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,a.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function rN(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(rO=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function rL(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(rM=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function rU(){"object"==typeof window&&!rO&&"u">typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}function rj(e,t){rM&&console.warn(e+" is deprecated, please use "+t+" instead.")}function rF(e){return"[object Object]"===Object.prototype.toString.call(e)}function rB(e,t,i){let n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;let a=[];
vendor: 42,334 bytes, line 2
2return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&function e(t,i,n){!i||n.has(i.id)||(n.set(i.id,i),Object.keys(i).forEach(r=>{r.endsWith("Id")?e(t,t.get(i[r]),n):r.endsWith("Ids")&&i[r].forEach(i=>{e(t,t.get(i),n)})}))}(e,i,r)})}),r}function rq(e,t){let i=e&&e.navigator;if(!i.mediaDevices)return;let n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;let n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);let r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),(e={})[r("max",i)]=n.ideal):e[r("",i)]=n.ideal,t.optional.push(e)}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){let t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let a=e.video.facingMode;a=a&&("object"==typeof a?a:{ideal:a});let s=t.version<66;if(a&&("user"===a.exact||"environment"===a.exact||"user"===a.ideal||"environment"===a.ideal)&&!(i.mediaDevices.getSupportedConstraints&&i.mediaDevices.getSupportedConstraints().facingMode&&!s)){let t;if(delete e.video.facingMode,"environment"===a.exact||"environment"===a.ideal?t=["back","rear"]:("user"===a.exact||"user"===a.ideal)&&(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let s=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=a.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),rU("chrome: "+JSON.stringify(e)),r(e)})}e.video=n(e.video)}return rU("chrome: "+JSON.stringify(e)),r(e)},a=function(e){return t.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(a(e))})})}).bind(i),i.mediaDevices.getUserMedia){let e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(a(e))))}}}function rV(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function rH(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)rA(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};let r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};let r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}}function rW(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};let n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);let t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function rG(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>rB(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),rA(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>rB(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,t,i,n=arguments[0];return(this.getSenders().forEach(t=>{t.track===n&&(e?i=!0:e=t)}),this.getReceivers().forEach(e=>(e.track===n&&(t?i=!0:t=e),e.track===n)),i||e&&t)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():t?t.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function rz(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let t=this.getSenders();i.apply(this,arguments);let n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),r.apply(this,arguments)}}function rK(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return rz(e);let i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){let i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};let r=e.RTCPeerConnection.prototype.removeStream;function a(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(r.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){let e=arguments,t=arguments.length&&"function"==typeof arguments[0];return t?i.apply(this,[t=>{let i=a(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>a(this,e))}})[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,t;let i;return arguments.length&&arguments[0].type?(arguments[0]=(e=this,t=arguments[0],i=t.sdp,Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(n.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:i})),s.apply(this,arguments)):s.apply(this,arguments)};let o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=o.get.apply(this);return""===e.type?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let t;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function rJ(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]})}function rQ(e,t){rA(e,"negotiationneeded",e=>{let i=e.target;if(!(t.version<72)&&(!i.getConfiguration||"plan-b"!==i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var rY=Object.freeze({__proto__:null,fixNegotiationNeeded:rQ,shimAddTrackRemoveTrack:rK,shimAddTrackRemoveTrackWithNative:rz,shimGetSendersWithDtmf:rW,shimGetUserMedia:rq,shimMediaStream:rV,shimOnTrack:rH,shimPeerConnection:rJ,shimSenderReceiverGetStats:rG});function rX(e,t){let i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){rj("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){let e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(e((i=JSON.parse(JSON.stringify(i))).audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){let t=n.prototype.getSettings;n.prototype.getSettings=function(){let i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){let t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(e(i=JSON.parse(JSON.stringify(i)),"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function rZ(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function r$(e,t){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]});let i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,r,a]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(r,a)}}function r0(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function r1(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),rA(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function r2(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){rj("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function r3(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function r4(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let i=(e=[...e]).length>0;i&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let n=t.apply(this,arguments);if(i){let{sender:t}=n,i=t.getParameters();"encodings"in i&&(1!==i.encodings.length||0!==Object.keys(i.encodings[0]).length)||(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function r9(e){if(!("object"==typeof e&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function r6(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function r8(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var r5=Object.freeze({__proto__:null,shimAddTransceiver:r4,shimCreateAnswer:r8,shimCreateOffer:r6,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:r9,shimGetUserMedia:rX,shimOnTrack:rZ,shimPeerConnection:r$,shimRTCDataChannel:r3,shimReceiverGetStats:r1,shimRemoveStream:r2,shimSenderGetStats:r0});function r7(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);let i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function ae(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function at(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,a=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){let i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,i){let n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,t.setRemoteDescription=o=function(e,t,i){let n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=function(e,t,i){let n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n}}function ai(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(an(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}).bind(t))}function an(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){return rF(t)?Object.keys(t).reduce(function(i,n){let r=rF(t[n]),a=r?e(t[n]):t[n],s=r&&!Object.keys(a).length;return void 0===a||s?i:Object.assign(i,{[n]:a})},{}):t}(e.video)}):e}function ar(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){let t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(rj("RTCIceServer.url","RTCIceServer.urls"),(n=JSON.parse(JSON.stringify(n))).urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function aa(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function as(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function ao(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ac=Object.freeze({__proto__:null,shimAudioContext:ao,shimCallbacksAPI:at,shimConstraints:an,shimCreateOfferLegacy:as,shimGetUserMedia:ai,shimLocalStreamsAPI:r7,shimRTCIceServerUrls:ar,shimRemoteStreamsAPI:ae,shimTrackEventTransceiver:aa}),al={exports:{}},ad=function(){let e;return eo?al.exports:(eo=1,(e={}).generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},e.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},e.getDescription=function(t){let i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){let i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(e=>0===e.indexOf(i))},e.parseCandidate=function(e){let t,i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},e.writeCandidate=function(e){let t=[];t.push(e.foundation);let i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},e.parseIceOptions=function(e){return e.substring(14).split(" ")},e.parseRtpMap=function(e){let t=e.substring(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return i.name=(t=t[0].split("/"))[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},e.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);let i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},e.parseExtmap=function(e){let t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},e.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},e.parseFmtp=function(e){let t,i={},n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i[(t=n[e].trim().split("="))[0].trim()]=t[1];return i},e.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},e.parseRtcpFb=function(e){let t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},e.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},e.parseSsrcMedia=function(e){let t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},e.parseSsrcGroup=function(e){let t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},e.getMid=function(t){let i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(e){let t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},e.parseCryptoLine=function(e){let t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+("object"==typeof t.keyParams?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+"\r\n"},e.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;let t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){let n=e.matchPrefix(t+i,"a=ice-ufrag:")[0],r=e.matchPrefix(t+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},e.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},e.parseRtpParameters=function(t){let i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=e.splitLines(t)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){let a=n[r],s=e.matchPrefix(t,"a=rtpmap:"+a+" ")[0];if(s){let n=e.parseRtpMap(s),r=e.matchPrefix(t,"a=fmtp:"+a+" ");switch(n.parameters=r.length?e.parseFmtp(r[0]):{},n.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+a+" ").map(e.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}e.matchPrefix(t,"a=extmap:").forEach(t=>{i.headerExtensions.push(e.parseExtmap(t))});let r=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},e.writeRtpDescription=function(t,i){let n="";n+="m="+t+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(t=>{n+=e.writeRtpMap(t),n+=e.writeFmtp(t),n+=e.writeRtcpFb(t)});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime)}),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(t=>{n+=e.writeExtmap(t)}),n},e.parseRtpEncodingParameters=function(t){let i,n=[],r=e.parseRtpParameters(t),a=-1!==r.fecMechanisms.indexOf("RED"),s=-1!==r.fecMechanisms.indexOf("ULPFEC"),o=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"cname"===e.attribute),c=o.length>0&&o[0].ssrc,l=e.matchPrefix(t,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(i=l[0][1]),r.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&i&&(t.rtx={ssrc:i}),n.push(t),a&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:s?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&c&&n.push({ssrc:c});let d=e.matchPrefix(t,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,n.forEach(e=>{e.maxBitrate=d})),n},e.parseRtcpParameters=function(t){let i={},n=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);let r=e.matchPrefix(t,"a=rtcp-rsize");return i.reducedSize=r.length>0,i.compound=0===r.length,i.mux=e.matchPrefix(t,"a=rtcp-mux").length>0,i},e.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},e.parseMsid=function(t){let i,n=e.matchPrefix(t,"a=msid:");if(1===n.length)return{stream:(i=n[0].substring(7).split(" "))[0],track:i[1]};let r=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"msid"===e.attribute);if(r.length>0)return{stream:(i=r[0].value.split(" "))[0],track:i[1]}},e.parseSctpDescription=function(t){let i,n=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:");r.length>0&&(i=parseInt(r[0].substring(19),10)),isNaN(i)&&(i=65536);let a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};let s=e.matchPrefix(t,"a=sctpmap:");if(s.length>0){let e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},e.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,n){return"v=0\r\no="+(n||"thisisadapterortc")+" "+(t||e.generateSessionId())+" "+(void 0!==i?i:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},e.getDirection=function(t,i){let n=e.splitLines(t);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(e){return"0"===e.split(" ",2)[1]},e.parseMLine=function(t){let i=e.splitLines(t)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(t){let i=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(t){if("string"!=typeof t||0===t.length)return!1;let i=e.splitLines(t);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},al.exports=e,al.exports)}(),au=ad&&ad.__esModule&&Object.prototype.hasOwnProperty.call(ad,"default")?ad.default:ad,ah=(p={__proto__:null,default:au},[ad].forEach(function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach(function(t){if("default"!==t&&!(t in p)){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(p,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}})}),Object.freeze(p));function ap(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let i=new t(e),n=au.parseCandidate(e.candidate);for(let e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,rA(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function am(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||rA(e,"icecandidate",e=>{if(e.candidate){let t=au.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function ag(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});let i=function(e){if(!e||!e.sdp)return!1;let t=au.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=au.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})},n=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;let i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:0x7ffffff5:t.version<60?57===t.version?65535:65536:0x7ffffff5),i},a=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);let r=au.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=0x7ffffff5),n},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){let e,t=n(arguments[0]),i=r(t),s=a(arguments[0],t);e=0===i&&0===s?1/0:0===i||0===s?Math.max(i,s):Math.min(i,s);let o={};Object.defineProperty(o,"maxMessageSize",{get:()=>e}),this._sctp=o}return s.apply(this,arguments)}}function af(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){let i=e.send;e.send=function(){let n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}let i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=i.apply(this,arguments);return t(e,this),e},rA(e,"datachannel",e=>(t(e.channel,e.target),e))}function av(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}
2),["setLocalDescription","setRemoteDescription"].forEach(e=>{let i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function ab(e,t){if(!e.RTCPeerConnection||"chrome"===t.browser&&t.version>=71||"safari"===t.browser&&t._safariVersion>=13.1)return;let i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){let i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function ak(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ay(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var aT=Object.freeze({__proto__:null,removeExtmapAllowMixed:ab,shimAddIceCandidateNullOrEmpty:ak,shimConnectionState:av,shimMaxMessageSize:ag,shimParameterlessSetLocalDescription:ay,shimRTCIceCandidate:ap,shimRTCIceCandidateRelayProtocol:am,shimSendThrowTypeError:af});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},i=function(e){let t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;let{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){let e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}return i.mozGetUserMedia?(t.browser="firefox",t.version=parseInt(rx(i.userAgent,/Firefox\/(\d+)\./,1))):i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(t.browser="chrome",t.version=parseInt(rx(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))):e.RTCPeerConnection&&i.userAgent.match(/AppleWebKit\/(\d+)\./)?(t.browser="safari",t.version=parseInt(rx(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=rx(i.userAgent,/Version\/(\d+(\.?\d+))/,1)):t.browser="Not a supported browser.",t}(e),n={browserDetails:i,commonShim:aT,extractVersion:rx,disableLog:rN,disableWarnings:rL,sdp:ah};switch(i.browser){case"chrome":if(!rY||!rJ||!t.shimChrome){rU("Chrome shim is not included in this adapter release.");break}if(null===i.version){rU("Chrome shim can not determine version, not shimming.");break}rU("adapter.js shimming chrome."),n.browserShim=rY,ak(e,i),ay(e),rq(e,i),rV(e),rJ(e,i),rH(e),rK(e,i),rW(e),rG(e),rQ(e,i),ap(e),am(e),av(e),ag(e,i),af(e),ab(e,i);break;case"firefox":if(!r5||!r$||!t.shimFirefox){rU("Firefox shim is not included in this adapter release.");break}rU("adapter.js shimming firefox."),n.browserShim=r5,ak(e,i),ay(e),rX(e,i),r$(e,i
2),rZ(e),r2(e),r0(e),r1(e),r3(e),r4(e),r9(e),r6(e),r8(e),ap(e),av(e),ag(e,i),af(e);break;case"safari":if(!ac||!t.shimSafari){rU("Safari shim is not included in this adapter release.");break}rU("adapter.js shimming safari."),n.browserShim=ac,ak(e,i),ay(e),ar(e),as(e),at(e),r7(e),ae(e),aa(e),ai(e),ao(e),ap(e),am(e),ag(e,i),af(e),ab(e,i);break;default:rU("Unsupported browser!")}}({window:"u"<typeof window?void 0:window});class aS extends(ec=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}aS.resolve=e=>Reflect.get(ec,"resolve",aS).call(aS,e);let aC=/version\/(\d+(\.?_?\d+)+)/i;function aE(e){let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(void 0===e&&"u"<typeof navigator)return;let n=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===t||i){let e=aw.find(e=>{let{test:t}=e;return t.test(n)});t=null==e?void 0:e.describe(n)}return t}let aw=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:aP(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:aR(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:aP(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:aR(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:aP(aC,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:aR(e)})}];function aP(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=t.match(e);return n&&n.length>=i&&n[i]||""}function aR(e){return e.includes("mac os")?aP(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class aI extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==i?void 0:i.cause)&&(this.cause=null==i?void 0:i.cause)}}class aD extends aI{}(m=el||(el={}))[m.NotAllowed=0]="NotAllowed",m[m.ServerUnreachable=1]="ServerUnreachable",m[m.InternalError=2]="InternalError",m[m.Cancelled=3]="Cancelled",m[m.LeaveRequest=4]="LeaveRequest",m[m.Timeout=5]="Timeout",m[m.WebSocket=6]="WebSocket",m[m.ServiceNotFound=7]="ServiceNotFound";class a_ extends aD{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=el[t]}static notAllowed(e,t,i){return new a_(e,el.NotAllowed,t,i)}static timeout(e){return new a_(e,el.Timeout)}static leaveRequest(e,t){return new a_(e,el.LeaveRequest,void 0,t)}static internal(e,t){return new a_(e,el.InternalError,void 0,t)}static cancelled(e){return new a_(e,el.Cancelled)}static serverUnreachable(e,t){return new a_(e,el.ServerUnreachable,t)}static websocket(e,t,i){return new a_(e,el.WebSocket,t,i)}static serviceNotFound(e,t){return new a_(e,el.ServiceNotFound,void 0,t)}}class aO extends aI{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class aM extends aI{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class ax extends aI{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class aA extends aI{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class aN extends aI{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class aL extends aI{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class aU extends aD{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:n1[t]}}(g=ed||(ed={}))[g.AlreadyOpened=0]="AlreadyOpened",g[g.AbnormalEnd=1]="AbnormalEnd",g[g.DecodeFailed=2]="DecodeFailed",g[g.LengthExceeded=3]="LengthExceeded",g[g.Incomplete=4]="Incomplete",g[g.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",g[g.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class aj extends aD{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ed[t]}}class aF extends aI{constructor(e){super(18,e),this.name="SignalReconnectError"}}(f=eu||(eu={})).PermissionDenied="PermissionDenied",f.NotFound="NotFound",f.DeviceInUse="DeviceInUse",f.Other="Other",(v=eu||(eu={})).getFailure=function(e){if(e&&"name"in e)return"NotFoundError"===e.name||"DevicesNotFoundError"===e.name?v.NotFound:"NotAllowedError"===e.name||"PermissionDeniedError"===e.name?v.PermissionDenied:"NotReadableError"===e.name||"TrackStartError"===e.name?v.DeviceInUse:v.Other};class aB{}aB.setTimeout=function(){return setTimeout(...arguments)},aB.setInterval=function(){return setInterval(...arguments)},aB.clearTimeout=function(){return clearTimeout(...arguments)},aB.clearInterval=function(){return clearInterval(...arguments)},(b=eh||(eh={})).Connected="connected",b.Reconnecting="reconnecting",b.SignalReconnecting="signalReconnecting",b.Reconnected="reconnected",b.Disconnected="disconnected",b.ConnectionStateChanged="connectionStateChanged",b.Moved="moved",b.MediaDevicesChanged="mediaDevicesChanged",b.ParticipantConnected="participantConnected",b.ParticipantDisconnected="participantDisconnected",b.TrackPublished="trackPublished",b.TrackSubscribed="trackSubscribed",b.TrackSubscriptionFailed="trackSubscriptionFailed",b.TrackUnpublished="trackUnpublished",b.TrackUnsubscribed="trackUnsubscribed",b.TrackMuted="trackMuted",b.TrackUnmuted="trackUnmuted",b.LocalTrackPublished="localTrackPublished",b.L
2ocalTrackUnpublished="localTrackUnpublished",b.LocalAudioSilenceDetected="localAudioSilenceDetected",b.ActiveSpeakersChanged="activeSpeakersChanged",b.ParticipantMetadataChanged="participantMetadataChanged",b.ParticipantNameChanged="participantNameChanged",b.ParticipantAttributesChanged="participantAttributesChanged",b.ParticipantActive="participantActive",b.RoomMetadataChanged="roomMetadataChanged",b.DataReceived="dataReceived",b.SipDTMFReceived="sipDTMFReceived",b.TranscriptionReceived="transcriptionReceived",b.ConnectionQualityChanged="connectionQualityChanged",b.TrackStreamStateChanged="trackStreamStateChanged",b.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",b.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",b.AudioPlaybackStatusChanged="audioPlaybackChanged",b.VideoPlaybackStatusChanged="videoPlaybackChanged",b.MediaDevicesError="mediaDevicesError",b.ParticipantPermissionsChanged="participantPermissionsChanged",b.SignalConnected="signalConnected",b.RecordingStatusChanged="recordingStatusChanged",b.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",b.EncryptionError="encryptionError",b.DCBufferStatusChanged="dcBufferStatusChanged",b.ActiveDeviceChanged="activeDeviceChanged",b.ChatMessage="chatMessage",b.LocalTrackSubscribed="localTrackSubscribed",b.MetricsReceived="metricsReceived",b.DataTrackPublished="dataTrackPublished",b.DataTrackUnpublished="dataTrackUnpublished",b.LocalDataTrackPublished="localDataTrackPublished",b.LocalDataTrackUnpublished="localDataTrackUnpublished",(k=ep||(ep={})).TrackPublished="trackPublished",k.TrackSubscribed="trackSubscribed",k.TrackSubscriptionFailed="trackSubscriptionFailed",k.TrackUnpublished="trackUnpublished",k.TrackUnsubscribed="trackUnsubscribed",k.TrackMuted="trackMuted",k.TrackUnmuted="trackUnmuted",k.LocalTrackPublished="localTrackPublished",k.LocalTrackUnpublished="localTrackUnpublished",k.LocalTrackCpuConstrained="localTrackCpuConstrained",k.LocalSenderCreated="localSenderCreated",k.ParticipantMetadataChanged="participantMetadataChanged",k.ParticipantNameChanged="participantNameChanged",k.DataReceived="dataReceived",k.SipDTMFReceived="sipDTMFReceived",k.TranscriptionReceived="transcriptionReceived",k.IsSpeakingChanged="isSpeakingChanged",k.ConnectionQualityChanged="connectionQualityChanged",k.TrackStreamStateChanged="trackStreamStateChanged",k.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",k.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",k.TrackCpuConstrained="trackCpuConstrained",k.MediaDevicesError="mediaDevicesError",k.AudioStreamAcquired="audioStreamAcquired",k.ParticipantPermissionsChanged="participantPermissionsChanged",k.PCTrackAdded="pcTrackAdded",k.AttributesChanged="attributesChanged",k.LocalTrackSubscribed="localTrackSubscribed",k.ChatMessage="chatMessage",k.Active="active",(y=em||(em={})).TransportsCreated="transportsCreated",y.Connected="connected",y.Disconnected="disconnected",y.Resuming="resuming",y.Resumed="resumed",y.Restarting="restarting",y.Restarted="restarted",y.SignalResumed="signalResumed",y.SignalRestarted="signalRestarted",y.Closing="closing",y.MediaTrackAdded="mediaTrackAdded",y.ActiveSpeakersUpdate="activeSpeakersUpdate",y.DataPacketReceived="dataPacketReceived",y.RTPVideoMapUpdate="rtpVideoMapUpdate",y.DCBufferStatusChanged="dcBufferStatusChanged",y.ParticipantUpdate="participantUpdate",y.RoomUpdate="roomUpdate",y.SpeakersChanged="speakersChanged",y.StreamStateChanged="streamStateChanged",y.ConnectionQualityUpdate="connectionQualityUpdate",y.SubscriptionError="subscriptionError",y.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",y.RemoteMute="remoteMute",y.SubscribedQualityUpdate="subscribedQualityUpdate",y.LocalTrackUnpublished="localTrackUnpublished",y.LocalTrackSubscribed="localTrackSubscribed",y.Offline="offline",y.SignalRequestResponse="signalRequestResponse",y.SignalConnected="signalConnected",y.RoomMoved="roomMoved",y.PublishDataTrackResponse="publishDataTrackResponse",y.UnPublishDataTrackResponse="unPublishDataTrackResponse",y.DataTrackSubscriberHandles="dataTrackSubscriberHandles",y.DataTrackPacketReceived="dataTrackPacketReceived",y.Joined="joined",(T=eg||(eg={})).Message="message",T.Muted="muted",T.Unmuted="unmuted",T.Restarted="restarted",T.Ended="ended",T.Subscribed="subscribed",T.Unsubscribed="unsubscribed",T.CpuConstrained="cpuConstrained",T.UpdateSettings="updateSettings",T.UpdateSubscription="updateSubscription",T.AudioPlaybackStarted="audioPlaybackStarted",T.AudioPlaybackFailed="audioPlaybackFailed",T.AudioSilenceDetected="audioSilenceDetected",T.VisibilityChanged="visibilityChanged",T.VideoDimensionsChanged="videoDimensionsChanged",T.VideoPlaybackStarted="videoPlaybackStarted",T.VideoPlaybackFailed="videoPlaybackFailed",T.ElementAttached="elementAttached",T.ElementDetached="elementDetached",T.UpstreamPaused="upstreamPaused",T.UpstreamResumed="upstreamResumed",T.SubscriptionPermissionChanged="subscriptionPermissionChanged",T.SubscriptionStatusChanged="subscriptionStatusChanged",T.SubscriptionFailed="subscriptionFailed",T.TrackProcessorUpdate="trackProcessorUpdate",T.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",T.TranscriptionReceived="transcriptionReceived",T.TimeSyncUpdate="timeSyncUpdate",T.PreConnectBufferFlushed="preConnectBufferFlushed";class aq{constructor(e,t,i,n,r){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(void 0!==t&&void 0!==i)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r};else throw TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}let aV=["vp8","h264"],aH=["vp8","h264","vp9","av1","h265"],aW=function(e){return!!aV.find(t=>t===e)};(S=ef||(ef={}))[S.PREFER_REGRESSION=0]="PREFER_REGRESSION",S[S.SIMULCAST=1]="SIMULCAST",S[S.REGRESSION=2]="REGRESSION",(C=ev||(ev={})).telephone={maxBitrate:12e3}
2,C.speech={maxBitrate:24e3},C.music={maxBitrate:48e3},C.musicStereo={maxBitrate:64e3},C.musicHighQuality={maxBitrate:96e3},C.musicHighQualityStereo={maxBitrate:128e3};let aG={h90:new aq(160,90,9e4,20),h180:new aq(320,180,16e4,20),h216:new aq(384,216,18e4,20),h360:new aq(640,360,45e4,20),h540:new aq(960,540,8e5,25),h720:new aq(1280,720,17e5,30),h1080:new aq(1920,1080,3e6,30),h1440:new aq(2560,1440,5e6,30),h2160:new aq(3840,2160,8e6,30)},az={h120:new aq(160,120,7e4,20),h180:new aq(240,180,125e3,20),h240:new aq(320,240,14e4,20),h360:new aq(480,360,33e4,20),h480:new aq(640,480,5e5,20),h540:new aq(720,540,6e5,25),h720:new aq(960,720,13e5,30),h1080:new aq(1440,1080,23e5,30),h1440:new aq(1920,1440,38e5,30)},aK={h360fps3:new aq(640,360,2e5,3,"medium"),h360fps15:new aq(640,360,4e5,15,"medium"),h720fps5:new aq(1280,720,8e5,5,"medium"),h720fps15:new aq(1280,720,15e5,15,"medium"),h720fps30:new aq(1280,720,2e6,30,"medium"),h1080fps15:new aq(1920,1080,25e5,15,"medium"),h1080fps30:new aq(1920,1080,5e6,30,"medium"),original:new aq(0,0,7e6,30,"medium")};function aJ(e,t,i){var n,r;let{optionsWithoutProcessor:a,audioProcessor:s,videoProcessor:o}=a2(null!=e?e:{}),c=null==t?void 0:t.processor,l=null==i?void 0:i.processor,d=null!=a?a:{};return!0===d.audio&&(d.audio={}),!0===d.video&&(d.video={}),d.audio&&(aQ(d.audio,t),null!=(n=d.audio).deviceId||(n.deviceId={ideal:"default"}),(s||c)&&(d.audio.processor=null!=s?s:c)),d.video&&(aQ(d.video,i),null!=(r=d.video).deviceId||(r.deviceId={ideal:"default"}),(o||l)&&(d.video.processor=null!=o?o:l)),d}function aQ(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function aY(e){var t,i;let n={};if(e.video)if("object"==typeof e.video){let i={},r=e.video;Object.keys(r).forEach(e=>{"resolution"===e?aQ(i,r.resolution):i[e]=r[e]}),n.video=i,null!=(t=n.video).deviceId||(t.deviceId={ideal:"default"})}else n.video=!!e.video&&{deviceId:{ideal:"default"}};else n.video=!1;return e.audio?"object"==typeof e.audio?(n.audio=e.audio,null!=(i=n.audio).deviceId||(i.deviceId={ideal:"default"})):n.audio={deviceId:{ideal:"default"}}:n.audio=!1,n}function aX(e){return rP(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){let i=aZ();if(i){let n=i.createAnalyser();n.fftSize=2048;let r=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield a7(t),n.getByteTimeDomainData(r);let a=r.some(e=>128!==e&&0!==e);return i.close(),!a}return!1}()})}function aZ(){var e;let t="u">typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){let i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"u">typeof window&&(null==(e=window.document)?void 0:e.body)){let e=()=>rP(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null==(t=window.document.body)||t.removeEventListener("click",e)}});i.addEventListener("statechange",()=>{var t;"closed"===i.state&&(null==(t=window.document.body)||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return i}}function a$(e){return e===a9.Source.Microphone?"audioinput":e===a9.Source.Camera?"videoinput":void 0}function a0(e){return e.split("/")[1].toLowerCase()}function a1(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?a1(e.track):{})}}function a2(e){let t,i,n=Object.assign({},e);return"object"==typeof n.audio&&n.audio.processor&&(t=n.audio.processor,n.audio=Object.assign(Object.assign({},n.audio),{processor:void 0})),"object"==typeof n.video&&n.video.processor&&(i=n.video.processor,n.video=Object.assign(Object.assign({},n.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:void 0===n?n:"function"!=typeof structuredClone?JSON.parse(JSON.stringify(n)):"object"==typeof n&&null!==n?structuredClone(Object.assign({},n)):structuredClone(n)}}function a3(e,t){return e.width*e.height<t.width*t.height}let a4=[];(E=eb||(eb={}))[E.LOW=0]="LOW",E[E.MEDIUM=1]="MEDIUM",E[E.HIGH=2]="HIGH";class a9 extends r_.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){var i;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=a9.StreamState.Active,this.isInBackgroun
2d=!1,this._currentBitrate=0,this.log=rS,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=rC(null!=(i=n.loggerName)?i:ea.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=a9.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),a1(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===a9.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===a9.Kind.Video&&this.addAppVisibilityListener(),!e&&("audio"===t&&(a4.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&a4.splice(a4.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),a6(this.mediaStreamTrack,e);let i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?eg.AudioPlaybackStarted:eg.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?eg.AudioPlaybackFailed:eg.VideoPlaybackFailed,t):"AbortError"===t.name?rS.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):rS.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(eg.ElementAttached,e),e}detach(e){try{if(e){a8(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(eg.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{a8(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(eg.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=rC(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),a4.forEach(e=>{e.parentElement||(t=!1)}),t&&a4.push(e)}}handleAppVisibilityChanged(){return rP(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==a9.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){sl()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){sl()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function a6(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,(n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks()).includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),ss()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(ss()||sr())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function a8(e,t){if(t.srcObject instanceof MediaStream){let i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}(P=n=(w=a9||(a9={})).Kind||(w.Kind={})).Audio="audio",P.Video="video",P.Unknown="unknown",(R=r=w.Source||(w.Source={})).Camera="camera",R.Microphone="microphone",R.ScreenShare="screen_share",R.ScreenShareAudio="screen_share_audio",R.Unknown="unknown",(I=a=w.StreamState||(w.StreamState={})).Active="active",I.Paused="paused",I.Unknown="unknown",w.kindToProto=function(e){switch(e){case n.Audio:return ii.AUDIO;case n.Video:return ii.VIDEO;default:return ii.DATA}},w.kindFromProto=function(e){switch(e){case ii.AUDIO:return n.Audio;case ii.VIDEO:return n.Video;default:return n.Unknown}},w.sourceToProto=function(e){switch(e){case r.Camera:return ir.CAMERA;case r.Microphone:return ir.MICROPHONE;case r.ScreenShare:return ir.SCREEN_SHARE;case r.ScreenShareAudio:return ir.SCREEN_SHARE_AUDIO;default:return ir.UNKNOWN}},w.sourceFromProto=function(e){switch(e){case ir.CAMERA:return r.Camera;case ir.MICROPHONE:return r.Microphone;case ir.SCREEN_SHARE:return r.ScreenShare;case ir.SCREEN_SHARE_AUDIO:return r.ScreenShareAudio;default:return r.Unknown}},w.streamStateFromProto=function(e){switch(e){case ne.ACTIVE:return a.Active;case ne.PAUSED:return a.Paused;default:return a.Unknown}};let a5="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function a7(e){return new aS(t=>aB.setTimeout(t,e))}function se(){return"addTransceiver"in RTCPeerConnection.prototype}function st(){return"addTrack"in RTCPeerConnection.prototype}function si(e){return"av1"===e||"vp9"===e}function sn(e){return!(!document||so())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function sr(){var e;return(null==(e=aE())?void 0:e.name)==="Firefox"}function sa(){let e=aE();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function ss(){var e;return(null==(e=aE())?void 0:e.name)==="Safari"}function so(){let e=aE();return(null==e?void 0:e.name)==="Safari"||(null==e?void 0:e.os)==="iOS"}function sc(){var e,t;return!!sl()&&(null!=(t=null==(e=navigator.userAgentData)?void 0:e.mobile)?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function sl(){return"u">typeof document}function sd(){return"ReactNative"==navigator.product}function su(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function sh(e){return su(e)?e.hostname.split(".")[0]:null}function sp(){if(e.g&&e.g.LiveKitReactNativeGlobal)return e.g.LiveKitReactNativeGlobal}
2function sm(){if(!sd())return;let e=sp();if(e)return e.platform}function sg(){if(sl())return window.devicePixelRatio;if(sd()){let e=sp();if(e)return e.devicePixelRatio}return 1}function sf(e,t){let i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){let t=parseInt(i[e],10),a=parseInt(n[e],10);if(t>a)return 1;if(t<a)return -1;if(e===r-1&&t===a)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function sv(e){for(let t of e)t.target.handleResize(t)}function sb(e){for(let t of e)t.target.handleVisibilityChanged(t)}let sk=null,sy=()=>(sk||(sk=new ResizeObserver(sv)),sk),sT=null,sS=()=>(sT||(sT=new IntersectionObserver(sb,{root:null,rootMargin:"0px"})),sT);function sC(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=document.createElement("canvas");r.width=e,r.height=t;let a=r.getContext("2d");null==a||a.fillRect(0,0,r.width,r.height),n&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,2*Math.PI,!0),a.closePath(),a.fillStyle="grey",a.fill());let[s]=r.captureStream().getTracks();if(!s)throw Error("Could not get empty media stream video track");return s.enabled=i,s}function sE(){if(!i){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),[i]=r.stream.getAudioTracks(),!i)throw Error("Could not get empty media stream audio track");i.enabled=!1}return i.clone()}class sw{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>rP(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null==(e=this.onFinally)||e.call(this)})}}function sP(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function sR(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function sI(e){switch(e.reason){case el.LeaveRequest:return e.context;case el.Cancelled:return ic.CLIENT_INITIATED;case el.NotAllowed:return ic.USER_REJECTED;case el.ServerUnreachable:return ic.JOIN_FAILURE;default:return ic.UNKNOWN_REASON}}function sD(e){return void 0!==e?Number(e):void 0}function s_(e){return void 0!==e?BigInt(e):void 0}function sO(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function sM(e){return!!e&&e.kind==a9.Kind.Audio}function sx(e){return!!e&&e.kind==a9.Kind.Video}function sA(e){return sO(e)&&sx(e)}function sN(e){return sO(e)&&sM(e)}function sL(e){return!!e&&!e.isLocal}function sU(e){return sL(e)&&sx(e)}function sj(){return"u">typeof CompressionStream}function sF(e){return e.endsWith("/")?e:"".concat(e,"/")}function sB(e,t){return e.pathname="".concat(sF(e.pathname)).concat(t),e}function sq(e){if("string"==typeof e)return nn.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return nn.fromBinary(new Uint8Array(e));throw Error("could not decode websocket message: ".concat(typeof e))}let sV="lk_e2ee";function sH(){return void 0!==window.RTCRtpScriptTransform}(D=ek||(ek={})).SetKey="setKey",D.RatchetRequest="ratchetRequest",D.KeyRatcheted="keyRatcheted",(ey||(ey={})).KeyRatcheted="keyRatcheted",(_=eT||(eT={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",_.EncryptionError="encryptionError",(eS||(eS={})).Error="cryptorError",r_.EventEmitter,(O=eC||(eC={}))[O.InvalidKey=0]="InvalidKey",O[O.MissingKey=1]="MissingKey",O[O.InternalError=2]="InternalError";class sW extends r_.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;let{kind:n,data:r}=e.data;switch(n){case"error":if(rS.error(r.error.message),r.uuid){let e=this.decryptDataRequests.get(r.uuid);if(null==e?void 0:e.reject){e.reject(r.error);break}let t=this.encryptDataRequests.get(r.uuid);if(null==t?void 0:t.reject){t.reject(r.error);break}}
2this.emit(eT.EncryptionError,r.error,r.participantIdentity);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case"enable":if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null==(t=this.room)?void 0:t.localParticipant.identity))this.emit(eT.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){let e=null==(i=this.room)?void 0:i.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(eT.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(ek.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex);break;case"decryptDataResponse":let a=this.decryptDataRequests.get(r.uuid);(null==a?void 0:a.resolve)&&a.resolve(r);break;case"encryptDataResponse":let s=this.encryptDataRequests.get(r.uuid);(null==s?void 0:s.resolve)&&s.resolve(r)}},this.onWorkerError=e=>{rS.error("e2ee worker encountered an error:",{error:e.error}),this.emit(eT.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||sH()))throw new aO("tried to setup end-to-e
2nd encryption on an unsupported browser");if(rS.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:rE.getLevel()}};this.worker&&(rS.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){rS.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):rS.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(em.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(eh.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==iT.NONE,t.identity)),e.on(eh.ConnectionStateChanged,t=>{t===ez.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==iT.NONE,e.identity)})})}).on(eh.TrackUnsubscribed,(e,t,i)=>{var n;let r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null==(n=this.worker)||n.postMessage(r)}).on(eh.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(eh.SignalConnected,()=>{if(!this.room)throw TypeError("expected room to be present on signal connect");let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{var i;this.postKey(t,e===(null!=(i=t.keyIndex)?i:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(ep.LocalSenderCreated,(e,t)=>rP(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(ep.LocalTrackPublished,e=>{if(!sx(e.track)||!so())return;let t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:a0(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(ek.SetKey,(e,t)=>this.postKey(e,null==t||t)).on(ek.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return rP(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");let t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new sw;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise})}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");let r=crypto.randomUUID(),a=new sw;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage({kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:n}}),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}})}postKey(e,t){var i;let{key:n,participantIdentity:r,keyIndex:a}=e;if(!this.worker)throw Error("could not set key, worker is missing");let s={kind:"setKey",data:{participantIdentity:r,isPublisher:r===(null==(i=this.room)?void 0:i.localParticipant.identity),key:n,keyIndex:a,updateCurrentKeyIndex:t}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker)this.worker.postMessage({kind:"enable",data:{enabled:e,participantIdentity:t}});else throw 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(!(null==(t=this.room)?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:e}})}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?a0(i.mimeType):void 0)}}setupE2EESender(e,t){if(!sO(e)||!t){t||rS.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,n){return rP(this,void 0,void 0,function*(){if(this.worker){if(sH()&&!sa())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:t,codec:n});else{if(sV in e&&n)return void this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}});let r=e.writableStream,a=e.readableStream;if(!r||!a){let t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,a=t.readable}let s={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:n,participantIdentity:i,isReuse:sV in e}};this.worker.postMessage(s,[a,r])}e[sV]=!0}})}handleSender(e,t,i){var n;if(!(sV in e)&&this.worker){if(!(null==(n=this.room)?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(sH()&&!sa()){rS.info("initialize script transform");let n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{rS.info("initialize encoded streams");let n=e.createEncodedStreams(),r={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(r,[n.readable,n.writable])}e[sV]=!0}}}class sG{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new sG),this._instance}addFailedConnectionAttempt(e){var t;let i=sh(new URL(e));if(!i)return;let n=null!=(t=this.failedConnectionAttempts.get(i))?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,a7(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){let t=new URL(e),i=t&&sh(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),i=t&&sh(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}sG._instance=null;let sz="default";class sK{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new sK),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return rP(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;if((null==(n=sK.userMediaPromiseMap)?void 0:n.size)>0){rS.debug("awaiting getUserMedia promise");try{e?yield sK.userMediaPromiseMap.get(e):yield Promise.all(sK.userMediaPromiseMap.values())}catch(e){rS.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(i&&!(ss()&&t.hasDeviceInUse(e))&&(0===r.filter(t=>t.kind===e).length||r.some(t=>{let i=""===t.label,n=!e||t.kind===e;return i&&n}))){let t=yield navigator.mediaDevices.getUserMedia({video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}});r=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEac
2h(e=>{e.stop()})}return t._previousDevices=r,e&&(r=r.filter(t=>t.kind===e)),r}()})}normalizeDeviceId(e,t,i){return rP(this,void 0,void 0,function*(){if(t!==sz)return t;let n=yield this.getDevices(e),r=n.find(e=>e.deviceId===sz);if(!r)return void rS.warn("could not reliably determine default device");let a=n.find(e=>e.deviceId!==sz&&e.groupId===(null!=i?i:r.groupId));return a?null==a?void 0:a.deviceId:void rS.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?sK.userMediaPromiseMap.has(e):sK.userMediaPromiseMap.size>0}}sK.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],sK.userMediaPromiseMap=new Map;class sJ{static u16(e){return new sJ(e,65535)}static u32(e){return new sJ(e,0xffffffff)}constructor(e,t){if(this.value=e,e<0)throw Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new sJ(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let e=this.value;return this.increment(),new sJ(e,this.maxSize)}isBefore(e){let t=this.value>>>0,i=(e.value>>>0)-t>>>0;return 0!==i&&i<this.maxSize+1}}class sQ{static fromRtpTicks(e){return new sQ(e,9e4)}static rtpRandom(){let e=Math.round(0xffffffff*Math.random());return sQ.fromRtpTicks(e)}constructor(e,t){this.timestamp=sJ.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new sQ(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class sY{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new sY(t,new Date,e)}static startingAtTime(e,t,i){return new sY(i,e,t)}static rtpStartingNow(e){return sY.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return sY.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=sY.durationInMsToTicks(t,this.rateInHz),n=this.base.clone();return n.wrappingAdd(i),n.isBefore(this.previous)&&(n=this.previous),this.previous=n.clone(),n.clone()}static durationInMsToTicks(e,t){return Math.round((1e6*e*t+5e8)/1e9)}}function sX(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error("Error coercing ".concat(e," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}(M=eE||(eE={}))[M.Reserved=0]="Reserved",M[M.TooLarge=1]="TooLarge";class sZ extends aD{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=eE[t]}isReason(e){return this.reason===e}static tooLarge(){return new sZ("Value too large to be a valid track handle",eE.TooLarge)}static reserved(e){return new sZ("0x".concat(e.toString(16)," is a reserved value."),eE.Reserved)}}let s$={fromNumber(e){if(0===e)throw sZ.reserved(e);if(e>65535)throw sZ.tooLarge();return e}};class s0{constructor(){this.value=0}get(){return(this.value+=1,this.value>65535)?null:this.value}}let s1=e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==iT.NONE});(x=ew||(ew={}))[x.WAITING=0]="WAITING",x[x.RUNNING=1]="RUNNING",x[x.COMPLETED=2]="COMPLETED";class s2{constructor(){this.pendingTasks=new Map,this.taskMutex=new eZ,this.nextTaskIndex=0}run(e){return rP(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ew.WAITING};this.pendingTasks.set(t.id,t);let i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ew.RUNNING,yield e()}finally{t.status=ew.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return rP(this,void 0,void 0,function*(){return this.run(()=>rP(this,void 0,void 0,function*(){}))})}
2snapshot(){return Array.from(this.pendingTasks.values())}}class s3{get readyState(){return this.ws.readyState}constructor(e){var t,i;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null==(t=n.signal)?void 0:t.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,null!=(i=n.protocols)?i:[]);r.binaryType="arraybuffer",this.ws=r;const a=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return r.close(e,t)};this.opened=new aS((e,t)=>{let i=()=>{t(a_.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let{data:i}=t;return e.enqueue(i)},r.onerror=t=>e.error(t)},cancel:a}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",i)},r.addEventListener("error",i)}),this.closed=new aS((e,t)=>{let i=()=>rP(this,void 0,void 0,function*(){let i=new aS(e=>{r.readyState===WebSocket.CLOSED||r.addEventListener("close",t=>{e(t)},{once:!0})}),n=yield aS.race([a7(250),i]);n?e(n):t(a_.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=t=>{let{code:n,reason:a}=t;e({closeCode:n,reason:a}),r.removeEventListener("error",i)},r.addEventListener("error",i)}),n.signal&&(n.signal.onabort=()=>r.close()),this.close=a}}let s4=["syncState","trickle","offer","answer","simulate","leave"];
2(A=eP||(eP={}))[A.CONNECTING=0]="CONNECTING",A[A.CONNECTED=1]="CONNECTED",A[A.RECONNECTING=2]="RECONNECTING",A[A.DISCONNECTING=3]="DISCONNECTING",A[A.DISCONNECTED=4]="DISCONNECTED";class s9{get currentState(){return this.state}get isDisconnected(){return this.state===eP.DISCONNECTING||this.state===eP.DISCONNECTED}get isEstablishingConnection(){return this.state===eP.CONNECTING||this.state===eP.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.rtt=0,this.state=eP.DISCONNECTED,this.log=rS,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=rC(null!=(e=i.loggerName)?e:ea.Signal),this.loggerContextCb=i.loggerContextCb,this.useJSON=t,this.requestQueue=new s2,this.queuedRequests=[],this.closingLock=new eZ,this.connectionLock=new eZ,this.state=eP.DISCONNECTED}get logContext(){var e,t;return null!=(t=null==(e=this.loggerContextCb)?void 0:e.call(this))?t:{}}join(e,t,i,n){return rP(this,arguments,void 0,function(e,t,i,n){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){return r.state=eP.CONNECTING,r.options=i,yield r.connect(e,t,i,n,a,s)}()})}reconnect(e,t,i,n){return rP(this,void 0,void 0,function*(){return this.options?(this.state=eP.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath)):void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)})}connect(e,t,i,n){return rP(this,arguments,void 0,function(e,t,i,n){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){var o,c,l,d,u;let h,p,m=yield r.connectionLock.lock();r.connectOptions=i,r.useV0SignalPath=a;let g=(p=new iz({sdk:iK.JS,protocol:16,version:"2.18.3"}),sd()&&(p.os=null!=(o=sm())?o:""),p),f=(function(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=function(e,t){let i=new URL(e.startsWith("http")?e.replace(/^(http)/,"ws"):e);return t.forEach((e,t)=>{i.searchParams.set(t,e)}),sB(i,"rtc")}(e,t);return i?n:sB(n,"v1")})(e,a?(c=t,l=g,d=i,(h=new URLSearchParams).set("access_token",c),d.reconnect&&(h.set("reconnect","1"),d.sid&&h.set("sid",d.sid)),h.set("auto_subscribe",d.autoSubscribe?"1":"0"),h.set("sdk",sd()?"reactnative":"js"),h.set("version",l.version),h.set("protocol",l.protocol.toString()),l.deviceModel&&h.set("device_model",l.deviceModel),l.os&&h.set("os",l.os),l.osVersion&&h.set("os_version",l.osVersion),l.browser&&h.set("browser",l.browser),l.browserVersion&&h.set("browser_version",l.browserVersion),d.adaptiveStream&&h.set("adaptive_stream","1"),d.reconnectReason&&h.set("reconnect_reason",d.reconnectReason.toString()),(null==(u=navigator.connection)?void 0:u.type)&&h.set("network",navigator.connection.type),h):yield function(e,t,i,n){return rP(this,void 0,void 0,function*(){let r,a,s=new URLSearchParams;s.set("access_token",e);let o=new n4({clientInfo:t,connectionSettings:new n3({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0,publisherOffer:n});i.reconnectReason&&(o.reconnectReason=i.reconnectReason);let c=o.toBinary();if(sj()){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(c)),t.close();let i=[],n=e.readable.getReader();for(;;){let{done:e,value:t}=yield n.read();if(e)break;i.push(t)}let s=new Uint8Array(i.reduce((e,t)=>e+t.length,0)),o=0;for(let e of i)s.set(e,o),o+=e.length;r=s,a=n6.GZIP}else r=c,a=n6.NONE;let l=new n9({joinRequest:r,compression:a}).toBinary();return s.set("join_request",btoa(Array.from(l,e=>String.fromCodePoint(e)).join("")).replace(/\+/g,"-").replace(/\//g,"_")),s})}(t,g,i,s),a).toString(),v=sB(new URL(sR(f)),"validate").toString();return new Promise((e,t)=>
2rP(r,void 0,void 0,function*(){var r,a;try{let s=!1,o=e=>rP(this,void 0,void 0,function*(){if(s)return;s=!0;let i=e instanceof Event?e.currentTarget:e,n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;let i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(i,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),c(),t(a_.cancelled(n))});null==n||n.addEventListener("abort",o);let c=()=>{clearTimeout(l),null==n||n.removeEventListener("abort",o)},l=setTimeout(()=>{o(a_.timeout("room connection has timed out (signal)"))},i.websocketTimeout),d=(e,t)=>{this.handleSignalConnected(e,l,t)},u=new URL(f);u.searchParams.has("access_token")&&u.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(u),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new s3(f);try{this.ws.closed.then(e=>{var i;this.isEstablishingConnection&&t(a_.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state})),this.state===eP.CONNECTED&&this.handleOnClose(null!=(i=e.reason)?i:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(a_.internal("Websocket error during a (re)connection attempt: ".concat(e)))});let n=yield this.ws.opened.catch(e=>rP(this,void 0,void 0,function*(){if(this.state!==eP.CONNECTED){this.state=eP.DISCONNECTED,clearTimeout(l);let i=yield this.handleConnectionError(e,v);t(i);return}this.handleWSError(e),t(e)}));if(clearTimeout(l),!n)return;let s=n.readable.getReader();this.streamWriter=n.writable.getWriter();let o=yield s.read();if(s.releaseLock(),!o.value)throw a_.internal("no message received as first message");let c=sq(o.value),u=this.validateFirstMessage(c,null!=(r=i.reconnect)&&r);if(!u.isValid)return void t(u.error);(null==(a=c.message)?void 0:a.case)==="join"&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.onJoined&&this.onJoined(c.message.value));let h=u.shouldProcessFirstMessage?c:void 0;d(n,h),e(u.response)}catch(e){t(e)}finally{c()}}finally{m()}}))}()})}startReadingLoop(e,t){return rP(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield a7(this.signalLatency));let{done:t,value:i}=yield e.read();if(t)break;let n=sq(i);this.handleSignalResponse(n)}})}close(){return rP(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([eP.DISCONNECTING||eP.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");let n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=eP.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,a7(250)])}}catch(t){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=eP.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:s8(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:s8(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new nh({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new np({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return rP(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){let r=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new nD({requestId:r,metadata:e,name:t,attributes:n}
2)}),r}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new nI({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new nV({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:to.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new nQ({timestamp:to.parse(Date.now()),rtt:to.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new nE({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new nP({reason:ic.CLIENT_INITIATED,action:nR.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new ns({pubHandle:e,name:t,encryption:i?iT.GCM:iT.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new nc({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new nT({updates:[new nS({trackSid:e,subscribe:t})]})})}sendRequest(e){return rP(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){let n;if(!i&&(n=s4.indexOf(e.case)>=0,rS.trace("request allowed to bypass queue:",{canPass:n,req:e}),!n)&&t.state===eP.RECONNECTING)return void t.queuedRequests.push(()=>rP(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield a7(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);let r=new ni({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,i;let n=e.message;if(void 0==n)return void this.log.debug("received unsupported message",this.logContext);let r=!1;if("answer"===n.case){let e=s6(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){let e=s6(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){let e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!=(t=n.value.participants)?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!=(i=n.value.speakers)?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement
2(n.value):"publishDataTrackResponse"===n.case?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(n.value):"unpublishDataTrackResponse"===n.case?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(n.value):"dataTrackSubscriberHandles"===n.case?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(n.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return rP(this,void 0,void 0,function*(){if(this.state===eP.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){(this.clearPingTimeout(),this.pingTimeoutDuration)?this.pingTimeout=aB.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&aB.clearTimeout(this.pingTimeout)}startPingInterval(){(this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration)?(this.log.debug("start ping interval",this.logContext),this.pingInterval=aB.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&aB.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=eP.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,r,a,s;if((null==(i=e.message)?void 0:i.case)==="join")return{isValid:!0,response:e.message.value};if(this.state===eP.RECONNECTING&&(null==(n=e.message)?void 0:n.case)!=="leave")if((null==(r=e.message)?void 0:r.case)==="reconnect")return{isValid:!0,response:e.message.value};else return this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0};return this.isEstablishingConnection&&(null==(a=e.message)?void 0:a.case)==="leave"?{isValid:!1,error:a_.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:a_.internal("Unexpected first message")}:{isValid:!1,error:a_.internal("did not receive join response, got ".concat(null==(s=e.message)?void 0:s.case," instead"))}}handleConnectionError(e,t){return rP(this,void 0,void 0,function*(){try{let i=yield fetch(t);switch(i.status){case 404:return a_.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:let n=yield i.text();return a_.notAllowed(n,i.status)}if(e instanceof a_)return e;return a_.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(e){return e instanceof a_?e:a_.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}})}}function s6(e){let t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function s8(e,t){return new nb({sdp:e.sdp,type:e.type,id:t})}class s5{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;)if(this.buffer[0].sequence<=e)this.pop();else break}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class s7{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();let n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){let t=this._map.get(e);if(t)return t.expiresAt<Date.now()?void this._map.delete(e):t.value}has(e){let t=this._map.get(e);
2return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){for(let[t,i]of(this.cleanup(),this._map.entries()))i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],i=this.asValueMap();for(let[n,r]of i.entries())t.push(e(r,n,i));return t}asValueMap(){let e=new Map;for(let[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var oe={},ot={},oi={exports:{}};function on(){if(eR)return oi.exports;eR=1;var e=oi.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=(null!=e.raddr?" raddr %s rport %d":"%v%v")+(null!=e.tcptype?" tcptype %s":"%v"),null!=e.generation&&(t+=" generation %d"),t+=(null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","max
2MessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+((null!=e.id?"id=%s %s":"%v%s")+(null!=e.mediaClockValue?"=%s":"")+(null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":""))}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),oi.exports}var or=function(){if(eO)return oe;eO=1;var e=function(){var e,t,i,n,r,a;return eI?ot:(eI=1,e=function(e){return String(Number(e))===e?Number(e):e},t=function(t,i,n,r){if(r&&!n)i[r]=e(t[1]);else for(var a=0;a<n.length;a+=1)null!=t[a+1]&&(i[n[a]]=e(t[a+1]))},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var a=e.push?{}:r?i[e.name]:i;t(n.match(e.reg),a,e.names,e.name),e.push&&i[e.push].push(a)},n=on(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/),ot.parse=function(e){var t={},a=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach(function(e){var t=e[0],r=e.slice(2);"m"===t&&(a.push({rtp:[],fmtp:[]}),s=a[a.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(r))return i(c,s,r)}}),t.media=a,t},a=function(t,i){var n=i.split(/=(.+)/,2);return 2===n.length?t[n[0]]=e(n[1]):1===n.length&&i.length>1&&(t[n[0]]=void 0),t},ot.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},ot.parseFmtpConfig=ot.parseParams,ot.parsePayloads=function(e){return e.toString().split(" ").map(Number)},ot.parseRemoteCandidates=function(t){for(var i=[],n=t.split(" ").map(e),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},ot.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})})},ot.parseSimulcastStreamList=function(t){return t.split(";").map(function(t){return t.split(",").map(function(t){var i,n=!1;return"~"!==t[0]?i=e(t):(i=e(t.substring(1,t.length)),n=!0),{scid:i,paused:n}})})},ot)}(),t=function(){if(e_)return eD;e_=1;var e=on(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,r=n.length;return e.replace(t,function(e){if(i>=r)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var a=0;a<t.names.length;a+=1){var s=t.names[a];t.name?r.push(n[t.name][s]):r.push(n[t.names[a]])}else r.push(n[t.name]);return i.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];return eD=function(t,i){i=i||{}
2,null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var s=i.outerOrder||r,o=i.innerOrder||a,c=[];return s.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})}),t.media.forEach(function(t){c.push(n("m",e.m[0],t)),o.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})})}),c.join("\r\n")+"\r\n"}}();return oe.grammar=on(),oe.write=t,oe.parse=e.parse,oe.parseParams=e.parseParams,oe.parseFmtpConfig=e.parseFmtpConfig,oe.parsePayloads=e.parsePayloads,oe.parseRemoteCandidates=e.parseRemoteCandidates,oe.parseImageAttributes=e.parseImageAttributes,oe.parseSimulcastStreamList=e.parseSimulcastStreamList,oe}();function oa(e){var t,i;let n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=null!=(t=a.isImmediate)&&t,o=null!=(i=a.callback)&&i,c=a.maxWait,l=Date.now(),d=[],u=function(){for(var t=arguments.length,i=Array(t),a=0;a<t;a++)i[a]=arguments[a];let u=this;return new Promise((t,a)=>{let h=s&&void 0===n;if(void 0!==n&&aB.clearTimeout(n),n=aB.setTimeout(function(){if(n=void 0,l=Date.now(),!s){let t=e.apply(u,i);o&&o(t),d.forEach(e=>{let{resolve:i}=e;return i(t)}),d=[]}},function(){if(void 0!==c){let e=Date.now()-l;if(e+r>=c)return c-e}return r}()),h){let n=e.apply(u,i);return o&&o(n),t(n)}d.push({resolve:t,reject:a})})};return u.cancel=function(e){void 0!==n&&aB.clearTimeout(n),d.forEach(t=>{let{reject:i}=t;return i(e)}),d=[]},u}let os="negotiationStarted",oo="negotiationComplete",oc="rtpVideoPayloadTypes";class ol extends r_.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.log=rS,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=oa(e=>rP(this,void 0,void 0,function*(){this.emit(os);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=rC(null!=(t=i.loggerName)?t:ea.PCTransport),this.loggerOptions=i,this.config=e,this._pc=this.createPC(),this.offerLock=new eZ}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null==(t=this.onIceCandidate)||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null==(t=this.onIceCandidateError)||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null==(t=this.onIceConnectionStateChange)||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null==(t=this.onSignalingStatechange)||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null==(t=this.onConnectionStateChange)||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null==(t=this.onDataChannel)||t.call(this,e)},e.ontrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null==(t=(e=this.loggerOptions).loggerContextCb)?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return rP(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return rP(this,void 0,void 0,function*(){var i,n,r,a;let s;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;if("offer"===e.type){let t,i,n,s,{stereoMids:o,nackMids:c}=(r=e,t=[],i=[],n=or.parse(null!=(a=r.sdp)?a:""),s=0,n.media.forEac
2h(e=>{var n;let r=oh(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),(null==(n=e.rtcpFb)?void 0:n.some(e=>e.payload===s&&"nack"===e.type))&&i.push(r),e.fmtp.some(e=>e.payload===s&&(e.config.includes("sprop-stereo=1")&&t.push(r),!0)))}),{stereoMids:t,nackMids:i});this.remoteStereoMids=o,this.remoteNackMids=c}else if("answer"===e.type){if(this.pendingInitialOffer){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=or.parse(null!=(i=e.sdp)?i:"");t.media.forEach(e=>{ou(e)}),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(e,or.write(t))}let t=or.parse(null!=(n=e.sdp)?n:"");t.media.forEach(e=>{let t=oh(e.mid);"audio"===e.type&&this.trackBitrates.some(i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;let r=!1;for(let t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),r=!0;break}return!r&&i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0})}),s=or.write(t)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit
2(oo),e.sdp&&or.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(oc,e.rtp)})),!0})}createInitialOffer(){return rP(this,void 0,void 0,function*(){var e;let t=yield this.offerLock.lock();try{if("stable"!==this.pc.signalingState)return void this.log.warn("signaling state is not stable, cannot create initial offer",this.logContext);let t=this.latestOfferId+1;this.latestOfferId=t;let i=yield this.pc.createOffer();this.pendingInitialOffer={sdp:i.sdp,type:i.type};let n=or.parse(null!=(e=i.sdp)?e:"");return n.media.forEach(e=>{ou(e)}),i.sdp=or.write(n),{offer:i,offerId:t}}finally{t()}})}createAndSendOffer(e){return rP(this,void 0,void 0,function*(){var t;let i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&("have-local-offer"===this._pc.signalingState||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if((null==e?void 0:e.iceRestart)&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0,this.log.debug("requesting renegotiation",Object.assign({},this.logContext));return}}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);let i=this.latestOfferId+1;this.latestOfferId=i;let n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));let r=or.parse(null!=(t=n.sdp)?t:"");if(r.media.forEach(e=>{ou(e),"audio"===e.type?od(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i||(si(t.codec)&&!ss()&&this.ensureVideoDDExtensionForSVC(e,r),!si(t.codec)))return!0;let n=Math.round(.7*t.maxbr);for(let t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,or.write(r)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return rP(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),i=or.parse(null!=(e=t.sdp)?e:"");return i.media.forEach(e=>{ou(e),"audio"===e.type&&od(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,or.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new aA("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 aA("PC closed, cannot configure");return null==(t=this._pc)?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null==(e=this._pc)?void 0:e.removeTrack)}removeTrack(e){var t;return null==(t=this._pc)?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.connectionState)?t:"closed"}getICEConnectionState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.iceConnectionState)?t:"closed"}getSignallingState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.signalingState)?t:"closed"}getTransceivers(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.getTransceivers())?t:[]}getSenders(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.getSenders())?t:[]}getLocalDescription(){var e;return null==(e=this._pc)?void 0:e.localDescription}getRemoteDescription(){var e;return null==(e=this.pc)?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return rP(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;let r=null==(e=i.get(t))?void 0:e.remoteCandidateId;if(void 0!==r)return n.get(r)})}
2setMungedSDP(e,t,i){return rP(this,void 0,void 0,function*(){if(t){let n=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let t="unknown error";r instanceof Error?t=r.message:"string"==typeof r&&(t=r);let n={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(n.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:n})),new aN(t)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null==(i=e.ext)?void 0:i.some(e=>e.uri===a5))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;"video"===t.type&&(null==(i=t.ext)||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null==(n=e.ext)||n.push({value:this.ddExtID,uri:a5})}}}function od(e,t,i){let n=oh(e.mid),r=0;e.rtp.some(e=>"opus"===e.codec&&(r=e.payload,!0)),r>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some(e=>e.payload===r&&"nack"===e.type)&&e.rtcpFb.push({payload:r,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some(e=>e.payload===r&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function ou(e){if(e.connection){let t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function oh(e){return"number"==typeof e?e.toFixed(0):e}let op={audioPreset:ev.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:aK.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!0,preConnectBuffer:!1},om={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},og={deviceId:{ideal:"default"},resolution:aG.h720.resolution},of={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:rw}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},ov={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};(N=eM||(eM={}))[N.NEW=0]="NEW",N[N.CONNECTING=1]="CONNECTING",N[N.CONNECTED=2]="CONNECTED",N[N.FAILED=3]="FAILED",N[N.CLOSING=4]="CLOSING",N[N.CLOSED=5]="CLOSED";class ob{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var n;this.peerConnectionTimeout=ov.peerConnectionTimeout,this.log=rS,this.updateState=()=>{var e,t;let i=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>"connected"===e)?this.state=eM.CONNECTED:n.some(e=>"failed"===e)?this.state=eM.FAILED:n.some(e=>"connecting"===e)?this.state=eM.CONNECTING:n.every(e=>"closed"===e)?this.state=eM.CLOSED:n.some(e=>"closed"===e)?this.state=eM.CLOSING:n.every(e=>"new"===e)&&(this.state=eM.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(eM[i]," to ").concat(eM[this.state]),this.logContext),null==(e=this.onStateChange)||e.call(this,this.state,this.publisher.getConnectionState(),null==(t=this.subscriber)?void 0:t.getConnectionState()))},this.log=rC(null!=(n=t.loggerName)?n:ea.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired="subscriber-primary"!==e,this.isSubscriberConnectionRequired="subscriber-primary"===e,this.publisher=new ol(i,t),this._mode=e,"publisher-only"!==e&&(this.subscriber=new ol(i,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null==(t=this.onIceCandidate)||t.call(this,e,i7.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null==(t=this.onDataChannel)||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null==(t=this.onIceCandidate)||t.call(this,e,i7.PUBLISHER)},this.publisher.onTrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null==(i=this.onPublisherOffer)||i.call(this,e,t)},this.state=eM.NEW,this.connectionLock=new eZ,this.remoteOfferLock=new eZ}get logContext(){var e,t;return Object.assign({},null==(t=(e=this.loggerOptions).loggerContextCb)?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return rP(this,void 0,void 0,function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null==(e=this.subscriber)?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return rP(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return rP(this,void 0,void 0,function*(){var i;t===i7.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null==(i=this.subscriber)?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return rP(this,void 0,void 0,function*(){var i,n,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null==(i=this.subscriber)?void 0:i.getSignallingState().toString()}));let a=yield this.remoteOfferLock.lock();try{if(!(yield null==(n=this.subscriber)?void 0:n.setRemoteDescription(e,t)))return;return yield null==(r=this.subscriber)?void 0:r.createAndSetAnswer()}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null==(i=this.subscriber)||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return rP(this,void 0,void 0,function*(){var i;let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null==(i=this.requiredTransports)?void 0:i.map(i=>
2this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return rP(this,void 0,void 0,function*(){return new aS((t,i)=>rP(this,void 0,void 0,function*(){let n=setTimeout(()=>{i(new aN("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(n),this.publisher.off(os,s),e.signal.removeEventListener("abort",a)},a=()=>{r(),i(new aN("negotiation aborted"))},s=()=>{e.signal.aborted||(clearTimeout(n),n=setTimeout(()=>{r(),i(new aN("negotiation timed out"))},this.peerConnectionTimeout))};e.signal.addEventListener("abort",a),this.publisher.on(os,s),this.publisher.once(oo,()=>{r(),t()}),yield this.publisher.negotiate(e=>{r(),e instanceof Error?i(e):i(Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){let t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e);return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===i7.PUBLISHER||e===i7.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return rP(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,r)=>rP(i,void 0,void 0,function*(){let i=()=>{this.log.warn("abort transport connection",this.logContext),aB.clearTimeout(a),r(a_.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);let a=aB.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),r(a_.internal("could not establish pc connection"))},n);for(;this.state!==eM.CONNECTED;)if(yield a7(50),null==t?void 0:t.signal.aborted)return void r(a_.cancelled("room connection has been cancelled"));aB.clearTimeout(a),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class ok{static fetchRegionSettings(e,t,i){return rP(this,void 0,void 0,function*(){let n=yield ok.fetchLock.lock();try{var r;let n=yield fetch("".concat((r=e,"".concat(r.protocol.replace("ws","http"),"//").concat(r.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){let e=function(e){var t;let i=e.get("Cache-Control");if(i){let e=null==(t=i.match(/(?:^|[,\s])max-age=(\d+)/))?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers);return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:e?1e3*e:5e3}}if(401===n.status)throw a_.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status);throw a_.internal("Could not fetch region settings: ".concat(n.statusText))}catch(e){if(e instanceof a_)throw e;if(null==i?void 0:i.aborted)throw a_.cancelled("Region fetching was aborted");throw a_.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{n()}})}static scheduleRefetch(e,t,i){return rP(this,void 0,void 0,function*(){clearTimeout(ok.settingsTimeouts.get(e.hostname)),ok.settingsTimeouts.set(e.hostname,setTimeout(()=>rP(this,void 0,void 0,function*(){try{let i=yield ok.fetchRegionSettings(e,t);ok.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof a_&&n.reason===el.NotAllowed)return void rS.debug("token is not valid, cancelling auto region refresh");rS.debug("auto refetching of region settings failed",{error:n}),ok.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){ok.cache.set(e.hostname,i),ok.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){let t=ok.settingsTimeouts.get(e);t&&(clearTimeout(t),ok.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=ok.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>
2{let t=ok.connectionTrackers.get(e);t&&0===t.connectionCount&&(rS.debug("stopping region refetch after disconnect delay",{hostname:e}),ok.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){let t=ok.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){let e=this.serverUrl.hostname,t=ok.connectionTrackers.get(e);t||(t={connectionCount:0},ok.connectionTrackers.set(e,t)),t.connectionCount++,ok.cancelCleanup(e)}notifyDisconnected(){let e=this.serverUrl.hostname,t=ok.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&ok.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return su(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return rP(this,void 0,void 0,function*(){return ok.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return rP(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=ok.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),ok.updateCachedRegionSettings(this.serverUrl,this.token,t));let i=t.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(!(i.length>0))return null;{let e=i[0];return this.attemptedRegions.push(e),rS.debug("next region: ".concat(e.region)),e.url}})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){ok.updateCachedRegionSettings(this.serverUrl,this.token,e)}}ok.cache=new Map,ok.settingsTimeouts=new Map,ok.connectionTrackers=new Map,ok.fetchLock=new eZ;class oy extends Error{constructor(e,t,i){super(t),this.code=e,this.message=oS(t,oy.MAX_MESSAGE_BYTES),this.data=i?oS(i,oy.MAX_DATA_BYTES):void 0}static fromProto(e){return new oy(e.code,e.message,e.data)}toProto(){return new iV({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new oy(oy.ErrorCode[e],oy.ErrorMessage[e],t)}}function oT(e){return new TextEncoder().encode(e).length}function oS(e,t){if(oT(e)<=t)return e;let i=0,n=e.length,r=new TextEncoder;for(;i<n;){let a=Math.floor((i+n+1)/2);r.encode(e.slice(0,a)).length<=t?i=a:n=a-1}return e.slice(0,i)}function oC(e,t){let i,n;return t?("bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp)?0:(i-n)*8e3/(e.timestamp-t.timestamp):0}oy.MAX_MESSAGE_BYTES=256,oy.MAX_DATA_BYTES=15360,oy.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},oy.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};let oE="u">typeof MediaRecorder,ow=oE?MediaRecorder:class{constructor(){throw Error("MediaRecorder is not available in this environment")}};class oP extends ow{constructor(e,t){let i,n;if(!oE)throw Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);const r=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",a),null==n||n.close(),n=void 0},a=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",a),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>rP(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer)i=new Uint8Array((yield t.data.arrayBuffer()));else if(t.data.byteArray)i=t.data.byteArray;else throw Error("no data available!");void 0!==n&&e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{r()}}),this.addEventListener("stop",r),this.addEventListener("error",a)}}class oR extends a9{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=oa(()=>rP(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>rP(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>
2{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(eg.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new eZ,this.pauseUpstreamLock=new eZ,this.trackChangeLock=new eZ,this.trackChangeLock.lock().then(t=>rP(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==a9.Kind.Video)return;let{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 null!=(t=null==(e=this.processor)?void 0:e.processedTrack)?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,i){return rP(this,void 0,void 0,function*(){var n;let r;if(e!==this._mediaStreamTrack||t){if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{a8(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(a6(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&(null==(n=this.sender.transport)?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(null!=r?r:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!!i||!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{a6(null!=r?r:e,t)}))}})}waitForDimensions(){return rP(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===a9.Kind.Audio)throw Error("cannot get dimensions for audio tracks");(null==(i=aE())?void 0:i.os)==="iOS"&&(yield a7(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield a7(50)}throw new aM("unable to get track dimensions after timeout")}()})}setDeviceId(e){return rP(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===sP(e)||((this._constraints.deviceId=e,this.isMuted)?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),sP(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return rP(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){if(e.source===a9.Source.ScreenShare)return;let{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),r=e.kind===a9.Kind.Audio?"audioinput":"videoinput";return t?sK.getInstance().normalizeDeviceId(r,i,n):i}()})}mute(){return rP(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return rP(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return rP(this,void 0,void 0,function*(){let i=yield this.trackChangeLock.lock();try{let i,n;if(!this.sender)throw new aM("unable to replace an unpublished track");return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e,t){return rP(this,void 0,void 0,function*(){this.manuallyStopped=!1;let i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let{deviceId:i,facingMode:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,n=Object.getOwnPropertySymbols(e);r<n.length;r++)0>t.indexOf(n[r])&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]]);return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let a={audio:!1,video:!1};this.kind===a9.Kind.Video?a.video=!i&&!n||{deviceId:i,facingMode:n}:a.audio=!i||Object.assign({deviceId:i}
2,r),this.attachedElements.forEach(e=>{a8(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let s=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===a9.Kind.Video&&(yield s.applyConstraints(r)),s.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(s,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(eg.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),(this.isMuted!==e||this._mediaStreamTrack.enabled===e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?eg.Muted:eg.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return rP(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),sc()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null==(e=this.processor)||e.destroy(),this.processor=void 0}pauseUpstream(){return rP(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(eg.UpstreamPaused,this);let t=aE();if((null==t?void 0:t.name)==="Safari"&&0>sf(t.version,"12.0"))throw new aO("pauseUpstream is not supported on Safari < 12.");(null==(e=this.sender.transport)?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return rP(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(eg.UpstreamResumed,this),(null==(e=this.sender.transport)?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return rP(this,void 0,void 0,function*(){var e;if(null==(e=this.sender)?void 0:e.getStats)return yield this.sender.getStats()})}setProcessor(e){return rP(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;let r=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);let r=document.createElement(t.kind),a={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(a),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(a6(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&i&&(a8(t._mediaStreamTrack,e),a6(t.processor.processedTrack,e));yield null==(n=t.sender)?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(eg.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return rP(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){let i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}}()})}internalStopProcessor(){return rP(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null==(i=e.processor.processedTrack)||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null==(n=e.processorElement)||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(eg.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!oE)return void this.log.warn("MediaRecorder is not available, cannot start prec
2onnect buffer",this.logContext);if(this.localTrackRecorder)return void this.log.warn("preconnect buffer already started");{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new oP(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null==(e=this.localTrackRecorder)?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null==(e=this.localTrackRecorder)?void 0:e.mimeType}}class oI extends oR{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,a9.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>rP(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=oC(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(eg.AudioTrackFeatureUpdate,this,iu.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(eg.AudioTrackFeatureUpdate,this,iu.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return rP(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source===a9.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return rP(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;return this.source===a9.Source.Microphone&&(this.stopOnMute||"ended"===this._mediaStreamTrack.readyState||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return rP(this,void 0,void 0,function*(){let t;if(e){let i=aY({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e,t){let i=Object.create(null,{restart:{get:()=>super.restart}});return rP(this,void 0,void 0,function*(){let n=yield i.restart.call(this,e,t);return this.checkForSilence(),n})}startMonitor(){!sl()||this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}setProcessor(e){return rP(this,void 0,void 0,function*(){var t;let i=yield this.trackChangeLock.lock();try{if(!sd()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());let i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null==(t=this.sender)?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit
2(eg.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return rP(this,void 0,void 0,function*(){var e;let t;if(null==(e=this.sender)?void 0:e.getStats)return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return rP(this,void 0,void 0,function*(){let e=yield aX(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(eg.AudioSilenceDetected)),e})}}let oD=Object.values(aG),o_=Object.values(az),oO=Object.values(aK),oM=[aG.h180,aG.h360],ox=[az.h180,az.h360],oA=["q","h","f"];function oN(e,t,i,n){var r,a,s;let o,c=null==n?void 0:n.videoEncoding;e&&(c=null==n?void 0:n.screenShareEncoding);let l=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!c&&!l&&!d||!t||!i)return[{}];c||(c=function(e,t,i,n){let r=function(e,t,i){if(e)return oO;let n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?oD:o_}(e,t,i),{encoding:a}=r[0],s=Math.max(t,i);for(let e=0;e<r.length;e+=1){let t=r[e];if(a=t.encoding,t.width>=s)break}if(n)switch(n){case"av1":case"h265":(a=Object.assign({},a)).maxBitrate=.7*a.maxBitrate;break;case"vp9":(a=Object.assign({},a)).maxBitrate=.85*a.maxBitrate}return a}(e,t,i,u),rS.debug("using video encoding",c));let h=c.maxFramerate,p=new aq(t,i,c.maxBitrate,c.maxFramerate,c.priority);if(d&&si(u)){let e=new oF(d),t=[];if(e.spatial>3)throw Error("unsupported scalabilityMode: ".concat(d));let i=aE();if(so()||sd()||(null==i?void 0:i.name)==="Chrome"&&0>sf(null==i?void 0:i.version,"113")){let n="h"==e.suffix?2:3,r=((s=i)||(s=aE()),(null==s?void 0:s.name)==="Safari"&&sf(s.version,"18.3")>0||(null==s?void 0:s.os)==="iOS"&&!!(null==s?void 0:s.osVersion)&&sf(s.osVersion,"18.3")>0);for(let i=0;i<e.spatial;i+=1)t.push({rid:oA[2-i],maxBitrate:c.maxBitrate/Math.pow(n,i),maxFramerate:p.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,i):void 0});t[0].scalabilityMode=d}else t.push({maxBitrate:c.maxBitrate,maxFramerate:p.encoding.maxFramerate,scalabilityMode:d});return p.encoding.priority&&(t[0].priority=p.encoding.priority,t[0].networkPriority=p.encoding.priority),rS.debug("using svc encoding",{encodings:t}),t}if(!l)return[c];let m=[];if((m=e?null!=(r=oj(null==n?void 0:n.screenShareSimulcastLayers))?r:oL(e,p):null!=(a=oj(null==n?void 0:n.videoSimulcastLayers))?a:oL(e,p)).length>0){let e=m[0];m.length>1&&([,o]=m);let n=Math.max(t,i);if(n>=960&&o)return oU(t,i,[e,o,p],h);if(n>=480)return oU(t,i,[e,p],h)}return oU(t,i,[p])}function oL(e,t){if(e)return[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(e=>{var i,n;return new aq(Math.floor(t.width/e.scaleResolutionDownBy),Math.floor(t.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!=(i=t.encoding.maxFramerate)?i:30)/(null!=(n=e.fps)?n:30))))),e.fps,t.encoding.priority)});let{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?oM:ox}function oU(e,t,i,n){let r=[];if(i.forEach((i,a)=>{if(a>=oA.length)return;let s=Math.min(e,t),o={rid:oA[a],scaleResolutionDownBy:Math.max(1,s/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(o.maxFramerate=c);let l=sr()||0===a;i.encoding.priority&&l&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),r.push(o)}),sd()&&"ios"===sm()){let e;r.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;r.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,rS.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),rS.info('Setting framerate of encoding "'.concat(null!=(n=i.rid)?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return r}function oj(e){if(e)return e.sort((e,t)=>{let{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class oF{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!=(e=this.suffix
2)?e:"")}}class oB extends oR{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,a9.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>rP(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(eg.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;let r=null==(n=this.prevStats)?void 0:n.get(i);e+=oC(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new eZ}get isSimulcast(){return!!this.sender&&!!(this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!sl())return;let i=null==(t=this.sender)?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return rP(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var t,i,n,r,a,s,o=!0,c=rI(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0)r=s.value,o=!1,yield null==(a=r.sender)?void 0:a.replaceTrack(null)}catch(e){i={error:e}}finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return rP(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var t,i,n,r,a,s,o=!0,c=rI(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0)r=s.value,o=!1,yield null==(a=r.sender)?void 0:a.replaceTrack(r.mediaStreamTrack)}catch(e){i={error:e}}finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return rP(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source!==a9.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return rP(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;return this.source!==a9.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){for(let t of(super.setTrackMuted(e),this.simulcastCodecs.values()))t.mediaStreamTrack.enabled=!e}getSenderStats(){return rP(this,void 0,void 0,function*(){var e;if(!(null==(e=this.sender)?void 0:e.getStats))return[];let t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){let r={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!=(n=e.rid)?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},a=i.get(e.remoteId);a&&(r.jitter=a.jitter,r.packetsLost=a.packetsLost,r.roundTripTime=a.roundTripTime),t.push(r)}}),t.sort((e,t)=>
2{var i,n;return(null!=(i=t.frameWidth)?i:0)-(null!=(n=e.frameWidth)?n:0)}),t})}setPublishingQuality(e){let t=[];for(let i=eb.LOW;i<=eb.HIGH;i+=1)t.push(new nU({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(si(this.codec),t)}restartTrack(e){return rP(this,void 0,void 0,function*(){let t;if(e){let i=aY({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield this.restart(t),this.isCpuConstrained=!1;try{for(var i,n,r,a,s,o,c=!0,l=rI(this.simulcastCodecs.values());!(i=(o=yield l.next()).done);c=!0)a=o.value,c=!1,a.sender&&(null==(s=a.sender.transport)?void 0:s.state)!=="closed"&&(a.mediaStreamTrack=this.mediaStreamTrack.clone(),yield a.sender.replaceTrack(a.mediaStreamTrack))}catch(e){n={error:e}}finally{try{!c&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return rP(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){if(yield t.setProcessor.call(i,e,n),null==(c=i.processor)?void 0:c.processedTrack)try{for(var r,a,s,o,c,l,d,u=!0,h=rI(i.simulcastCodecs.values());!(r=(d=yield h.next()).done);u=!0)o=d.value,u=!1,yield null==(l=o.sender)?void 0:l.replaceTrack(i.processor.processedTrack)}catch(e){a={error:e}}finally{try{!u&&!r&&(s=h.return)&&(yield s.call(h))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return rP(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);let i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){let i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return rP(this,void 0,void 0,function*(){var t,i,n,r,a,s,o;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(si(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,i=rI(e);!(r=(n=yield i.next()).done);t=!0)if(o=n.value,t=!1,this.codec&&this.codec!==o.codec){let e=this.simulcastCodecs.get(o.codec);if(this.log.debug("try setPublishingCodec for ".concat(o.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:e})),e&&e.sender)e.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(o.codec),this.logContext),yield oq(e.sender,e.encodings,o.qualities,this.senderLock,si(o.codec),this.log,this.logContext));else for(let e of o.qualities)if(e.enabled){c.push(o.codec);break}}else yield this.setPublishingLayers(si(o.codec),o.qualities)}catch(e){a={error:e}}finally{try{!t&&!r&&(s=i.return)&&(yield s.call(i))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return rP(this,void 0,void 0,function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield oq(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return rP(this,void 0,void 0,function*(){if(!this.sender)throw Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!=(i=this.mediaStreamTrack.getSettings().height)?i:360)/360)),scalabilityMode:0===t&&si(this.codec)?"L1T3":void 0,maxFramerate:15*(0===t),maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return rP(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),sc()&&this.isInBackgroun
2d&&this.source===a9.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function oq(e,t,i,n,r,a,s){return rP(this,void 0,void 0,function*(){let o=yield n.lock();a.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:e,qualities:i,senderEncodings:t}));try{let n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length)return void a.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:o,senderEncodings:t}));let c=!1;r&&i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0),o.forEach((e,n)=>{var r;let o=null!=(r=e.rid)?r:"";""===o&&(o="q");let l=oV(o),d=i.find(e=>e.quality===l);d&&e.active!==d.enabled&&(c=!0,e.active=d.enabled,a.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled"),s),sr()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(n.encodings=o,a.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}})}function oV(e){switch(e){case"f":default:return eb.HIGH;case"h":return eb.MEDIUM;case"q":return eb.LOW}}function oH(e,t,i,n){if(!i)return[new iP({quality:eb.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){let n=new oF(i[0].scalabilityMode),r=[],a="h"==n.suffix?1.5:2,s="h"==n.suffix?2:3;for(let o=0;o<n.spatial;o+=1)r.push(new iP({quality:Math.min(eb.HIGH,n.spatial-1)-o,width:Math.ceil(e/Math.pow(a,o)),height:Math.ceil(t/Math.pow(a,o)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(s,o)):0,ssrc:0}));return r}return i.map(i=>{var n,r,a;let s=null!=(n=i.scaleResolutionDownBy)?n:1;return new iP({quality:oV(null!=(r=i.rid)?r:""),width:Math.ceil(e/s),height:Math.ceil(t/s),bitrate:null!=(a=i.maxBitrate)?a:0,ssrc:0})})}let oW="_lossy",oG="_reliable",oz="_data_track",oK="leave-reconnect";(L=ex||(ex={}))[L.New=0]="New",L[L.Connected=1]="Connected",L[L.Disconnected=2]="Disconnected",L[L.Reconnecting=3]="Reconnecting",L[L.Closed=4]="Closed",(U=eA||(eA={}))[U.RELIABLE=0]="RELIABLE",U[U.LOSSY=1]="LOSSY",U[U.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY";class oJ extends r_.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ov.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=ex.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=rS,this.reliableDataSequence=1,this.reliableMessageBuffer=new s5,this.reliableReceivedState=new s7(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>rP(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){let e;if(i){if(i.label===oG)t.reliableDCSub=i,e=t.handleDataMessage;else if(i.label===oW)t.lossyDCSub=i,e=t.handleDataMessage;else{if(i.label!==oz)return;t.dataTrackDCSub=i,e=t.handleDataTrackMessage}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=e}}()}),this.handleDataMessage=e=>rP(this,void 0,void 0,function*(){var t,i,n,r,a;let s=yield this.dataProcessLock.lock();try{let s;if(e.data instanceof ArrayBuffer)s=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));s=yield e.data.arrayBuffer()}let o=iI.fromBinary(new Uint8Array(s));if(o.sequence>0&&""!==o.participantSid){let e=this.reliableReceivedState.get(o.participantSid);if(e&&o.sequence<=e)return;this.reliableReceivedState.set(o.participantSid,o.sequence)}if((null==(t=o.value)?void 0:t.case)==="speaker")this.emit(em.ActiveSpeakersUpdate,o.value.value.speakers);else if((null==(i=o.value)?void 0:i.case)==="encryptedPacket"){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);let e=yield null==(n=this.e2eeManager)?void 0:n.handleEncryptedData(o.value.value.encryptedValue,o.value.value.iv,o.participantIdentity,o.value.value.keyIndex),t=iO.fromBinary(e.payload),i=new iI({value:t.value,participantIdentity:o.participantIdentity,participantSid:o.participantSid});(null==(r=i.value)?void 0:r.case)==="user"&&oQ(i,i.value.value),this.emit
2(em.DataPacketReceived,i,o.value.value.encryptionType)}else(null==(a=o.value)?void 0:a.case)==="user"&&oQ(o,o.value.value),this.emit(em.DataPacketReceived,o,iT.NONE)}finally{s()}}),this.handleDataTrackMessage=e=>rP(this,void 0,void 0,function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));t=yield e.data.arrayBuffer()}this.emit("dataTrackPacketReceived",new Uint8Array(t))}),this.handleDataError=e=>{let t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){let{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());let i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(em.Disconnected),this.close()},n=Date.now()-this.reconnectStart,r=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null===r?i(n):(e===oK&&(r=0),this.log.debug("reconnecting in ".concat(r,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=aB.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),r))},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===ex.Connected&&e();let i=()=>{this.off(em.Disconnected,n),e()},n=()=>{this.off(em.Restarted,i),t()};this.once(em.Restarted,i),this.once(em.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{if(e===eA.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(em.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>rP(this,void 0,void 0,function*(){!this.url||(yield fetch(sR(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===eP.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===eP.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(il.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>rP(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(sR(this.url),{method:"HEAD"}),a7(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=rC(null!=(t=e.loggerName)?t:ea.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new s9(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new eZ,this.dataProcessLock=new eZ,this.dcBufferStatus=new Map([[eA.RELIABLE,!0],[eA.LOSSY,!0],[eA.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(em.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(em.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(em.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(em.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(em.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(em.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(em.StreamStateChanged,e),this.client.onRequestResponse=e=>
2this.emit(em.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(em.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(em.Joined,e)}get logContext(){var e,t,i,n,r,a;return{room:null==(t=null==(e=this.latestJoinResponse)?void 0:e.room)?void 0:t.name,roomID:null==(n=null==(i=this.latestJoinResponse)?void 0:i.room)?void 0:n.sid,participant:null==(a=null==(r=this.latestJoinResponse)?void 0:r.participant)?void 0:a.identity,participantID:this.participantSid}}join(e,t,i,n){return rP(this,arguments,void 0,function(e,t,i,n){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var s,o,c,l,d,u;r._isNewlyCreated=!1,r.url=e,r.token=t,r.signalOpts=i,r.maxJoinAttempts=i.maxRetries;try{let h;if(r.joinAttempts+=1,r.setupSignalClientCallbacks(),!a&&sj()){r.pcManager||(yield r.configure(),r.createDataChannels(),r.addMediaSections(3,3));let e=yield null==(s=r.pcManager)?void 0:s.publisher.createInitialOffer();e&&(h=s8(e.offer,e.offerId))}if(null==n?void 0:n.aborted)throw a_.cancelled("Connection aborted");let p=yield r.client.join(e,t,i,n,a,h);r._isClosed=!1,r.latestJoinResponse=p,r.participantSid=null==(o=p.participant)?void 0:o.sid,r.subscriberPrimary=p.subscriberPrimary,!a&&sj()?null==(c=r.pcManager)||c.updateConfiguration(r.makeRTCConfiguration(p)):(r.pcManager||(yield r.configure(p,!a)),(!r.subscriberPrimary||p.fastPublish)&&r.negotiate().catch(e=>{rS.error(e,r.logContext)})),r.registerOnLineListener(),r.clientConfiguration=p.clientConfiguration,r.emit(em.SignalConnected,p);let m=p.serverInfo;return m||(m={version:p.serverVersion,region:p.serverRegion}),r.log.debug("connected to Livekit Server ".concat(Object.entries(m).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null==(l=p.room)?void 0:l.name,roomSid:null==(d=p.room)?void 0:d.sid,identity:null==(u=p.participant)?void 0:u.identity}),{joinResponse:p,serverInfo:m}}catch(s){if(s instanceof a_){if(s.reason===el.ServerUnreachable){if(r.log.warn("Couldn't connect to server, attempt ".concat(r.joinAttempts," of ").concat(r.maxJoinAttempts),r.logContext),r.joinAttempts<r.maxJoinAttempts)return r.join(e,t,i,n,a)}else if(s.reason===el.ServiceNotFound)return r.log.warn("Initial connection failed: ".concat(s.message," – Retrying")),r.join(e,t,i,n,!0)}throw s}}()})}close(){return rP(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed)return void e();try{this._isClosed=!0,this.joinAttempts=0,this.emit(em.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return rP(this,void 0,void 0,function*(){var e;yield null==(e=this.pcManager)?void 0:e.close(),this.pcManager=void 0;let t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new s5,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return rP(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new aM("a track with the same ID has already been published");return new Promise((t,i)=>{let n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(a_.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null==(e=this.reliableDCSub)?void 0:e.readyState}getConnectedServerAddress(){return rP(this,void 0,void 0,function*(){var e;return null==(e=this.pcManager)?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return rP(this,void 0,void 0,function*(){var i;if(!this.pcManager||this.pcManager.currentState===eM.NEW){if(e){this.participantSid=null==(i=e.participant)?void 0:i.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new ob(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new ob("publisher-only",this.loggerOptions,e)}
2this.emit(em.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,t,i)=>rP(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(e),this.logContext),["closed","disconnected","failed"].includes(t)&&(this.publisherConnectionPromise=void 0),e===eM.CONNECTED){let e=this.pcState===ex.New;this.pcState=ex.Connected,e&&this.emit(em.Connected,this.latestJoinResponse)}else e===eM.FAILED&&(this.pcState===ex.Connected||this.pcState===ex.Reconnecting)&&(this.pcState=ex.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?il.RR_SUBSCRIBER_FAILED:il.RR_PUBLISHER_FAILED));let n=this.client.isDisconnected||this.client.currentState===eP.RECONNECTING,r=[eM.FAILED,eM.CLOSING,eM.CLOSED].includes(e);n&&r&&!this._isClosed&&this.emit(em.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(em.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>rP(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>rP(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;let n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null==(t=e.track)?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));let{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(em.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(em.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,null==(t=this.regionUrlProvider)||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(em.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(em.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null==(t=e.participant)?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(em.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(em.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(em.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(em.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",il.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:e.regions})),e.action){case nR.DISCONNECT:this.emit(em.Disconnected,null==e?void 0:e.reason),this.close();break;case nR.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(oK);break;case nR.RESUME:this.handleDisconnect(oK)}}}makeRTCConfiguration(e){var t;let i=Object.assign({},this.rtcConfig);if((null==(t=this.signalOpts)?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(e.iceServers&&!i.iceServers){let t=[];
2e.iceServers.forEach(e=>{let i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===io.ENABLED&&(i.iceTransportPolicy="relay"),i}addMediaSections(e,t){var i,n;let r={direction:"recvonly"};for(let t=0;t<e;t++)null==(i=this.pcManager)||i.addPublisherTransceiverOfKind("audio",r);for(let e=0;e<t;e++)null==(n=this.pcManager)||n.addPublisherTransceiverOfKind("video",r)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(oW,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(oG,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(oz,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(eA.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(eA.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(eA.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(eA.LOSSY);e&&(e.bufferedAmountLowThreshold=Math.min(Math.max(this.lossyDataStatByterate/10,8192),262144))},1e3))}createSender(e,t,i){return rP(this,void 0,void 0,function*(){if(se())return yield this.createTransceiverRTCRtpSender(e,t,i);if(st())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new aA("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return rP(this,void 0,void 0,function*(){if(se())return this.createSimulcastTransceiverSender(e,t,i,n);if(st())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new aA("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return rP(this,void 0,void 0,function*(){if(!this.pcManager)throw new aA("publisher is closed");let n=[];e.mediaStream&&n.push(e.mediaStream),sx(e)&&(e.codec=t.videoCodec);let r={direction:"sendonly",streams:n};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,n){return rP(this,void 0,void 0,function*(){if(!this.pcManager)throw new aA("publisher is closed");let r={direction:"sendonly"};n&&(r.sendEncodings=n);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return rP(this,void 0,void 0,function*(){if(!this.pcManager)throw new aA("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return rP(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed){if(this.attemptingReconnect)return void rS.warn("already attempting reconnect, returning early",this.logContext);((null==(t=this.clientConfiguration)?void 0:t.resumeConnection)===io.DISABLED||(null!=(n=null==(i=this.pcManager)?void 0:i.currentState)?n:eM.NEW)===eM.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let e=!0;
2t instanceof aA?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof aF||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",il.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(em.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return rP(this,void 0,void 0,function*(){var t,i,n;try{let i;if(!this.url||!this.token)throw new aA("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(em.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new aF;i=(yield this.join(null!=e?e:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(e){if(e instanceof a_&&e.reason===el.NotAllowed)throw new aA("could not reconnect, token might be expired");throw new aF}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(em.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==eP.CONNECTED)throw new aF("Signal connection got severed during reconnect");null==(t=this.regionUrlProvider)||t.resetAttempts(),this.emit(em.Restarted)}catch(t){let e=yield null==(i=this.regionUrlProvider)?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null==(n=this.regionUrlProvider)||n.resetAttempts(),t}})}resumeConnection(e){return rP(this,void 0,void 0,function*(){var t;let i;if(!this.url||!this.token)throw new aA("could not reconnect, url or token not saved");if(!this.pcManager)throw new aA("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(em.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(t){let e="";if(t instanceof Error&&(e=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof a_&&t.reason===el.NotAllowed)throw new aA("could not reconnect, token might be expired");if(t instanceof a_&&t.reason===el.LeaveRequest)throw t;throw new aF(e)}
2if(this.emit(em.SignalResumed),i){let e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==eP.CONNECTED)throw new aF("Signal connection got severed during reconnect");this.client.setReconnected(),(null==(t=this.reliableDC)?void 0:t.readyState)==="open"&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(em.Resumed)})}waitForPCInitialConnection(e,t){return rP(this,void 0,void 0,function*(){if(!this.pcManager)throw new aA("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return rP(this,void 0,void 0,function*(){this.pcState=ex.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield a7(2e3),!this.pcManager)throw new aA("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ex.Connected}catch(e){throw this.pcState=ex.Disconnected,a_.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,n){return rP(this,void 0,void 0,function*(){let r=new iI({destinationIdentities:[e],kind:iD.RELIABLE,value:{case:"rpcResponse",value:new iq({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(r,eA.RELIABLE)})}publishRpcAck(e,t){return rP(this,void 0,void 0,function*(){let i=new iI({destinationIdentities:[e],kind:iD.RELIABLE,value:{case:"rpcAck",value:new iB({requestId:t})}});yield this.sendDataPacket(i,eA.RELIABLE)})}sendDataPacket(e,t){return rP(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=function(e){var t,i,n,r,a;if((null==(t=e.value)?void 0:t.case)!=="sipDtmf"&&(null==(i=e.value)?void 0:i.case)!=="metrics"&&(null==(n=e.value)?void 0:n.case)!=="speaker"&&(null==(r=e.value)?void 0:r.case)!=="transcription"&&(null==(a=e.value)?void 0:a.case)!=="encryptedPacket")return new iO({value:e.value})}(e);if(t){let i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new i_({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===eA.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let i=e.toBinary();switch(t){case eA.LOSSY:case eA.DATA_TRACK_LOSSY:return this.sendLossyBytes(i,t);case eA.RELIABLE:let n=this.dataChannelForKind(t);if(n){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)}})}sendLossyBytes(e,t){return rP(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"drop";return function*(){yield i.ensurePublisherConnected(t);let r=i.dataChannelForKind(t);if(r){if(!i.isBufferStatusLow(t))switch(n){case"wait":yield i.waitForBufferStatusLow(t);break;case"drop":i.lossyDataDropCount+=1,i.lossyDataDropCount%100==0&&i.log.warn("dropping lossy data channel messages, total dropped: ".concat(i.lossyDataDropCount),i.logContext);return}if(i.lossyDataStatCurrentBytes+=e.byteLength,i.attemptingReconnect)return;r.send(e)}i.updateAndEmitDCBufferStatus(t)}()})}resendReliableMessagesForResume(e){return rP(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(eA.RELIABLE);let t=this.dataChannelForKind(eA.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(eA.RELIABLE)})}waitForBufferStatusLow(e){return rP(this,void 0,void 0,function*(){return new aS((t,i)=>rP(this,void 0,void 0,function*(){if(this.isClosed&&i(new aA("engine closed")),this.isBufferStatusLow(e))t();else{let n=()=>i(new aA("engine closed"));this.once(em.Closing,n);let r=this.dataChannelForKind(e);if(!r)return void i(new aA("DataChannel not found, kind: ".concat(e)));r.addEventListener("bufferedamountlow",()=>{this.off(em.Closing,n),t()},{once:!0})}}))})}ensureDataTransportConnected(e){return rP(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new aA("PC manager is closed");let r=i?t.pcManager.subscriber:t.pcManager.publisher,a=i?"Subscriber":"Publisher";if(!r)throw a_.internal("".concat(a," connection not set"));let s=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),s=!0),s||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(s=!0),s&&t.negotiate().catch(e=>{rS.error(e,t.logContext)});let o=t.dataChannelForKind(e,i);if((null==o?void 0:o.readyState)==="open")return;let c=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<c;){if(r.isICEConnected&&(null==(n=t.dataChannelForKind(e,i))?void 0:n.readyState)==="open")return;yield a7(50)}throw a_.internal("could not establish ".concat(a," connection, state: ").concat(r.getICEConnectionState()))}()})}ensurePublisherConnected(e){return rP(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&!![eM.CONNECTING,eM.CONNECTED].includes(this.pcManager.currentState)&&!!this.client.ws&&this.client.ws.readyState!==WebSocket.CLOSED}negotiate(){return rP(this,void 0,void 0,function*(){return new aS((e,t)=>rP(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new aN("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.dataTrackDC||this.createDataChannels();let i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new aN("cannot negotiate on closed engine")),this.on(em.Closing,n),this.on(em.Restarting,n),this.pcManager.publisher.once(oc,e=>{let t=new Map;
2e.forEach(e=>{let i=e.codec.toLowerCase();aH.includes(i)&&t.set(e.payload,i)}),this.emit(em.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(n){if(i.signal.aborted)return void e();n instanceof aN&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",il.RR_UNKNOWN),n instanceof Error?t(n):t(Error(String(n)))}finally{this.off(em.Closing,n),this.off(em.Restarting,n)}}))})}dataChannelForKind(e,t){switch(e){case eA.RELIABLE:if(!t)return this.reliableDC;return this.reliableDCSub;case eA.LOSSY:if(!t)return this.lossyDC;return this.lossyDCSub;case eA.DATA_TRACK_LOSSY:if(!t)return this.dataTrackDC;return this.dataTrackDCSub}}sendSyncState(e,t,i){var n,r,a,s;let o;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);let c=this.pcManager.publisher.getLocalDescription(),l=this.pcManager.publisher.getRemoteDescription(),d=null==(n=this.pcManager.subscriber)?void 0:n.getRemoteDescription(),u=null==(r=this.pcManager.subscriber)?void 0:r.getLocalDescription(),h=null==(s=null==(a=this.signalOpts)?void 0:a.autoSubscribe)||s,p=[],m=[];e.forEach(e=>{e.isDesired!==h&&p.push(e.trackSid),e.isEnabled||m.push(e.trackSid)}),this.client.sendSyncState(new nG({answer:"publisher-only"===this.pcManager.mode?l?s8({sdp:l.sdp,type:l.type}):void 0:u?s8({sdp:u.sdp,type:u.type}):void 0,offer:"publisher-only"===this.pcManager.mode?c?s8({sdp:c.sdp,type:c.type}):void 0:d?s8({sdp:d.sdp,type:d.type}):void 0,subscription:new ny({trackSids:p,subscribe:!h,participantTracks:[]}),publishTracks:(o=[],t.forEach(e=>{void 0!==e.track&&o.push(new nf({cid:e.track.mediaStreamID,track:e.trackInfo}))}),o),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:m,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new nz({publisherSid:t,lastSeq:e})),publishDataTracks:i.map(e=>{let t;return new no({info:new iE({sid:(t=e).sid,pubHandle:t.pubHandle,name:t.name,encryption:t.usesE2ee?iT.GCM:iT.NONE})})})}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,i)=>{(null==t?void 0:t.id)!==void 0&&null!==t.id&&e.push(new nK({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(eA.LOSSY),i7.PUBLISHER),t(this.dataChannelForKind(eA.RELIABLE),i7.PUBLISHER),t(this.dataChannelForKind(eA.LOSSY,!0),i7.SUBSCRIBER),t(this.dataChannelForKind(eA.RELIABLE,!0),i7.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&aB.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){sl()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){sl()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;let i=null==(t=this.pcManager)?void 0:t.getMidForReceiver(e);if(i){let e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===i});if(e)return e[1]}}}function oQ(e,t){let i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;let n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}class oY{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new aj("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ed.Incomplete);else if(this.bytesReceived>this.totalByteSize)throw new aj("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ed.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class oX extends oY{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null==(t=this.onProgress)||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>rP(this,void 0,void 0,function*(){try{let t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;let i=yield new Promise((i,n)=>{if(t){let r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),e.read().then(i,n).finally(()=>{t.removeEventListener("abort",r)})}else e.read().then(i,n)});if(i.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};return this.handleChunkReceived(i.value),{done:!1,value:i.value.content}}catch(e){throw t(),e}}),return(){return rP(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return rP(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,a;let s=new Set,o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=rI(o);!(i=(c=yield d.next()).done);l=!0)a=c.value,l=!1,s.add(a)}catch(e){n={error:e}}finally{try{!l&&!i&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}return Array.from(s)}()})}}
2class oZ extends oY{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;let i=sD(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null==(t=this.onProgress)||t.call(this,r)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder("utf-8",{fatal:!0}),i=this.signal,n=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>rP(this,void 0,void 0,function*(){try{if(null==i?void 0:i.aborted)throw i.reason;let n=yield new Promise((t,n)=>{if(i){let r=()=>n(i.reason);i.addEventListener("abort",r,{once:!0}),e.read().then(t,n).finally(()=>{i.removeEventListener("abort",r)})}else e.read().then(t,n)});if(n.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(n.value);try{e=t.decode(n.value.content)}catch(e){throw new aj("Cannot decode datastream chunk ".concat(n.value.chunkIndex," as text: ").concat(e),ed.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw n(),e}}),return(){return rP(this,void 0,void 0,function*(){return n(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return rP(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,a;let s="",o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=rI(o);!(i=(c=yield d.next()).done);l=!0)a=c.value,l=!1,s+=a}catch(e){n={error:e}}finally{try{!l&&!i&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}return s}()})}}class o${constructor(){this.log=rS,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;for(let{packet:t,encryptionType:i}of(this.bufferedPackets=[],e))this.handleDataStreamPacket(t,i)}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new aj('A text stream handler for topic "'.concat(e,'" has already been set.'),ed.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new aj('A byte stream handler for topic "'.concat(e,'" has already been set.'),ed.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){let n=new aj("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ed.AbnormalEnd);for(let[e,t]of i)t.controller.error(n),this.byteStreamControllers.delete(e);for(let[e,i]of t)i.controller.error(n),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){if(!this.isConnected)return void this.bufferedPackets.push({packet:e,encryptionType:t});switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}handleStreamHeader(e,t,i){var n;if("byteHeader"===e.contentHeader.case){let r,a=this.byteStreamHandlers.get(e.topic);if(!a)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s={id:e.streamId,name:null!=(n=e.contentHeader.value.name)?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:sD(e.timestamp),attributes:e.attributes,encryptionType:i},o=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(e.streamId))throw new aj("A data stream read is already in progress for a stream with i
2d ".concat(e.streamId,"."),ed.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now(),sendingParticipantIdentity:t})}});a(new oX(s,o,sD(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){let n,r=this.textStreamHandlers.get(e.topic);if(!r)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},s=new ReadableStream({start:i=>{if(n=i,this.textStreamControllers.has(e.streamId))throw new aj("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ed.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:n,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new oZ(a,s,sD(e.totalLength)),{identity:t})}}handleStreamChunk(e,t){let i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new aj("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ed.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new aj("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ed.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){let i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new aj("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ed.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new aj("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ed.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class o0{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return rP(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null==(e=this.onClose)||e.call(this)})}}class o1 extends o0{}class o2 extends o0{}class o3{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return rP(this,void 0,void 0,function*(){var i;let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,a=null==(i=null==t?void 0:t.attachments)?void 0:i.map(()=>crypto.randomUUID()),s=Array(a?a.length+1:1).fill(0),o=(e,i)=>{var n;s[i]=e;let r=s.reduce((e,t)=>e+t,0);null==(n=null==t?void 0:t.onProgress)||n.call(t,r)},c=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:a,attributes:null==t?void 0:t.attributes});return yield c.write(e),o(1,0),yield c.close(),(null==t?void 0:t.attachments)&&a&&(yield Promise.all(t.attachments.map((e,i)=>rP(this,void 0,void 0,function*(){return this._sendFile(a[i],e,{topic:t.to
2pic,mimeType:e.type,onProgress:e=>{o(e,i+1)}})})))),c.info})}streamText(e){return rP(this,void 0,void 0,function*(){var t,i,n;let r=null!=(t=null==e?void 0:e.streamId)?t:crypto.randomUUID(),a={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:null!=(i=null==e?void 0:e.topic)?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null==(n=this.engine.e2eeManager)?void 0:n.isDataChannelEncryptionEnabled)?iT.GCM:iT.NONE,attachedStreamIds:null==e?void 0:e.attachedStreamIds},s=new i1({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:s_(a.timestamp),totalLength:s_(a.size),attributes:a.attributes,contentHeader:{case:"textHeader",value:new i$({version:null==e?void 0:e.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:(null==e?void 0:e.type)==="update"?iZ.UPDATE:iZ.CREATE})}}),o=null==e?void 0:e.destinationIdentities,c=new iI({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(c,eA.RELIABLE);let l=0,d=this.engine,u=new WritableStream({write(e){return rP(this,void 0,void 0,function*(){for(let t of function(e){let t=[],i=new TextEncoder().encode(e);for(;i.length>15e3;){let e=15e3;for(;e>0;){let t=i[e];if(void 0!==t&&(192&t)!=128)break;e--}t.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&t.push(i),t}(e)){let e=new iI({destinationIdentities:o,value:{case:"streamChunk",value:new i2({content:t,streamId:r,chunkIndex:s_(l)})}});yield d.sendDataPacket(e,eA.RELIABLE),l+=1}})},close(){return rP(this,void 0,void 0,function*(){let e=new iI({destinationIdentities:o,value:{case:"streamTrailer",value:new i3({streamId:r})}});yield d.sendDataPacket(e,eA.RELIABLE)})},abort(e){console.log("Sink error:",e)}}),h=()=>rP(this,void 0,void 0,function*(){yield p.close()});d.once(em.Closing,h);let p=new o1(u,a,()=>this.engine.off(em.Closing,h));return p})}sendFile(e,t){return rP(this,void 0,void 0,function*(){let i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return rP(this,void 0,void 0,function*(){var n;let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!=(n=null==i?void 0:i.mimeType)?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){let{done:e,value:t}=yield a.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return rP(this,void 0,void 0,function*(){var t,i,n,r,a;let s=null!=(t=null==e?void 0:e.streamId)?t:crypto.randomUUID(),o=null==e?void 0:e.destinationIdentities,c={id:s,mimeType:null!=(i=null==e?void 0:e.mimeType)?i:"application/octet-stream",topic:null!=(n=null==e?void 0:e.topic)?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!=(r=null==e?void 0:e.name)?r:"unknown",encryptionType:(null==(a=this.engine.e2eeManager)?void 0:a.isDataChannelEncryptionEnabled)?iT.GCM:iT.NONE},l=new iI({destinationIdentities:o,value:{case:"streamHeader",value:new i1({totalLength:s_(c.size),mimeType:c.mimeType,streamId:s,topic:c.topic,timestamp:s_(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new i0({name:c.name})}})}});yield this.engine.sendDataPacket(l,eA.RELIABLE);let d=0,u=new eZ,h=this.engine,p=this.log;return new o2(new WritableStream({write(e){return rP(this,void 0,void 0,function*(){let t=yield u.lock(),i=0;try{for(;i<e.byteLength;){let t=e.slice(i,i+15e3),n=new iI({destinationIdentities:o,value:{case:"streamChunk",value:new i2({content:t,streamId:s,chunkIndex:s_(d)})}});yield h.sendDataPacket(n,eA.RELIABLE),d+=1,i+=t.byteLength}}finally{t()}})},close(){return rP(this,void 0,void 0,function*(){let e=new iI({destinationIdentities:o,value:{case:"streamTrailer",value:new i3({streamId:s})}});yield h.sendDataPacket(e,eA.RELIABLE)})},abort(e){p.error("Sink error:",e)}}),c)})}}function o4(e){if(0===e.length)return new AbortController().signal;if(1===e.length)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,i=Array(e.length);return e.forEach((e,n)=>{let r=()=>{for(let n of(t.abort(e.reason),i))n()};e.addEventListener("abort",r),i[n]=()=>e.removeEventListener("abort",r)}),t.signal}function o9(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))},e),t.signal}
2(j=eN||(eN={}))[j.TooShort=0]="TooShort",j[j.HeaderOverrun=1]="HeaderOverrun",j[j.MissingExtWords=2]="MissingExtWords",j[j.UnsupportedVersion=3]="UnsupportedVersion",j[j.InvalidHandle=4]="InvalidHandle",j[j.MalformedExt=5]="MalformedExt";class o6 extends aD{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=eN[t]}static tooShort(){return new o6("Too short to contain a valid header",eN.TooShort)}static headerOverrun(){return new o6("Header exceeds total packet length",eN.HeaderOverrun)}static missingExtWords(){return new o6("Extension word indicator is missing",eN.MissingExtWords)}static unsupportedVersion(e){return new o6("Unsupported version ".concat(e),eN.UnsupportedVersion)}static invalidHandle(e){return new o6("invalid track handle: ".concat(e.message),eN.InvalidHandle,{cause:e})}static malformedExt(e){return new o6("Extension with tag ".concat(e," is malformed"),eN.MalformedExt)}}(F=eL||(eL={}))[F.TooSmallForHeader=0]="TooSmallForHeader",F[F.TooSmallForPayload=1]="TooSmallForPayload";class o8 extends aD{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=eL[t]}static tooSmallForHeader(){return new o8("Buffer cannot fit header",eL.TooSmallForHeader)}static tooSmallForPayload(){return new o8("Buffer cannot fit payload",eL.TooSmallForPayload)}}class o5{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),n=this.toBinaryInto(i);if(e!==n)throw Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(n," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}(B=eU||(eU={}))[B.UserTimestamp=2]="UserTimestamp",B[B.E2ee=1]="E2ee";class o7 extends o5{}class ce extends o7{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+ce.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,ce.tag),t+=1,e.setUint8(t,ce.lengthBytes),t+=1,e.setBigUint64(t,this.timestamp),t+=8;let i=this.toBinaryLengthBytes();if(t!==i)throw Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:ce.tag,lengthBytes:ce.lengthBytes,timestamp:this.timestamp}}}ce.tag=eU.UserTimestamp,ce.lengthBytes=8;class ct extends o7{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+ct.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,ct.tag),t+=1,e.setUint8(t,ct.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let i=0;i<this.iv.length;i+=1)e.setUint8(t,this.iv[i]),t+=1;let i=this.toBinaryLengthBytes();if(t!==i)throw Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:ct.tag,lengthBytes:ct.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}ct.tag=eU.E2ee,ct.lengthBytes=13;class ci extends o5{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee&&(t+=this.e2ee.toBinaryInto(e)),this.userTimestamp){let i=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=i}let i=this.toBinaryLengthBytes();if(t!==i)throw Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){let t,i,n=sX(e),r=0;for(;n.byteLength-r>=2;){let e=n.getUint8(r);r+=1;let a=n.getUint8(r);if(r+=1,0!==e)switch(e){case eU.UserTimestamp:if(n.byteLength-r<ce.lengthBytes)throw o6.malformedExt(e);t=new ce(n.getBigUint64(r)),r+=a;break;case eU.E2ee:if(n.byteLength-r<ct.lengthBytes)throw o6.malformedExt(e);let s=n.getUint8(r),o=new Uint8Array(12);for(let e=0;e<o.length;e+=1){let t=r;t+=1,t+=+e,o[e]=n.getUint8(t)}i=new ct(s,o),r+=a;break;default:if(n.byteLength-r<a)throw o6.malformedExt(e);r+=a}}return[new ci({userTimestamp:t,e2ee:i}),n.byteLength]}toJSON(){var e,t,i,n;return{userTimestamp:null!=(t=null==(e=this.userTimestamp)?void 0:e.toJSON())?t:null,e2ee:null!=(n=null==(i=this.e2ee)?void 0:i.toJSON())?n:null}}}let cn={from:e=>({payload:e.payload,extensions:new ci({userTimestamp:e.userTimestamp?new ce(e.userTimestamp):void 0})}),lossyIntoFrame(e){var t;return{payload:e.payload,userTimestamp:null==(t=e.extensions.userTimestamp)?void 0:t.t
2imestamp}}},cr=Symbol.for("lk.track"),ca=Symbol.for("lk.data-track");class cs{constructor(e,t,i){this.trackSymbol=cr,this.isLocal=!1,this.typeSymbol=ca,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{let[t]=this.manager.openSubscriptionStream(this.info.sid,null==e?void 0:e.signal,null==e?void 0:e.bufferSize);return t}catch(e){throw e}}}class co extends o5{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=null!=(t=e.extensions)?t:new ci}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil(e/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-e}}toBinaryLengthBytes(){let{lengthBytes:e,paddingLengthBytes:t}=this.extensionsMetrics(),i=12;return e>0&&(i+=2+e+t),i}toBinaryInto(e){let t;if(e.byteLength<this.toBinaryLengthBytes())throw o8.tooSmallForHeader();let i=0;switch(this.marker){case ej.Inter:t=0;break;case ej.Final:t=1;break;case ej.Start:t=2;break;case ej.Single:t=3}i|=t<<3;let{lengthBytes:n,lengthWords:r,paddingLengthBytes:a}=this.extensionsMetrics();n>0&&(i|=4);let s=0;if(e.setUint8(s,i),s+=1,e.setUint8(s,0),s+=1,e.setUint16(s,this.trackHandle),s+=2,e.setUint16(s,this.sequence.value),s+=2,e.setUint16(s,this.frameNumber.value),s+=2,e.setUint32(s,this.timestamp.asTicks()),s+=4,n>0){e.setUint16(s,r-1),s+=2;let t=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+s));s+=t;for(let t=0;t<a;t+=1)e.setUint8(s,0),s+=1}let o=this.toBinaryLengthBytes();if(s!==o)throw Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(s," bytes but expected length was ").concat(o," bytes"));return o}static fromBinary(e){let t,i,n=sX(e);if(n.byteLength<12)throw o6.tooShort();let r=0,a=n.getUint8(r);r+=1;let s=a>>5&7;if(s>0)throw o6.unsupportedVersion(s);switch(a>>3&3){case 2:t=ej.Start;break;case 1:t=ej.Final;break;case 3:t=ej.Single;break;default:t=ej.Inter}r+=1;try{i=s$.fromNumber(n.getUint16(r))}catch(e){if(e instanceof sZ&&(e.isReason(eE.Reserved)||e.isReason(eE.TooLarge)))throw o6.invalidHandle(e);throw e}r+=2;let o=sJ.u16(n.getUint16(r));r+=2;let c=sJ.u16(n.getUint16(r));r+=2;let l=sQ.fromRtpTicks(n.getUint32(r));r+=4;let d=new ci;if((a>>2&1)>0){if(n.byteLength-r<2)throw o6.missingExtWords();let e=n.getUint16(r),t=4*(e+1);if((r+=2)+t>n.byteLength)throw o6.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),[a,s]=ci.fromBinary(i);d=a,r+=s}return[new co({marker:t,trackHandle:i,sequence:o,frameNumber:c,timestamp:l,extensions:d}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}(q=ej||(ej={}))[q.Start=0]="Start",q[q.Inter=1]="Inter",q[q.Final=2]="Final",q[q.Single=3]="Single";class cc extends o5{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t;if(t=0+this.header.toBinaryInto(e),e.byteLength-t<this.payload.byteLength)throw o8.tooSmallForPayload();for(let i=0;i<this.payload.length;i+=1)e.setUint8(t,this.payload[i]),t+=1;let i=this.toBinaryLengthBytes();if(t!==i)throw Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return i}static fromBinary(e){let t=sX(e),[i,n]=co.fromBinary(t);return[new cc(i,new Uint8Array(t.buffer.slice(t.byteOffset+n,t.byteOffset+t.byteLength))),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}let cl=rC(ea.DataTracks);class cd extends aD{constructor(e,t,i,n){super(19,"Frame ".concat(i," dropped: ").concat(e),n),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=eF[t],this.frameNumber=i}static interrupted(e,t){return new cd("Interrupted by the start of a new frame ".concat(t),eF.Interrupted,e)}static unknownFrame(e){return new cd("Initial packet was never received.",eF.UnknownFrame,e)}static bufferFull(e){return new cd("Reorder buffer is full.",eF.BufferFull,e)}static incomplete(e,t,i){return new cd("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),eF.Incomplete,e)}}(V=eF||(eF={}))[V.Interrupted=0]="Interrupted",V[V.UnknownFrame=1]="UnknownFrame",V[V.BufferFull=2]="BufferFull",V[V.Incomplete=3]="Incomplete";class cu{constructor(){this.partial=null}push(e,t){switch(e.header.marker){case ej.Single:return this.frameFromSingle(e,t);case ej.Start:return this.beginPartial(e,t);case ej.Inter:case ej.Final:return this.pushToPartial(e)}}reset(){this.partial=null}frameFromSingle(e,t){if(e.header.marker!==ej.Single)throw Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));if(this.partial)if(null==t?void 0:t.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),cd.interrupted(t,e.header.frameNumber.value)}else cl.warn("Data track frame ".concat(this.partial.frameNumber," was interrupted by the start of a new frame, dropping."));return this.reset(),{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==ej.Start)throw Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));if(this.partial)if(null==t?void 0:t.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),cd.interrupted(t,e.header.frameNumber.value)}else cl.warn("Data track frame ".concat(this.partial.frameNumber," was interrupted by the start of a new frame ").concat(e.header.frameNumber.value,", dropping."));this.reset();let i=e.header.sequence;return this.partial={frameNumber:e.header.frameNumber.value,startSequence:i,extensions:e.header.extensions,payloads:new Map([[i.value,e.payload]])},null}pushToPartial(e){if(e.header.marker!==ej.Inter&&e.header.marker!==ej.Final)throw Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));if(!this.partial)throw this.reset(),cd.unknownFrame(e.header.frameNumber.value);if(e.header.frameNumber.value!==this.partial.frameNumber){let t=this.partial.frameNumber;throw this.reset(),cd.interrupted(t,e.header.frameNumber.value)}if(this.partial.payloads.size>=cu.MAX_BUFFER_PACKETS){let e=this.partial.frameNumber;throw this.reset(),cd.bufferFull(e)}return(this.partial.payloads.has(e.header.sequence.value)&&cl.warn("Data track frame ".concat(this.partial.frameNumber," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),this.partial.payloads.set(e.header.sequence.value,e.payload),e.header.marker===ej.Final)?this.finalize(this.partial,e.header.sequence.value):null}finalize(e,t){let i=e.payloads.size,n=0;for(let t of e.payloads.values())n+=t.length;let r=new Uint8Array(n),a=e.startSequence.clone(),s=0;for(;;){let i=e.payloads.get(a.value);if(!i)break;e.payloads.delete(a.value);let n=r.length-s;if(i.length>n)throw Error("Depacketizer.finalize: Expected at least ".concat(i.length," more bytes left in the payload buffer, only got ").concat(n," bytes."));if(r.set(i,s),s+=i.length,a.value!=t){a.increment();continue}return this.reset(),{payload:r,extensions:e.extensions}}throw this.reset(),cd.incomplete(e.frameNumber,i,t-e.startSequence.value+1)}}cu.MAX_BUFFER_PACKETS=128,(H=eB||(eB={}))[H.Unpublished=0]="Unpublished",H[H.Timeout=1]="Timeout",H[H.Disconnected=2]="Disconnected",H[H.Cancelled=4]="Cancelled";class ch extends aD{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=eB[t]}static unpublished(){return new ch("The track has been unpublished and is no longer available",eB.Unpublished)}static timeout(){return new ch("Request to subscribe to data track t
2imed-out",eB.Timeout)}static disconnected(){return new ch("Cannot subscribe to data track when disconnected",eB.Disconnected)}static cancelled(){return new ch("Subscription to data track cancelled by caller",eB.Cancelled)}}let cp=rC(ea.DataTracks);class cm{constructor(e){var t;const i=null!==e.e2eeManager;if(e.info.usesE2ee!==i)throw Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const n=new cu;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=null!=(t=e.e2eeManager)?t:null,this.depacketizer=n}updateE2eeManager(e){this.e2eeManager=e}processPacket(e){return rP(this,void 0,void 0,function*(){let t=this.depacketize(e);if(!t)return null;let i=yield this.decryptIfNeeded(t);return i||null})}depacketize(e){let t;try{t=this.depacketizer.push(e)}catch(e){return cp.warn("Data frame depacketize error: ".concat(e)),null}return t}decryptIfNeeded(e){return rP(this,void 0,void 0,function*(){var t,i;let n,r=this.e2eeManager;if(!r)return e;let a=null!=(i=null==(t=e.extensions)?void 0:t.e2ee)?i:null;if(!a)return cp.error("Missing E2EE meta"),null;try{n=yield r.handleEncryptedData(e.payload,a.iv,this.publisherIdentity,a.keyIndex)}catch(e){return cp.error("Error decrypting packet: ".concat(e)),null}return e.payload=n.payload,e})}}let cg=rC(ea.DataTracks);class cf extends r_.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=null!=(t=null==e?void 0:e.e2eeManager)?t:null}updateE2eeManager(e){for(let t of(this.e2eeManager=e,this.descriptors.values()))"active"===t.subscription.type&&t.subscription.pipeline.updateE2eeManager(e)}openSubscriptionStream(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16,n=null,r=new sw;return[new ReadableStream({start:i=>{n=i;let a=()=>{var e;i.error(ch.cancelled()),null==(e=r.reject)||e.call(r,ch.cancelled())};this.subscribeRequest(e,t).then(()=>rP(this,void 0,void 0,function*(){var n;null==t||t.addEventListener("abort",a);let s=this.descriptors.get(e);s?"active"!==s.subscription.type?cg.error("Subscription for track ".concat(e," is not active")):(s.subscription.streamControllers.add(i),null==(n=r.resolve)||n.call(r)):cg.error("Unknown track ".concat(e))})).catch(e=>{var t;i.error(e),null==(t=r.reject)||t.call(r,e)}).finally(()=>{null==t||t.removeEventListener("abort",a)})},cancel:()=>{if(!n)return void cg.warn("ReadableStream subscribed to ".concat(e," was not started."));let t=this.descriptors.get(e);t?"active"!==t.subscription.type?cg.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):(t.subscription.streamControllers.delete(n),0===t.subscription.streamControllers.size&&this.unSubscribeRequest(t.info.sid)):cg.warn("Unknown track ".concat(e,", skipping cancel..."))}},new CountQueuingStrategy({highWaterMark:i})),r.promise]}subscribeRequest(e,t){return rP(this,void 0,void 0,function*(){let i=this.descriptors.get(e);if(!i)throw Error("Cannot subscribe to unknown track");let n=(t,i,n)=>rP(this,void 0,void 0,function*(){if("active"===t.subscription.type)return;if("pending"!==t.subscription.type)throw Error("Descriptor for track ".concat(e," is not pending, found ").concat(t.subscription.type));let r=o4([i,n].filter(e=>void 0!==e)),a=new sw;t.subscription.completionFuture.promise.then(()=>{var e;return null==(e=a.resolve)?void 0:e.call(a)}).catch(e=>{var t;return null==(t=a.reject)?void 0:t.call(a,e)});let s=()=>{var e;if("pending"===t.subscription.type){if(t.subscription.pendingRequestCount-=1,(null==n?void 0:n.aborted)||t.subscription.pendingRequestCount<=0)return void t.subscription.cancel();null==(e=a.reject)||e.call(a,ch.cancelled())}};r.aborted&&s(),r.addEventListener("abort",s),yield a.promise,r.removeEventListener("abort",s)});switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new sw,pendingRequestCount:1,cancel:()=>{var t,n;let a=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),"pending"===a.type&&(null==(n=(t=a.completionFuture).reject)||n.call(t,r.aborted?ch.timeout():ch.cancelled()))}}
2,this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});let r=o9(1e4);yield n(i,t,r);return}case"pending":i.subscription.pendingRequestCount+=1,yield n(i,t);return;case"active":return}})}querySubscribed(){return rP(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>"active"===e.subscription.type).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){var t;let i=this.descriptors.get(e);if(!i)throw Error("Cannot subscribe to unknown track");if("active"!==i.subscription.type)return void cg.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat(null==(t=i.subscription)?void 0:t.type));for(let e of i.subscription.streamControllers)e.close();let n=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}receiveSfuPublicationUpdates(e){return rP(this,void 0,void 0,function*(){if(0===e.size)return;let t=new Map;for(let[i,n]of e.entries()){let e=new Set;for(let t of n)e.add(t.sid),this.descriptors.has(t.sid)||(yield this.handleTrackPublished(i,t));t.set(i,e)}for(let[e,i]of t.entries())for(let t of Array.from(this.descriptors.entries()).filter(t=>{let[i,n]=t;return n.publisherIdentity===e}).map(e=>{let[t]=e;return t}).filter(e=>!i.has(e)))this.handleTrackUnpublished(t)})}queryPublications(){return rP(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return rP(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid))return void cg.error("Existing descriptor for track ".concat(t.sid));let i={info:t,publisherIdentity:e,subscription:{type:"none"}};this.descriptors.set(i.info.sid,i);let n=new cs(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:n})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);t?(this.descriptors.delete(e),"active"===t.subscription.type&&(t.subscription.streamControllers.forEach(e=>{e.close()}),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})):cg.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(let[t,i]of e.entries())this.registerSubscriberHandle(t,i)}registerSubscriberHandle(e,t){var i,n;let r=this.descriptors.get(t);if(!r)return void cg.error("Unknown track ".concat(t));switch(r.subscription.type){case"none":return void cg.warn("No subscription for ".concat(t));case"active":r.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case"pending":{let a=new cm({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager}),s=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Set},this.subscriptionHandles.set(e,t),null==(n=(i=s.completionFuture).resolve)||n.call(i)}}}packetReceived(e){return rP(this,void 0,void 0,function*(){let t;try{[t]=cc.fromBinary(e)}catch(e){cg.error("Failed to deserialize packet: ".concat(e));return}let i=this.subscriptionHandles.get(t.header.trackHandle);if(!i)return void cg.warn("Unknown subscriber handle ".concat(t.header.trackHandle));let n=this.descriptors.get(i);if(!n)return void cg.error("Missing descriptor for track ".concat(i));if("active"!==n.subscription.type)return void cg.warn("Received packet for track ".concat(i," without active subscription"));let r=yield n.subscription.pipeline.processPacket(t);if(r)for(let e of n.subscription.streamControllers){if(null!==e.desiredSize&&e.desiredSize<=0){cg.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(e.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}let t=cn.lossyIntoFrame(r);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let[e,t]of this.descriptors)"none"!==t.subscription.type&&this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0})}handleRemoteParticipantDisconnected(e){var t,i;for(let n of this.descriptors.values())if(n.publisherIdentity===e)switch(n.subscription.type){case"none":break;
2case"pending":null==(i=(t=n.subscription.completionFuture).reject)||i.call(t,ch.disconnected());break;case"active":this.unSubscribeRequest(n.info.sid)}}shutdown(){var e,t;for(let i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),"pending"===i.subscription.type&&(null==(t=(e=i.subscription.completionFuture).reject)||t.call(e,ch.disconnected())),"active"===i.subscription.type&&i.subscription.streamControllers.forEach(e=>e.close());this.descriptors.clear()}}class cv extends aD{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=eq[t]}static mtuTooShort(){return new cv("MTU is too short to send frame",eq.MtuTooShort)}}(W=eq||(eq={}))[W.MtuTooShort=0]="MtuTooShort";class cb{constructor(e,t){this.sequence=sJ.u16(0),this.frameNumber=sJ.u16(0),this.clock=sY.rtpStartingNow(sQ.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?ej.Single:0===e?ej.Start:e===t-1?ej.Final:ej.Inter}*packetize(e,t){var i;let n=this.frameNumber.getThenIncrement(),r={marker:ej.Inter,trackHandle:this.handle,sequence:sJ.u16(0),frameNumber:n,timestamp:null!=(i=null==t?void 0:t.now)?i:this.clock.now(),extensions:e.extensions},a=new co(r).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw cv.mtuTooShort();let s=this.mtuSizeBytes-a,o=Math.ceil(e.payload.byteLength/s);for(let t=0,i=0;i<e.payload.byteLength;[t,i]=[t+1,i+s]){let n=this.sequence.getThenIncrement(),a=new co(Object.assign(Object.assign({},r),{marker:cb.computeFrameMarker(t,o),sequence:n})),c=Math.min(s,e.payload.byteLength-i),l=new Uint8Array(e.payload.buffer,e.payload.byteOffset+i,c);yield new cc(a,l)}}}(G=eV||(eV={}))[G.NotAllowed=0]="NotAllowed",G[G.DuplicateName=1]="DuplicateName",G[G.Timeout=2]="Timeout",G[G.LimitReached=3]="LimitReached",G[G.Disconnected=4]="Disconnected",G[G.Cancelled=5]="Cancelled",G[G.InvalidName=6]="InvalidName",G[G.Unknown=7]="Unknown";class ck extends aD{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=eV[t],this.rawMessage=null==i?void 0:i.rawMessage}static notAllowed(e){return new ck("Data track publishing unauthorized",eV.NotAllowed,{rawMessage:e})}static duplicateName(e){return new ck("Track name already taken",eV.DuplicateName,{rawMessage:e})}static invalidName(e){return new ck("Track name is invalid",eV.InvalidName,{rawMessage:e})}static timeout(){return new ck("Publish data track timed-out. Does the LiveKit server support data tracks?",eV.Timeout)}static limitReached(e){return new ck("Data track publication limit reached",eV.LimitReached,{rawMessage:e})}static unknown(e,t){return new ck("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),eV.Unknown)}static disconnected(){return new ck("Room disconnected",eV.Disconnected)}static cancelled(){return new ck("Publish data track cancelled by caller",eV.Cancelled)}}(z=eH||(eH={}))[z.TrackUnpublished=0]="TrackUnpublished",z[z.Dropped=1]="Dropped";class cy extends aD{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=eH[t]}static trackUnpublished(){return new cy("Track is no longer published",eH.TrackUnpublished)}static dropped(e){return new cy("Frame was dropped",eH.Dropped,{cause:e})}}(K=eW||(eW={}))[K.Packetizer=0]="Packetizer",K[K.Encryption=1]="Encryption";class cT extends aD{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=eW[t]}static packetizer(e){return new cT("Error packetizing frame",eW.Packetizer,{cause:e})}static encryption(e){return new cT("Error encrypting frame",eW.Encryption,{cause:e})}}class cS{constructor(e,t){this.trackSymbol=cr,this.isLocal=!0,this.typeSymbol=ca,this.handle=null,this.log=rS,this.options=e,this.manager=t,this.log=rC(ea.DataTracks)}static withExplicitHandle(e,t,i){let n=new cS(e,t);return n.handle=i,n}get info(){let e=this.descriptor;return(null==e?void 0:e.type)==="active"?e.info:void 0}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return rP(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){var e;return(null==(e=this.descriptor)?void 0:e.type)==="active"&&"unpublished"!==this.descriptor.publishState}tryPush(e){if(!this.handle)throw cy.trackUnpublished();let t=cn.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}unpublish(){return rP(this,void 0,void 0,function*(){if(!this.handle)return void rS.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}}class cC{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new cb(e.info.pubHandle,cC.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return function(e,t,i){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n,r=i.apply(e,t||[]),a=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,l)}}),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){r[e]&&(n[e]=function(t){return new Promise(function(i,n){a.push([e,t,i,n])>1||o(e,t)})},t&&(n[e]=t(n[e])))}function o(e,t){try{var i;(i=r[e](t)).value instanceof rR?Promise.resolve(i.value.v).then(c,l):d(a[0][2],i)}catch(e){d(a[0][3],e)}}function c(e){o("next",e)}function l(e){o("throw",e)}function d(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}}(this,arguments,function*(){let t=yield rR(this.encryptIfNeeded(e));try{yield rR((yield*function(e){var t,i;return t={},n("next"),n("throw",function(e){throw e}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,r){t[n]=e[n]?function(t){return(i=!i)?{value:rR(e[n](t)),done:!1}:r?r(t):t}:r}}(rI(this.packetizer.packetize(t)))))}catch(e){if(e instanceof cv)throw cT.packetizer(e);throw e}})}encryptIfNeeded(e){return rP(this,void 0,void 0,function*(){let t;if(!this.e2eeManager)return e;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw cT.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new ct(t.keyIndex,t.iv),e})}}cC.TRANSPORT_MTU_BYTES=16e3;let cE=rC(ea.DataTracks);class cw extends r_.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new s0,this.descriptors=new Map,this.e2eeManager=null!=(t=null==e?void 0:e.e2eeManager)?t:null}static withDescriptors(e){let t=new cw;return t.descriptors=e,t}updateE2eeManager(e){for(let t of(this.e2eeManager=e,this.descriptors.values())
2)"active"===t.type&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return null!=(t=this.descriptors.get(e))?t:null}tryProcessAndSend(e,t){return rP(this,void 0,void 0,function*(){var i,n,r,a;let s=this.getDescriptor(e);if((null==s?void 0:s.type)!=="active"||"unpublished"===s.publishState)throw cy.trackUnpublished();if("republishing"===s.publishState)throw cy.dropped("Data track republishing");try{try{for(var o,c=!0,l=rI(s.pipeline.processFrame(t));!(i=(o=yield l.next()).done);c=!0)a=o.value,c=!1,this.emit("packetAvailable",{bytes:a.toBinary()})}catch(e){n={error:e}}finally{try{!c&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(n)throw n.error}}}catch(e){throw cy.dropped(e)}})}publishRequest(e,t){return rP(this,void 0,void 0,function*(){let i=this.handleAllocator.get();if(!i)throw ck.limitReached();let n=o9(1e4),r=t?o4([t,n]):n;if(this.descriptors.has(i))throw Error("Descriptor for handle already exists");let a={type:"pending",completionFuture:new sw};this.descriptors.set(i,a);let s=()=>{var e,t;let r=this.descriptors.get(i);r?(this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),"pending"===r.type&&(null==(t=(e=r.completionFuture).reject)||t.call(e,n.aborted?ck.timeout():ck.cancelled()))):cE.warn("No descriptor for ".concat(i))};return r.aborted?(s(),a.completionFuture.promise.then(()=>i)):(r.addEventListener("abort",s),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:null!==this.e2eeManager}),yield a.completionFuture.promise,r.removeEventListener("abort",s),this.emit("trackPublished",{track:cS.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>"active"===e.type).map(e=>e.info)}unpublishRequest(e){return rP(this,void 0,void 0,function*(){let t=this.descriptors.get(e);t?"active"!==t.type?cE.warn("Track ".concat(e," not active")):(this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.emit("trackUnpublished",{sid:t.info.sid})):cE.warn("No descriptor for ".concat(e))})}receivedSfuPublishResponse(e,t){var i,n,r,a;let s=this.descriptors.get(e);if(!s)return void cE.warn("No descriptor for ".concat(e));switch(this.descriptors.delete(e),s.type){case"pending":if("ok"===t.type){let e,r=t.data,a=r.usesE2ee?this.e2eeManager:null;this.descriptors.set(r.pubHandle,(e=r,{type:"active",info:e,publishState:"published",pipeline:new cC({info:e,e2eeManager:a}),unpublishingFuture:new sw})),null==(n=(i=s.completionFuture).resolve)||n.call(i)}else null==(a=(r=s.completionFuture).reject)||a.call(r,t.error);return;case"active":if("republishing"!==s.publishState)return void cE.warn("Track ".concat(e," already active"));if("error"===t.type)return void cE.warn("Republish failed for track ".concat(e));cE.debug("Track ".concat(e," republished")),s.info.sid=t.data.sid,s.publishState="published",this.descriptors.set(s.info.pubHandle,s)}}receivedSfuUnpublishResponse(e){var t,i;let n=this.descriptors.get(e);n?(this.descriptors.delete(e),"active"!==n.type)?cE.warn("Track ".concat(e," not active")):(n.publishState="unpublished",null==(i=(t=n.unpublishingFuture).resolve)||i.call(t)):cE.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(let[i,n]of this.descriptors.entries())switch(n.type){case"pending":this.descriptors.delete(i),null==(t=(e=n.completionFuture).reject)||t.call(e,ck.disconnected());break;case"active":n.publishState="republishing",this.emit("sfuPublishRequest",{handle:n.info.pubHandle,name:n.info.name,usesE2ee:n.info.usesE2ee})}}shutdown(){return rP(this,void 0,void 0,function*(){var e,t,i,n;for(let r of this.descriptors.values())switch(r.type){case"pending":null==(t=(e=r.completionFuture).reject)||t.call(e,ck.disconnected());break;case"active":null==(n=(i=r.unpublishingFuture).resolve)||n.call(i),yield this.unpublishRequest(r.info.pubHandle)}this.descriptors.clear()})}}class cP extends a9{constructor(e,t,i,n,r){super(e,i,r),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?eg.Muted:eg.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit
2(eg.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return rP(this,void 0,void 0,function*(){var e;if(null==(e=this.receiver)?void 0:e.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver)if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;else this.log.warn("Playout delay not supported in this browser");else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),2e3)),"u">typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());let i=null==(t=this.receiver)?void 0:t.getSynchronizationSources()[0];if(i){let{timestamp:e,rtpTimestamp:t}=i;
2t&&this.rtpTimestamp!==t&&(this.emit(eg.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class cR extends cP{constructor(e,t,i,n,r,a){super(e,t,a9.Kind.Audio,i,a),this.monitorReceiver=()=>rP(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=oC(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(let i of this.attachedElements)this.audioContext?null==(t=this.gainNode)||t.gain.setTargetAtTime(e,0,.1):i.volume=e;sd()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(sd())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return rP(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(sn(t))return t.setSinkId(e)}))})}attach(e){let t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&sn(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(eg.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(eg.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null==(e=this.gainNode)||e.disconnect(),null==(t=this.sourceNode)||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return rP(this,void 0,void 0,function*(){let e;if(this.receiver&&this.receiver.getStats)return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})}),e})}}class cI extends cP{constructor(e,t,i,n,r){super(e,t,a9.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>rP(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=oC(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=oa(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===a9.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?a8(this._mediaStreamTrack,t):a6(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){let t=new cD(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);for(let t of this.elementInfos.filter(t=>t===e))t.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);for(let e of t=super.detach())this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null==(e=this.prevStats)?void 0:e.decoderImplementation}getReceiverStats(){return rP(this,void 0,void 0,function*(){let e;if(!this.receiver||!this.receiver.getStats)return;let t=yield this.receiver.getStats(),i="",n=new Map;return t.forEach(t=>
2{"inbound-rtp"===t.type?(i=t.codecId,e={type:"video",streamId:t.id,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation}):"codec"===t.type&&n.set(t.id,t)}),e&&""!==i&&n.get(i)&&(e.mimeType=n.get(i).mimeType),e})}stopObservingElement(e){for(let t of this.elementInfos.filter(t=>t.element===e))this.stopObservingElementInfo(t)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return rP(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;let n=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),r=(null==(i=null==(t=this.adaptiveStreamSettings)?void 0:t.pauseVideoInBackground)||!!i)&&this.isInBackground,a=this.elementInfos.some(e=>e.pictureInPicture),s=this.elementInfos.some(e=>e.visible)&&!r||a;if(this.lastVisible!==s||e){if(!s&&Date.now()-n<100)return void aB.setTimeout(()=>{this.updateVisibility()},100);this.lastVisible=s,this.emit(eg.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let i=0,n=0,r=this.getPixelDensity();for(let e of this.elementInfos){let t=e.width()*r,a=e.height()*r;t+a>i+n&&(i=t,n=a)}((null==(e=this.lastDimensions)?void 0:e.width)!==i||(null==(t=this.lastDimensions)?void 0:t.height)!==n)&&(this.lastDimensions={width:i,height:n},this.emit(eg.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=null==(e=this.adaptiveStreamSettings)?void 0:e.pixelDensity;return"screen"===t?sg():t?t:sg()>2?2:1}}class cD{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=c_(this.element),this.visibilityChangedAt=Date.now(),null==(t=this.handleVisibilityChanged)||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null==(t=null==(e=window.documentPictureInPicture)?void 0:e.window)||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=c_(this.element),null==(i=this.handleVisibilityChanged)||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=c_(this.element),null==(e=this.handleVisibilityChanged)||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:cO(e),this.isPiP=sl()&&c_(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=cO(this.element),this.isPiP=c_(this.element),this.element.handleResize=()=>{var e;null==(e=this.handleResize)||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,sS().observe(this.element),sy().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null==(e=window.documentPictureInPicture)||e.addEventListener("enter",this.onEnterPiP),null==(i=null==(t=window.documentPictureInPicture)?void 0:t.window)||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,r;null==(e=sS())||e.unobserve(this.element),null==(t=sy())||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null==(i=window.documentPictureInPicture)||i.removeEventListener("enter",this.onEnterPiP),null==(r=null==(n=window.documentPictureInPicture)?void 0:n.window)||r.removeEventListener("pagehide",this.onLeavePiP)}}function c_(e){var t,i;return document.pictureInPictureElement===e||null!=(t=window.documentPictureInPicture)&&!!t.window&&cO(e,null==(i=window.documentPictureInPicture)?void 0:i.window)}function cO(e,t){let i=t||window,n=e.offsetTop,r=e.offsetLeft,a=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&r<i.pageXOffset+i.innerWidth&&n+s>i.pageYOffset&&r+a>i.pageXOffset&&!o&&"none"!==c}class cM extends r_.EventEmitter{constructor(e,t,i,n){var r;super(),this.metadataMuted=!1,this.encryption=iT.NONE,this.log=rS,this.handleMuted=()=>
2{this.emit(eg.Muted)},this.handleUnmuted=()=>{this.emit(eg.Unmuted)},this.log=rC(null!=(r=null==n?void 0:n.loggerName)?r:ea.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=a9.Source.Unknown}setTrack(e){this.track&&(this.track.off(eg.Muted,this.handleMuted),this.track.off(eg.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(eg.Muted,this.handleMuted),e.on(eg.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),a1(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==iT.NONE}get audioTrack(){if(sM(this.track))return this.track}get videoTrack(){if(sx(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=a9.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===a9.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(Q=(J=cM||(cM={})).SubscriptionStatus||(J.SubscriptionStatus={})).Desired="desired",Q.Subscribed="subscribed",Q.Unsubscribed="unsubscribed",(Y=J.PermissionStatus||(J.PermissionStatus={})).Allowed="allowed",Y.NotAllowed="not_allowed";class cx extends cM{get isUpstreamPaused(){var e;return null==(e=this.track)?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(eg.Ended)},this.handleCpuConstrained=()=>{this.track&&sx(this.track)&&this.emit(eg.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(eg.Ended,this.handleTrackEnded),this.track.off(eg.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(eg.Ended,this.handleTrackEnded),e.on(eg.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return rP(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.mute()})}unmute(){return rP(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.unmute()})}pauseUpstream(){return rP(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.pauseUpstream()})}resumeUpstream(){return rP(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(!sM(this.track))return[];{let t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(iu.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(iu.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(iu.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(iu.TF_STEREO),(null==(e=this.options)?void 0:e.dtx)||i.add(iu.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(iu.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}}}function cA(e,t){return rP(this,void 0,void 0,function*(){null!=e||(e={});let i=!1,{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:a}=a2(e),s=a.audio,o=a.video;if(n&&"object"==typeof a.audio&&(a.audio.processor=n),r&&"object"==typeof a.video&&(a.video.processor=r),e.audio&&"object"==typeof a.audio&&"string"==typeof a.audio.deviceId){let e=a.audio.deviceId;a.audio.deviceId={exact:e},i=!0,s=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&"object"==typeof a.video&&"string"==typeof a.video.deviceId){let e=a.video.deviceId;a.video.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}!0===a.audio?a.audio={deviceId:"default"}:"object"==typeof a.audio&&null!==a.audio&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),!0===a.video?a.video={deviceId:"default"}:"object"!=typeof a.video||a.video.deviceId||(a.video.deviceId="default");let c=aJ(a,om,og),l=aY(c),d=navigator.mediaDevices.getUserMedia(l);
2a.audio&&(sK.userMediaPromiseMap.set("audioinput",d),d.catch(()=>sK.userMediaPromiseMap.delete("audioinput"))),a.video&&(sK.userMediaPromiseMap.set("videoinput",d),d.catch(()=>sK.userMediaPromiseMap.delete("videoinput")));try{let e=yield d;return yield Promise.all(e.getTracks().map(i=>rP(this,void 0,void 0,function*(){let a,s="audio"===i.kind,o=s?c.audio:c.video;"boolean"!=typeof o&&o||(o={});let d=s?l.audio:l.video;"boolean"!=typeof d&&(a=d);let u=i.getSettings().deviceId;(null==a?void 0:a.deviceId)&&sP(a.deviceId)!==u?a.deviceId=u:a||(a={deviceId:u});let h=function(e,t,i){switch(e.kind){case"audio":return new oI(e,t,!1,void 0,i);case"video":return new oB(e,t,!1,i);default:throw new aM("unsupported track type: ".concat(e.kind))}}(i,a,t);return h.kind===a9.Kind.Video?h.source=a9.Source.Camera:h.kind===a9.Kind.Audio&&(h.source=a9.Source.Microphone),h.mediaStream=e,sM(h)&&n?yield h.setProcessor(n):sx(h)&&r&&(yield h.setProcessor(r)),h})))}catch(n){if(!i)throw n;return cA(Object.assign(Object.assign({},e),{audio:s,video:o}),t)}})}function cN(e){return rP(this,void 0,void 0,function*(){return(yield cA({audio:!1,video:null==e||e}))[0]})}function cL(e){return rP(this,void 0,void 0,function*(){return(yield cA({audio:null==e||e,video:!1}
2))[0]})}(X=eG||(eG={})).Excellent="excellent",X.Good="good",X.Poor="poor",X.Lost="lost",X.Unknown="unknown";class cU extends r_.EventEmitter{get logContext(){var e,t;return Object.assign({},null==(t=null==(e=this.loggerOptions)?void 0:e.loggerContextCb)?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return(null==(e=this.permissions)?void 0:e.agent)||this.kind===ik.AGENT}get isActive(){var e;return(null==(e=this.participantInfo)?void 0:e.state)===ib.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,r,a){var s;let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ik.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=eG.Unknown,this.log=rS,this.log=rC(null!=(s=null==a?void 0:a.loggerName)?s:ea.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new sw,this.once(ep.Active,()=>{var e,t;null==(t=null==(e=this.activeFuture)?void 0:e.resolve)||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;let t=this.getTrackPublication(a9.Source.Camera);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(a9.Source.Microphone);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(a9.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return(!this.participantInfo||this.participantInfo.sid!==e.sid||!(this.participantInfo.version>e.version))&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===ib.ACTIVE&&(null==(t=this.participantInfo)?void 0:t.state)!==ib.ACTIVE&&this.emit(ep.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(ep.ParticipantMetadataChanged,i)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(ep.ParticipantNameChanged,e)}_setAttributes(e){let t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let a of n)e[a]!==t[a]&&(r[a]=null!=(i=t[a])?i:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(ep.AttributesChanged,t)}setPermissions(e){var t,i,n,r,a,s;let o=this.permissions,c=e.canPublish!==(null==(t=this.permissions)?void 0:t.canPublish)||e.canSubscribe!==(null==(i=this.permissions)?void 0:i.canSubscribe)||e.canPublishData!==(null==(n=this.permissions)?void 0:n.canPublishData)||e.hidden!==(null==(r=this.permissions)?void 0:r.hidden)||e.recorder!==(null==(a=this.permissions)?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null==(i=this.permissions)?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null==(s=this.permissions)?void 0:s.canSubscribeMetrics);return this.permissions=e,c&&this.emit(ep.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ep.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case is.EXCELLENT:return eG.Excellent;case is.GOOD:return eG.Good;case is.POOR:return eG.Poor;case is.LOST:return eG.Lost;default:return eG.Unknown}}
2(e),t!==this._connectionQuality&&this.emit(ep.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null==(t=(e=this.activeFuture).reject)||t.call(e,Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>sM(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(e.on(eg.Muted,()=>{this.emit(ep.TrackMuted,e)}),e.on(eg.Unmuted,()=>{this.emit(ep.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case a9.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case a9.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class cj extends cU{constructor(e,t,i,n,r,a,s){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=iT.NONE,this.e2eeStateMutex=new eZ,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sw)},this.handleReconnected=()=>{var e,t;null==(t=null==(e=this.reconnectFuture)?void 0:e.resolve)||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,r,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null==(t=null==(e=this.reconnectFuture)?void 0:e.reject)||t.call(e,Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null==(n=(i=this.signalConnectedFuture).reject)||n.call(i,Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null==(a=null==(r=this.activeAgentFuture)?void 0:r.reject)||a.call(r,Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new sw),null==(i=(t=this.signalConnectedFuture).resolve)||i.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:i,message:n}=e,r=this.pendingSignalRequests.get(t);if(r&&(i!==n1.OK&&r.reject(new aU(n,i)),this.pendingSignalRequests.delete(t)),"publishDataTrack"===e.request.case){let t;switch(e.reason){case n1.NOT_ALLOWED:t=ck.notAllowed(e.message);break;case n1.DUPLICATE_NAME:t=ck.duplicateName(e.message);break;case n1.INVALID_NAME:t=ck.invalidName(e.message);break;case n1.LIMIT_EXCEEDED:t=ck.limitReached(e.message);break;default:t=ck.unknown(e.reason,e.message);return}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:"error",error:t})}},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=oy.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let r=e.value.value;this.handleIncomingRpcAck(r.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>(function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new nq({participantIdentity:null!=(t=e.participantIdentity)?t:"",participantSid:null!=(i=e.participantSid)?i:"",allTracks:null!=(n=e.allowAll)&&n,trackSids:e.allowedTrackSids||[]})})(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{(void 0===t&&(t=!0),e.sid)?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),a1(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),a1(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),a1(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({}
2,this.logContext),a1(t))),this.emit(ep.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>rP(this,void 0,void 0,function*(){if(!(null==(o=this.roomOptions)?void 0:o.dynacast))return;let t=this.videoTrackPublications.get(e.trackSid);if(!t)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!t.videoTrack)return;let i=yield t.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var n,r,a,s,o,c,l=!0,d=rI(i);!(n=(c=yield d.next()).done);l=!0)s=c.value,l=!1,aW(s)&&(this.log.debug("publish ".concat(s," for ").concat(t.videoTrack.sid),Object.assign(Object.assign({},this.logContext),a1(t))),yield this.publishAdditionalCodecForTrack(t.videoTrack,s,t.options))}catch(e){r={error:e}}finally{try{!l&&!n&&(a=d.return)&&(yield a.call(d))}finally{if(r)throw r.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>rP(this,void 0,void 0,function*(){if(e.source===a9.Source.ScreenShare||e.source===a9.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),a1(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(sN(e)||sA(e))try{if(sl())try{let t=yield null==navigator?void 0:navigator.permissions.query({name:e.source===a9.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),a1(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),a1(e))),sN(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),a1(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=a,this.roomOutgoingDataTrackManager=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==iT.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(em.RemoteMute,(e,t)=>{let i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null==(t=this.signalConnectedFuture)?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(em.Connected,this.handleReconnected).on(em.SignalConnected,this.handleSignalConnected).on(em.SignalRestarted,this.handleReconnected).on(em.SignalResumed,this.handleReconnected).on(em.Restarting,this.handleReconnecting).on(em.Resuming,this.handleReconnecting).on(em.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(em.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(em.Closing,this.handleClosing).on(em.SignalRequestResponse,this.handleSignalRequestResponse).on(em.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return rP(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return rP(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return rP(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return rP(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:r}=e;return function*(){return new aS((e,a)=>rP(t,void 0,void 0,function*(){var t,s;try{let o=!1,c=yield this.engine.client.sendUpdateLocalMetadata(null!=(t=null!=i?i:this.metadata)?t:"",null!=(s=null!=n?n:this.name)?s:"",r),l=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{a(e),o=!0}
2,values:{name:n,metadata:i,attributes:r}});performance.now()-l<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!r||Object.entries(r).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))){this.pendingSignalRequests.delete(c),e();return}yield a7(50)}a(new aU("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(a9.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(a9.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(a9.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return rP(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?iT.GCM:iT.NONE,yield Promise.all(this.pendingPublishPromises.values()),0===this.trackPublications.size||Array.from(this.trackPublications.values()).every(t=>t.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,i,n){return rP(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t)if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case a9.Source.Camera:t=yield this.createTracks({video:null==i||i});break;case a9.Source.Microphone:t=yield this.createTracks({audio:null==i||i});break;case a9.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new aM(e)}}catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(ep.MediaDevicesError,i,a$(e)),this.pendingPublishing.delete(e),i}for(let n of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===a9.Source.Microphone&&sM(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{let e=[];for(let i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),a1(i))),e.push(this.publishTrack(i,n));let i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e)&&((r=yield this.waitForPendingPublicationOfSource(e))||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),r&&r.track)if(e===a9.Source.ScreenShare){r=yield this.unpublishTrack(r.track);let e=this.getTrackPublication(a9.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r})}enableCameraAndMicrophone(){return rP(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(a9.Source.Camera)||this.pendingPublishing.has(a9.Source.Microphone))){this.pendingPublishing.add(a9.Source.Camera),this.pendingPublishing.add(a9.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(a9.Source.Camera),this.pendingPublishing.delete(a9.Source.Microphone)}}})}createTracks(e){return rP(this,void 0,void 0,function*(){var t,i;null!=e||(e={});let n=aJ(e,null==(t=this.roomOptions)?void 0:t.audioCaptureDefaults,null==(i=this.roomOptions)?void 0:i.videoCaptureDefaults);try{return(yield cA(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(sM(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=a9.Source.Microphone,this.emit(ep.AudioStreamAcquired)),sx(e)&&(this.cameraError=void 0,e.source=a9.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return rP(this,void 0,void 0,function*(){var t,i,n;let r,a;
2if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new aO("getDisplayMedia not supported");void 0!==e.resolution||(null==(r=aE())?void 0:r.name)==="Safari"&&r.version.startsWith("17.")||(null==r?void 0:r.os)==="iOS"&&(null==r?void 0:r.osVersion)&&sf(r.osVersion,"17")>=0||(e.resolution=aK.h1080fps30.resolution);let s=(a=null==(i=(t=e).video)||i,t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(a="boolean"==typeof a?{}:a,a=ss()?Object.assign(Object.assign({},a),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):Object.assign(Object.assign({},a),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:null!=(n=t.audio)&&n,video:a,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}),o=yield navigator.mediaDevices.getDisplayMedia(s),c=o.getVideoTracks();if(0===c.length)throw new aM("no video track found");let l=new oB(c[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});l.source=a9.Source.ScreenShare,e.contentHint&&(l.mediaStreamTrack.contentHint=e.contentHint);let d=[l];if(o.getAudioTracks().length>0){this.emit(ep.AudioStreamAcquired);let e=new oI(o.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=a9.Source.ScreenShareAudio,d.push(e)}return d})}publishTrack(e,t){return rP(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return rP(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var r,a;let s,o;if(sN(e)&&e.setAudioContext(i.audioContext),yield null==(r=i.reconnectFuture)?void 0:r.promise,i.republishPromise&&!n&&(yield i.republishPromise),sO(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)s=e.getConstraints();else{let t;switch(s=e.constraints,e.source){case a9.Source.Microphone:t="audioinput";break;case a9.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(s=Object.assign(Object.assign({},s),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new oI(e,s,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new oB(e,s,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new aM("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(o=t)}),o)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),a1(o))),o;let c=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,d=null!=(a=c.forceStereo)?a:l;d&&(void 0===c.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),a1(e))),void 0===c.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!=c.dtx||(c.dtx=!1),null!=c.red||(c.red=!1)),!function(){let e=aE(),t="17.2";if(e)if("Safari"!==e.name&&"iOS"!==e.os)return!0;else if("iOS"===e.os&&e.osVersion&&sf(e.osVersion,t)>=0)return!0;else if("Safari"===e.name&&sf(e.version,t)>=0)return!0;else return!1}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),c.simulcast=!1),c.source&&(e.source=c.source);let u=new Promise((t,n)=>rP(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==eP.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:a1(e)}));let i=!1,r=setTimeout(()=>{i=!0,e.stop(),n(new aL("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),i)return;let a=yield this.publish(e,c,d);t(a)}else try{let i=yield this.publish(e,c,d);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,u);try{return yield u}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new sw),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),a1(e))),!1;let{canPublish:t,canPublishSources:i}=this.permissions;return!!(t&&(0===i.length||i.map(e=>(function(e){switch(e){case ir.CAMERA:return a9.Source.Camera;case ir.MICROPHONE:return a9.Source.Microphone;case ir.SCREEN_SHARE:return a9.Source.ScreenShare;case ir.SCREEN_SHARE_AUDIO:return a9.Source.ScreenShareAudio;default:return a9.Source.Unknown}})(e)).includes(e.source)))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),a1(e))),!1)}publish(e,t,i){return rP(this,void 0,void 0,function*(){var n,r,a,s,o,c,l,d,u,h;let p,m;if(!this.hasPermissionsToPublish(e))throw new aL("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>sO(e)&&t.source===e.source)&&e.source!==a9.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),a1(e))),t.stopMicTrackOnMute&&sM(e)&&(e.stopOnMute=!0),e.source===a9.Source.ScreenShare&&sr()&&(t.simulcast=!1),"av1"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||ss()||sr())return!1;let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}}return t}()&&(t.videoCodec=void 0),"vp9"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||sr())return!1;if(ss()){let e=aE();if((null==e?void 0:e.version)&&0>sf(e.version,"16")||(null==e?void 0:e.os)==="iOS"&&(null==e?void 0:e.osVersion)&&0>sf(e.osVersion,"16"))return!1}let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/vp9"===i.mimeType.toLowerCase()){t=!0;break}}return t}()&&(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec="vp8"),this.enabledPublishVideoCodecs.length>0&&!this.enabledPublishVideoCodecs.some(e=>t.videoCodec===a0(e.mime))&&(t.videoCodec=a0(this.enabledPublishVideoCodecs[0].mime));let g=t.videoCodec;e.on(eg.Muted,this.onTrackMuted),e.on(eg.Unmuted,this.onTrackUnmuted),e.on(eg.Ended,this.handleTrackEnded),e.on(eg.UpstreamPaused,this.onTrackUpstreamPaused),e.on(eg.UpstreamResumed,this.onTrackUpstreamResumed),e.on(eg.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let f=[],v=!(null==(n=t.dtx)||n),b=e.getSourceTrackSettings();b.autoGainControl&&f.push(iu.TF_AUTO_GAIN_CONTROL),b.echoCancellation&&f.push(iu.TF_ECHO_CANCELLATION),b.noiseSuppression&&f.push(iu.TF_NOISE_SUPPRESSION),b.channelCount&&b.channelCount>
21&&f.push(iu.TF_STEREO),v&&f.push(iu.TF_NO_DTX),sN(e)&&e.hasPreConnectBuffer&&f.push(iu.TF_PRECONNECT_BUFFER);let k=new na({cid:e.mediaStreamTrack.id,name:t.name,type:a9.kindToProto(e.kind),muted:e.isMuted,source:a9.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null==(r=t.red)||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:f});if(e.kind===a9.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(n){let t=null!=(s=null==(a=this.roomOptions.videoCaptureDefaults)?void 0:a.resolution)?s:aG.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),a1(e)),{dims:i}))}k.width=i.width,k.height=i.height,sA(e)&&(si(g)&&(e.source===a9.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),a1(e))))),t.scalabilityMode=null!=(o=t.scalabilityMode)?o:"L3T3_KEY"),k.simulcastCodecs=[new nr({codec:g,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:"vp8"}),t.backupCodec&&g!==t.backupCodec.codec&&k.encryption===iT.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),k.simulcastCodecs.push(new nr({codec:t.backupCodec.codec,cid:""})))),p=oN(e.source===a9.Source.ScreenShare,k.width,k.height,t),k.layers=oH(k.width,k.height,p,si(t.videoCodec))}else e.kind===a9.Kind.Audio&&(p=[{maxBitrate:null==(c=t.audioPreset)?void 0:c.maxBitrate,priority:null!=(d=null==(l=t.audioPreset)?void 0:l.priority)?d:"high",networkPriority:null!=(h=null==(u=t.audioPreset)?void 0:u.priority)?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new aA("cannot publish track when not connected");let y=()=>rP(this,void 0,void 0,function*(){var i,n;if(!this.engine.pcManager)throw new aA("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,p),this.emit(ep.LocalSenderCreated,e.sender,e),sA(e)&&(null!=t.degradationPreference||(t.degradationPreference=e.source===a9.Source.ScreenShare||e.constraints.height&&sP(e.constraints.height)>=1080?"maintain-resolution":"balanced"),e.setDegradationPreference(t.degradationPreference)),p)if(sr()&&e.kind===a9.Kind.Audio){let t;for(let i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null==(i=p[0])?void 0:i.maxBitrate)?p[0].maxBitrate/1e3:0})}else e.codec&&si(e.codec)&&(null==(n=p[0])?void 0:n.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:k.cid,codec:e.codec,maxbr:p[0].maxBitrate/1e3});yield this.engine.negotiate()}),T=new Promise((t,i)=>rP(this,void 0,void 0,function*(){var n;try{m=yield this.engine.addTrack(k),t(m)}catch(t){e.sender&&(null==(n=this.engine.pcManager)?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),a1(e)),{error:t}))})),i(t)}}));if(this.enabledPublishVideoCodecs.length>0)m=(yield Promise.all([T,y()]))[0];else{let i;if((m=yield T).codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===a9.Kind.Video){let n=a0(i);n!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),a1(e)),{codec:n})),t.videoCodec=n,p=oN(e.source===a9.Source.ScreenShare,k.width,k.height,t))}yield y()}let S=new cx(e.kind,m,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(S.on(eg.CpuConstrained,e=>this.onTrackCpuConstrained(e,S)),S.options=t,e.sid=m.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:p,trackInfo:m})),sA(e)?e.startMonitor(this.engine.client):sN(e)&&e.startMonitor(),this.addTrackPublication(S),this.emit
2(ep.LocalTrackPublished,S),sN(e)&&m.audioFeatures.includes(iu.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();this.on(ep.LocalTrackSubscribed,t=>{if(t.trackSid===m.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),a1(e))),e.stopPreConnectBuffer()}}),t&&new Promise((n,r)=>rP(this,void 0,void 0,function*(){try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),a1(e)));let m=setTimeout(()=>{r(Error("agent not active within 10 seconds"))},1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),a1(e)));let f=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:S.trackSid,sampleRate:String(null!=(l=b.sampleRate)?l:"48000"),channels:String(null!=(d=b.channelCount)?d:"1")}});try{for(var a,s,o,c,l,d,u,h=!0,p=rI(t);!(a=(u=yield p.next()).done);h=!0)c=u.value,h=!1,yield f.write(c)}catch(e){s={error:e}}finally{try{!h&&!a&&(o=p.return)&&(yield o.call(p))}finally{if(s)throw s.error}}yield f.close(),n()}catch(e){r(e)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),a1(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),a1(e)),{error:t}))})}return S})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return rP(this,void 0,void 0,function*(){var n;let r;if(this.encryptionType!==iT.NONE)return;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new aM("track is not published");if(!sA(e))throw new aM("track is not a video track");let a=Object.assign(Object.assign({},null==(n=this.roomOptions)?void 0:n.publishDefaults),i),s=function(e,t,i){var n,r,a,s;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&rS.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;let o=e.mediaStreamTrack.getSettings(),c=null!=(n=o.width)?n:null==(r=e.dimensions)?void 0:r.width,l=null!=(a=o.height)?a:null==(s=e.dimensions)?void 0:s.height;return e.source===a9.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),oN(e.source===a9.Source.ScreenShare,c,l,i)}(e,t,a);if(!s)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),a1(e)));let o=e.addSimulcastTrack(t,s);if(!o)return;let c=new na({cid:o.mediaStreamTrack.id,type:a9.kindToProto(e.kind),muted:e.isMuted,source:a9.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=oH(c.width,c.height,s),!this.engine||this.engine.isClosed)throw new aA("cannot publish track when not connected");let l=()=>rP(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,a,s),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:s,trackInfo:d}))})}unpublishTrack(e,t){return rP(this,void 0,void 0,function*(){var i,n;if(sO(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),a1(e))),yield t)}let r=this.getPublicationForTrack(e),a=r?a1(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));(e=r.track).off(eg.Muted,this.onTrackMuted),e.off(eg.Unmuted,this.onTrackUnmuted),e.off(eg.Ended,this.handleTrackEnded),e.off(eg.UpstreamPaused,this.onTrackUpstreamPaused),e.off(eg.UpstreamResumed,this.onTrackUpstreamResumed),e.off(eg.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null==(n=null==(i=this.roomOptions)?void 0:i.stopLocalTrackOnUnpublish)||n),t?e.stop():e.stopMonitor();let s=!1,o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<eM.FAILED&&o)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",s=!0);if(this.engine.removeTrack(o)&&(s=!0),sA(e)){for(let[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(s=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case a9.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case a9.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}
2return this.emit(ep.LocalTrackUnpublished,r),r.setTrack(void 0),s&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return rP(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return rP(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new aS((n,r)=>rP(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>rP(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==a9.Source.ScreenShare&&t.source!==a9.Source.ScreenShareAudio&&(sN(t)||sA(t))&&!t.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),n()}catch(e){e instanceof Error?r(e):r(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return rP(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){let n=i.reliable?eA.RELIABLE:eA.LOSSY,r=i.reliable?iD.RELIABLE:iD.LOSSY,a=i.destinationIdentities,s=i.topic,o=new iI({kind:r,value:{case:"user",value:new iA({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:s})}});yield t.engine.sendDataPacket(o,n)}()})}publishDtmf(e,t){return rP(this,void 0,void 0,function*(){let i=new iI({kind:iD.RELIABLE,value:{case:"sipDtmf",value:new iN({code:e,digit:t})}});yield this.engine.sendDataPacket(i,eA.RELIABLE)})}sendChatMessage(e,t){return rP(this,void 0,void 0,function*(){let i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new iI({value:{case:"chatMessage",value:new ij(Object.assign(Object.assign({},i),{timestamp:to.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,eA.RELIABLE),this.emit(ep.ChatMessage,i),i})}editChatMessage(e,t){return rP(this,void 0,void 0,function*(){let i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new iI({value:{case:"chatMessage",value:new ij(Object.assign(Object.assign({},i),{timestamp:to.parse(i.timestamp),editTimestamp:to.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,eA.RELIABLE),this.emit(ep.ChatMessage,i),i})}sendText(e,t){return rP(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return rP(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return rP(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return rP(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:n,responseTimeout:r=15e3}=e;return new aS((e,a)=>rP(this,void 0,void 0,function*(){var s,o,c,l;if(oT(n)>15360)return void a(oy.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null==(o=null==(s=this.engine.latestJoinResponse)?void 0:s.serverInfo)?void 0:o.version)&&0>sf(null==(l=null==(c=this.engine.latestJoinResponse)?void 0:c.serverInfo)?void 0:l.version,"1.8.0"))return void a(oy.builtIn("UNSUPPORTED_SERVER"));let d=Math.max(r,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(t,u,i,n,d);let h=setTimeout(()=>{this.pendingAcks.delete(u),a(oy.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)},7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:t});let p=setTimeout(()=>{this.pendingResponses.delete(u),a(oy.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(u,{resolve:(t,i)=>{clearTimeout(p),this.pendingAcks.has(u)&&(this.log.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),i?a(i):e(null!=t?t:"")},participantIdentity:t})}))}
2registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){let n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,r){return rP(this,void 0,void 0,function*(){let a=new iI({destinationIdentities:[e],kind:iD.RELIABLE,value:{case:"rpcRequest",value:new iF({id:t,method:i,payload:n,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,eA.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,oy.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;let n=this.trackPublications.get(e.sid);if(n){let r=n.isMuted||null!=(i=null==(t=n.track)?void 0:t.isUpstreamPaused)&&i;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),a1(n)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}}),!0)}setActiveAgent(e){var t,i,n,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null==(i=null==(t=this.activeAgentFuture)?void 0:t.resolve)||i.call(t,e):null==(r=null==(n=this.activeAgentFuture)?void 0:n.reject)||r.call(n,Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new sw),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{let n=i.track;n&&(e instanceof MediaStreamTrack?(sN(n)||sA(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return rP(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield a7(20)}})}publishDataTrack(e){return rP(this,void 0,void 0,function*(){let t=new cS(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class cF extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class cB extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i;super.set(e,t);let n=this.pending.get(e);if(n){for(let e of n)e.isResolved||null==(i=e.resolve)||i.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"WaitableMap"}getDeferred(e,t){return rP(this,void 0,void 0,function*(){let i=this.get(e);if(void 0!==i)return i;if(null==t?void 0:t.aborted)throw new cF("The operation was aborted.",t.reason);let n=new sw(void 0,()=>{let t=this.pending.get(e);if(!t)return;let i=t.indexOf(n);-1!==i&&t.splice(i,1),0===t.length&&this.pending.delete(e)}),r=this.pending.get(e);if(r?r.push(n):this.pending.set(e,[n]),t){let e=()=>{var e;n.isResolved||null==(e=n.reject)||e.call(n,new cF("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0}),n.promise.finally(()=>{t.removeEventListener("abort",e)})}return n.promise})}}class cq extends cM{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>
2{this.setTrack(void 0),this.emit(eg.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let n=new ny({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new iH({participantSid:"",trackSids:[this.trackSid]})]});this.emit(eg.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?cM.SubscriptionStatus.Unsubscribed:super.isSubscribed?cM.SubscriptionStatus.Subscribed:cM.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?cM.PermissionStatus.Allowed:cM.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&!e!==this.requestedDisabled&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null==(t=this.requestedVideoDimensions)?void 0:t.width)!==e.width||(null==(i=this.requestedVideoDimensions)?void 0:i.height)!==e.height)&&(sU(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&sU(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!=(e=this.requestedMaxQuality)?e:eb.HIGH}setTrack(e){let t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(eg.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(eg.VisibilityChanged,this.handleVisibilityChange),n.off(eg.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(eg.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(eg.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(eg.VisibilityChanged,this.handleVisibilityChange),e.on(eg.Ended,this.handleEnded),this.emit(eg.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(eg.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?eg.Muted:eg.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(eg.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(eg.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return sU(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new nC({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===a9.Kind.Video){let r=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(r)a3(this.videoDimensionsAdaptiveStream,r)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){var t,i,n;let e=(t=this.trackInfo,i=this.requestedMaxQuality,null==(n=t.layers)?void 0:n.find(e=>e.quality===i));e&&a3(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream;r?(e.width=Math.ceil(r.width),e.height=Math.ceil(r.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default qual
2ity",Object.assign(Object.assign({},this.logContext),{quality:eb.HIGH})),e.quality=eb.HIGH)}this.emit(eg.UpdateSettings,e)}}class cV extends cU{static fromParticipantInfo(e,t,i){return new cV(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,r,a,s){let o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:ik.STANDARD;super(t,i||"",n,r,a,s,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new cB,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(eg.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),a1(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(eg.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(eg.SubscriptionPermissionChanged,t=>{this.emit(ep.TrackSubscriptionPermissionChanged,e,t)}),e.on(eg.SubscriptionStatusChanged,t=>{this.emit(ep.TrackSubscriptionStatusChanged,e,t)}),e.on(eg.Subscribed,t=>{this.emit(ep.TrackSubscribed,t,e)}),e.on(eg.Unsubscribed,t=>{this.emit(ep.TrackUnsubscribed,t,e)}),e.on(eg.SubscriptionFailed,t=>{this.emit(ep.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a9.Source.Microphone;this.volumeMap.set(t,e);let i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a9.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,r,a){let s,o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(t=>{o||e.kind!==t.kind.toString()||(o=t)}),!o){if(0===a){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(ep.TrackSubscriptionFailed,t);return}void 0===a&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,r,a-1)},150);return}if("ended"===e.readyState){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),a1(o))),this.emit(ep.TrackSubscriptionFailed,t);return}return(s="video"===e.kind?new cI(e,t,n,r):new cR(e,t,n,this.audioContext,this.audioOutput)).source=o.source,s.isMuted=o.isMuted,s.setMediaStream(i),s.start(),o.setTrack(s),this.volumeMap.has(o.source)&&sL(s)&&sM(s)&&s.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,r;let a=this.getTrackPublicationBySid(e.sid);if(a)a.updateInfo(e);else{let t=a9.kindFromProto(e.type);if(!t)return;(a=new cq(t,e,null==(n=this.signalClient.connectOptions)?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null==(r=this.loggerOptions)?void 0:r.loggerName})).updateInfo(e),i.set(e.sid,a);let s=Array.from(this.trackPublications.values()).find(e=>e.source===(null==a?void 0:a.source));s&&a.source!==a9.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:a1(s),newTrack:a1(a)})),this.addTrackPublication(a)}t.set(e.sid,a)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),a1(e))),this.unpublishTrack(e.trackSid,!0))}
2),i.forEach(e=>{this.emit(ep.TrackPublished,e)}),!0}unpublishTrack(e,t){let i=this.trackPublications.get(e);if(!i)return;let{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case a9.Kind.Audio:this.audioTrackPublications.delete(e);break;case a9.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(ep.TrackUnpublished,i)}setAudioOutput(e){return rP(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(i=>{var n;sM(i.track)&&sL(i.track)&&t.push(i.track.setSinkId(null!=(n=e.deviceId)?n:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let[t,i]of this.dataTracks.entries())e===i.info.sid&&this.dataTracks.delete(t)}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(Z=ez||(ez={})).Disconnected="disconnected",Z.Connecting="connecting",Z.Connected="connected",Z.Reconnecting="reconnecting",Z.SignalReconnecting="signalReconnecting";class cH extends r_.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,r,a,s,o;if(super(),t=this,this.state=ez.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new eZ,this.isVideoPlaybackBlocked=!1,this.log=rS,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,i)=>rP(this,void 0,void 0,function*(){var n;if(!(!("u"<typeof RTCPeerConnection)&&(se()||st())))if(sd())throw Error("WebRTC isn't detected, have you called registerGlobals?");else throw Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");let r=yield this.disconnectLock.lock();if(this.state===ez.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(ez.Connecting),(null==(n=this.regionUrlProvider)?void 0:n.getServerUrl().toString())!==sF(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),su(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new ok(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null==(t=this.regionUrlProvider)||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));let a=(n,s,o)=>rP(this,void 0,void 0,function*(){var c,l;this.abortController&&this.abortController.abort();let d=new AbortController;this.abortController=d,null==r||r();try{if(yield sG.getInstance().getBackOffPromise(e),d.signal.aborted)throw a_.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=o?o:e,t,i,d),this.abortController=void 0,n()}catch(t){if(this.regionUrlProvider&&t instanceof a_&&t.reason!==el.Cancelled&&t.reason!==el.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null==(c=this.abortController)?void 0:c.signal)}catch(e){if(e instanceof a_&&(401===e.status||e.reason===el.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(e);return}}[el.InternalError,el.ServerUnreachable,el.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),sG.getInstance().addFailedConnectionAttempt(e)),!i||(null==(l=this.abortController)?void 0:l.signal.aborted)?(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,sI(t)),s(t)):(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(!0),yield a(n,s,i))}else{let e=ic.UNKNOWN_REASON;t instanceof a_&&(e=sI(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),s(t)}}}),s=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sw((e,t)=>{a(e,t,s)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,r,a)=>rP(this,void 0,void 0,function*(){let{joinResponse:s,serverInfo:o}=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},a.signal,!r.singlePeerConnection);
2if(this.serverInfo=o,!o.version)throw new ax("unknown server version");return"0.15.1"===o.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),r.dynacast=!1),s}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>rP(this,void 0,void 0,function*(){var r,a;this.state===ez.Reconnecting||this.isResuming||(null==(r=this.engine)?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine(!0)):this.maybeCreateEngine(),(null==(a=this.regionUrlProvider)?void 0:a.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ov),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(eh.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();let e=n.signal.aborted?a_.cancelled("Signal connection aborted"):a_.serverUnreachable("could not establish signal connection");throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof a_&&(e.reason=t.reason,e.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),a_.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}sl()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),sl()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ez.Connected),this.emit(eh.Connected),sG.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return rP(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n,r;let a=yield e.disconnectLock.lock();try{if(e.state===ez.Disconnected)return void e.log.debug("already disconnected",e.logContext);if(e.log.info("disconnect from room",Object.assign({},e.logContext)),e.state===ez.Connecting||e.state===ez.Reconnecting||e.isResuming){let t="Abort connection attempt due to user initiated disconnect";e.log.warn(t,e.logContext),null==(i=e.abortController)||i.abort(t),null==(r=null==(n=e.connectFuture)?void 0:n.reject)||r.call(n,a_.cancelled("Client initiated disconnect")),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,ic.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>rP(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>rP(this,void 0,void 0,function*(){let e=[],t=aE();if(t&&"iOS"===t.os){let t="livekit-dummy-audio-el",i=document.getElementById(t);if(!i){(i=document.createElement("audio")).id=t,i.autoplay=!0,i.hidden=!0;let e=sE();e.enabled=!0;let n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(eh.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}
2this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>rP(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null==(i=t.track)||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{for(let e of(this.clearConnectionReconcile(),this.isResuming=!1,this.remoteParticipants.values()))this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(ez.Reconnecting)&&this.emit(eh.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>rP(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(ez.Connected),this.emit(eh.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{var t;for(let i of e){if(i.identity===this.localParticipant.identity){this.localParticipant.updateInfo(i);continue}""===i.identity&&(i.identity=null!=(t=this.sidToIdentity.get(i.sid))?t:"");let e=this.remoteParticipants.get(i.identity);i.state===ib.DISCONNECTED?this.handleParticipantDisconnected(i.identity,e):e=this.getOrCreateParticipant(i.identity,i)}let i=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>s1(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(i)},this.handleActiveSpeakersUpdate=e=>{let t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEac
2h(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(eh.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});let i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(eh.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;let n=a9.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(ep.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(eh.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i,n)=>{this.emit(eh.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(ep.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit(eh.SipDTMFReceived,t,e),null==e||e.emit(ep.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{var i;let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=null==n?void 0:n.trackPublications.get(t.trackId),a=(i=this.transcriptionReceivedTimes,t.segments.map(e=>{var t;let{id:n,text:r,language:a,startTime:s,endTime:o,final:c}=e,l=null!=(t=i.get(n))?t:Date.now(),d=Date.now();return c?i.delete(n):i.set(n,l),{id:n,text:r,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:c,language:a,firstReceivedTime:l,lastReceivedTime:d}}));null==r||r.emit(eg.TranscriptionReceived,a),null==n||n.emit(ep.TranscriptionReceived,a,r),this.emit(eh.TranscriptionReceived,a,n,r)},this.handleChatMessage=(e,t)=>{let i=function(e){let{id:t,timestamp:i,message:n,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}(t);this.emit(eh.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(eh.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(eh.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(eh.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(eh.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit
2(eh.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>rP(this,void 0,void 0,function*(){var e;(null==(e=aE())?void 0:e.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(eh.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(eh.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(eh.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(eh.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(eh.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(eh.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(eh.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(eh.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null==(t=null==e?void 0:e.onPublish)||t.call(e,this)},this.onLocalTrackPublished=e=>rP(this,void 0,void 0,function*(){var t,i,n,r,a,s;null==(t=e.track)||t.on(eg.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.on(eg.Restarted,this.onLocalTrackRestarted),null==(a=null==(r=null==(n=e.track)?void 0:n.getProcessor())?void 0:r.onPublish)||a.call(r,this),this.emit(eh.LocalTrackPublished,e,this.localParticipant),sN(e.track)&&(yield e.track.checkForSilence())&&this.emit(eh.LocalAudioSilenceDetected,e);let o=yield null==(s=e.track)?void 0:s.getDeviceId(!1),c=a$(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit(eh.ActiveDeviceChanged,c,o))}),this.onLocalTrackUnpublished=e=>{var t,i;null==(t=e.track)||t.off(eg.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.off(eg.Restarted,this.onLocalTrackRestarted),this.emit(eh.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>rP(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),i=a$(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(eh.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(eh.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(eh.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(eh.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(eh.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},of),e),this.log=rC(null!=(i=this.options.loggerName)?i:ea.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},om),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},og),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},op),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new o$,this.outgoingDataStreamManager=new o3(this.engine,this.log),this.incomingDataTrackManager=new cf({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on("trackPublished",e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(eh.DataTrackPublished,e.track),null==(t=this.remoteParticipants.get(e.track.publisherIdentity))||t.addRemoteDataTrack(e.track))}).on("trackUnpublished",e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit
2(eh.DataTrackUnpublished,e.sid),null==(t=this.remoteParticipants.get(e.publisherIdentity))||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new cw({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on("sfuUnpublishRequest",e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on("trackPublished",e=>{this.emit(eh.LocalDataTrackPublished,e.track)}).on("trackUnpublished",e=>{this.emit(eh.LocalDataTrackUnpublished,e.sid)}).on("packetAvailable",e=>{let{bytes:t}=e;this.engine.sendLossyBytes(t,eA.DATA_TRACK_LOSSY,"wait")}),this.disconnectLock=new eZ,this.localParticipant=new cj("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager,this.outgoingDataTrackManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(null!=(n=this.e2eeManager)?n:null),this.outgoingDataTrackManager.updateE2eeManager(null!=(r=this.e2eeManager)?r:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",sP(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",sP(this.options.audioCaptureDefaults.deviceId)),(null==(a=this.options.audioOutput)?void 0:a.deviceId)&&this.switchActiveDevice("audiooutput",sP(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),sl()){const e=new AbortController;null==(o=null==(s=navigator.mediaDevices)?void 0:s.addEventListener)||o.call(s,"devicechange",this.handleDeviceChange,{signal:e.signal}),cH.cleanupRegistry&&cH.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return rP(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield 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")}finally{t()}})}setupE2EE(){var e,t;let i=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new sW(n,i),this.e2eeManager.on(eT.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(eh.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(eT.EncryptionError,(e,t)=>{let i=t?this.getParticipantByIdentity(t):void 0;this.emit(eh.EncryptionError,e,i)}),null==(e=this.e2eeManager)||e.setup(this),null==(t=this.e2eeManager)||t.setupEngine(this.engine))}get logContext(){var e;return{room:this.name,roomID:null==(e=this.roomInfo)?void 0:e.sid,participant:this.localParticipant.identity,participantID:this.localParticipant.sid}}get isRecording(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.activeRecording)&&t}getSid(){return this.state===ez.Disconnected?aS.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?aS.resolve(this.roomInfo.sid):new aS((e,t)=>{let i=t=>{""!==t.sid&&(this.engine.off(em.RoomUpdate,i),e(t.sid))};this.engine.on(em.RoomUpdate,i),this.once(eh.Disconnected,()=>
2{this.engine.off(em.RoomUpdate,i),t(new aA("Room disconnected before room server id was available"))})})}get name(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.name)?t:""}get metadata(){var e;return null==(e=this.roomInfo)?void 0:e.metadata}get numParticipants(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.numParticipants)?t:0}get numPublishers(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.numPublishers)?t:0}maybeCreateEngine(){(!this.engine||!this.engine.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new oJ(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(em.ParticipantUpdate,this.handleParticipantUpdates).on(em.RoomUpdate,this.handleRoomUpdate).on(em.SpeakersChanged,this.handleSpeakersChanged).on(em.StreamStateChanged,this.handleStreamStateUpdate).on(em.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(em.SubscriptionError,this.handleSubscriptionError).on(em.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(em.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(em.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(em.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(em.DataPacketReceived,this.handleDataPacket).on(em.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ez.SignalReconnecting)&&this.emit(eh.SignalReconnecting)}).on(em.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ez.Connected)&&this.emit(eh.Reconnected)}).on(em.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ez.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(em.Restarting,this.handleRestarting).on(em.Restarted,this.handleRestarted).on(em.SignalRestarted,this.handleSignalRestarted).on(em.Offline,()=>{this.setAndEmitConnectionState(ez.Reconnecting)&&this.emit(eh.Reconnecting)}).on(em.DCBufferStatusChanged,(e,t)=>{this.emit(eh.DCBufferStatusChanged,e,t)}).on(em.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});t?(this.localParticipant.emit(ep.LocalTrackSubscribed,t),this.emitWhenConnected(eh.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)}).on(em.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEac
2h((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(eh.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(em.PublishDataTrackResponse,e=>{e.info?this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==iT.NONE}}):this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."),this.logContext)}).on(em.UnPublishDataTrackResponse,e=>{e.info?this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle):this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."),this.logContext)}).on(em.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let[t,i]=e;return[parseInt(t,10),i.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(em.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(em.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>s1(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return sK.getInstance().getDevices(e,t)}prepareConnection(e,t){return rP(this,void 0,void 0,function*(){if(this.state===ez.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(su(new URL(e))&&t){this.regionUrlProvider=new ok(e,t);let i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ez.Disconnected&&(this.regionUrl=i,yield fetch(sR(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(sR(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return rP(this,void 0,void 0,function*(){let i,n=()=>rP(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new nJ({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new nJ({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new nJ({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new nJ({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>rP(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new nJ({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>rP(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new nJ({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new nJ({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>rP(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new nP({reason:ic.CLIENT_INITIATED,action:nR.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw Error("subscriber-bandwidth requires a number as argument");i=new nJ({scenario:{case:"subscriberBandwidth",value:s_(t)}});break;case"leave-full-reconnect":i=new nJ({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return rP(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];return function*(){var r,a,s,o,c,l;let d=!0,u=!1,h=n?{exact:t}:t;if("audioinput"===e){u=0===i.localParticipant.audioTrackPublications.size;let t=null!=(r=i.getActiveDevice(e))?r:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=h;let n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===a9.Source.Microphone);try{d=(yield Promise.all(n.map(e=>{var t;return null==(t=e.audioTrack)?void 0:t.setDeviceId(h)}
2))).every(e=>!0===e)}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}let a=n.some(e=>{var t,i;return null!=(i=null==(t=e.track)?void 0:t.isMuted)&&i});d&&a&&(u=!0)}else if("videoinput"===e){u=0===i.localParticipant.videoTrackPublications.size;let t=null!=(a=i.getActiveDevice(e))?a:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=h;let n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===a9.Source.Camera);try{d=(yield Promise.all(n.map(e=>{var t;return null==(t=e.videoTrack)?void 0:t.setDeviceId(h)}))).every(e=>!0===e)}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}let r=n.some(e=>{var t,i;return null!=(i=null==(t=e.track)?void 0:t.isMuted)&&i});d&&r&&(u=!0)}else if("audiooutput"===e){if(u=!0,!sn()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!=(s=yield sK.getInstance().normalizeDeviceId("audiooutput",t))?s:""),null!=(l=i.options).audioOutput||(l.audioOutput={});let n=null!=(o=i.getActiveDevice(e))?o:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null==(c=i.audioContext)||c.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return u&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(eh.ActiveDeviceChanged,e,t)),d}()})}setupLocalParticipantEvents(){this.localParticipant.on(ep.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ep.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ep.AttributesChanged,this.onLocalAttributesChanged).on(ep.TrackMuted,this.onLocalTrackMuted).on(ep.TrackUnmuted,this.onLocalTrackUnmuted).on(ep.LocalTrackPublished,this.onLocalTrackPublished).on(ep.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ep.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ep.MediaDevicesError,this.onMediaDevicesError).on(ep.AudioStreamAcquired,this.startAudio).on(ep.ChatMessage,this.onLocalChatMessageSent).on(ep.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):null==t||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){var n;let r,a;if(this.state===ez.Connecting||this.state===ez.Reconnecting){let n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,i),r()},r=()=>{this.off(eh.Reconnected,n),this.off(eh.Connected,n),this.off(eh.Disconnected,r)};this.once(eh.Reconnected,n),this.once(eh.Connected,n),this.once(eh.Disconnected,r);return}if(this.state===ez.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);let s=(a=(n=t.id).split("|")).length>1?[a[0],n.substr(a[0].length+1)]:[n,""],o=s[0],c=s[1],l=e.id;if(c&&c.startsWith("TR")&&(l=c),o===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);let d=Array.from(this.remoteParticipants.values()).find(e=>e.sid===o);if(!d){o.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o),this.logContext);return}if(!l.startsWith("TR")){let e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(o),this.logContext);l=e}l.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(o,", streamId: ").concat(c,", trackId: ").concat(l),Object.assign(Object.assign({},this.logContext),{remoteParticipantID:o,streamId:c,trackId:l})),this.options.adaptiveStream&&(r="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});let u=d.addSubscribedMediaTrack(e,l,t,i,r);
2(null==u?void 0:u.isEncrypted)&&!this.e2eeManager&&this.emit(eh.EncryptionError,Error("Encrypted ".concat(u.source," track received from participant ").concat(d.sid,", but room does not have encryption enabled!")))}handleDisconnect(){var e,t;let i=!(arguments.length>0)||void 0===arguments[0]||arguments[0],n=arguments.length>1?arguments[1]:void 0;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==ez.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(e=>{var t,n,r;e.track&&this.localParticipant.unpublishTrack(e.track,i),i?(null==(t=e.track)||t.detach(),null==(n=e.track)||n.stop()):null==(r=e.track)||r.stopMonitor()}),this.localParticipant.off(ep.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ep.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ep.AttributesChanged,this.onLocalAttributesChanged).off(ep.TrackMuted,this.onLocalTrackMuted).off(ep.TrackUnmuted,this.onLocalTrackUnmuted).off(ep.LocalTrackPublished,this.onLocalTrackPublished).off(ep.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ep.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ep.MediaDevicesError,this.onMediaDevicesError).off(ep.AudioStreamAcquired,this.startAudio).off(ep.ChatMessage,this.onLocalChatMessageSent).off(ep.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),sl()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null==(t=null==(e=navigator.mediaDevices)?void 0:e.removeEventListener)||t.call(e,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ez.Disconnected),this.emit(eh.Disconnected,n)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(eh.ParticipantDisconnected,t),t.setDisconnected(),null==(i=this.localParticipant)||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,n,r,a){return rP(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==a)return void(yield this.engine.publishRpcResponse(e,t,null,oy.builtIn("UNSUPPORTED_VERSION")));let s=this.rpcHandlers.get(i);if(!s)return void(yield this.engine.publishRpcResponse(e,t,null,oy.builtIn("UNSUPPORTED_METHOD")));let o=null,c=null;try{let a=yield s({requestId:t,callerIdentity:e,payload:n,responseTimeout:r});oT(a)>15360?(o=oy.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=a}catch(e){e instanceof oy?o=e:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),o=oy.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,o)})}selectDefaultDevices(){return rP(this,void 0,void 0,function*(){var e,t,i;let n=sK.getInstance().previousDevices,r=yield sK.getInstance().getDevices(void 0,!1),a=aE();if((null==a?void 0:a.name)==="Chrome"&&"iOS"!==a.os)for(let e of r){let t=n.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(eh.ActiveDeviceChanged,e.kind,e.deviceId)}for(let a of["audiooutput","audioinput","videoinput"]){let s="audioinput"===a?a9.Source.Microphone:"videoinput"===a?a9.Source.Camera:a9.Source.Unknown,o=this.localParticipant.getTrackPublication(s);if(o&&(null==(e=o.track)?void 0:e.isUserProvided))continue;let c=r.filter(e=>e.kind===a),l=this.getActiveDevice(a);if(l===(null==(t=n.filter(e=>e.kind===a)[0])?void 0:t.deviceId)&&c.length>0&&(null==(i=c[0])?void 0:i.deviceId)!==l){yield this.switchActiveDevice(a,c[0].deviceId);continue}("audioinput"!==a||so())&&"videoinput"!==a&&(!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(a))||"audiooutput"===a&&so()||(yield this.switchActiveDevice(a,c[0].deviceId)))}})}acquireAudioContext(){return rP(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!=(e=aZ())?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEac
2h(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),a7(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}let i=(null==(t=this.audioContext)?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(eh.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?cV.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new cV(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null==(i=this.options.audioOutput)?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}let i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(eh.ParticipantConnected,i),i.on(ep.TrackPublished,e=>{this.emitWhenConnected(eh.TrackPublished,e,i)}).on(ep.TrackSubscribed,(e,t)=>{e.kind===a9.Kind.Audio?(e.on(eg.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(eg.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===a9.Kind.Video&&(e.on(eg.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(eg.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(eh.TrackSubscribed,e,t,i)}).on(ep.TrackUnpublished,e=>{this.emit(eh.TrackUnpublished,e,i)}).on(ep.TrackUnsubscribed,(e,t)=>{this.emit(eh.TrackUnsubscribed,e,t,i)}).on(ep.TrackMuted,e=>{this.emitWhenConnected(eh.TrackMuted,e,i)}).on(ep.TrackUnmuted,e=>{this.emitWhenConnected(eh.TrackUnmuted,e,i)}).on(ep.ParticipantMetadataChanged,e=>{this.emitWhenConnected(eh.ParticipantMetadataChanged,e,i)}).on(ep.ParticipantNameChanged,e=>{this.emitWhenConnected(eh.ParticipantNameChanged,e,i)}).on(ep.AttributesChanged,e=>{this.emitWhenConnected(eh.ParticipantAttributesChanged,e,i)}).on(ep.ConnectionQualityChanged,e=>{this.emitWhenConnected(eh.ConnectionQualityChanged,e,i)}).on(ep.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(eh.ParticipantPermissionsChanged,e,i)}).on(ep.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(eh.TrackSubscriptionStatusChanged,e,t,i)}).on(ep.TrackSubscriptionFailed,(e,t)=>{this.emit(eh.TrackSubscriptionFailed,e,i,t)}).on(ep.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(eh.TrackSubscriptionPermissionChanged,e,t,i)}).on(ep.Active,()=>{this.emitWhenConnected(eh.ParticipantActive,i),i.kind===ik.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),i=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(let t of this.remoteParticipants.values())for(let i of t.videoTrackPublications.values()){var e;i.isSubscribed&&(e=i)&&!e.isLocal&&i.emitTrackUpdate()}}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=aB.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ic.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&aB.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.incomingDataStreamManager.setConnected(e===ez.Connected),this.emit
2(eh.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===ez.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ez.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return rP(this,void 0,void 0,function*(){var t,i,n,r;let a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ip({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:to.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new iv({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(eh.SignalConnected),this.emit(eh.Connected),this.setAndEmitConnectionState(ez.Connected),a.video){let e=new cx(a9.Kind.Video,new iC({source:ir.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:ii.AUDIO,name:"video-dummy"}),new oB(a.useRealTracks&&(null==(t=window.navigator.mediaDevices)?void 0:t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:sC(160*(null!=(i=s.aspectRatios[0])?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(ep.LocalTrackPublished,e)}if(a.audio){let e=new cx(a9.Kind.Audio,new iC({source:ir.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:ii.AUDIO}),new oI(a.useRealTracks&&(null==(n=navigator.mediaDevices)?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:sE(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(ep.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new iv({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:ib.ACTIVE,tracks:[],joinedAt:to.parse(Date.now())}),i=this.getOrCreateParticipant(t.identity,t);if(s.video){let n=sC(160*(null!=(r=s.aspectRatios[e%s.aspectRatios.length])?r:1),160,!1,!0),a=new iC({source:ir.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:ii.AUDIO});i.addSubscribedMediaTrack(n,a.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(s.audio){let e=sE(),n=new iC({source:ir.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:ii.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==eh.ActiveSpeakersChanged&&e!==eh.TranscriptionReceived){let t=(function e(t){return t.map(t=>{if(t)return Array.isArray(t)?e(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t})})(i).filter(e=>void 0!==e);(e===eh.TrackSubscribed||e===eh.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}cH.cleanupRegistry="u">typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),($=eK||(eK={}))[$.IDLE=0]="IDLE",$[$.RUNNING=1]="RUNNING",$[$.SKIPPED=2]="SKIPPED",$[$.SUCCESS=3]="SUCCESS",$[$.FAILED=4]="FAILED";class cW extends r_.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=eK.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new cH(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return rP(this,void 0,void 0,function*(){if(this.status!==eK.IDLE)throw Error("check is running already");this.setStatus(eK.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise(e=>setTimeout(e,500)),this.status!==eK.SKIPPED&&this.setStatus(this.isSuccess()?eK.SUCCESS:eK.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>"error"===e.level)}connect(e){return rP(this,void 0,void 0,function*(){return this.room.state===ez.Connected||(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions)),this.room})}disconnect(){return rP(this,void 0,void 0,function*(){this.room&&this.room.state!==ez.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(eK.SKIPPED)}switchProtocol(e){return rP(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(eh.Reconnecting,()=>{t=!0}),this.room.once(eh.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(e=>setTimeout(e,1e3)),!t)return;let n=Date.now()+1e4;for(;Date.now()<n;){if(i)return;yield a7(100)}throw Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}
2),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 null==(e=this.room)?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function cG(e,t,i){var n;return(t="symbol"==typeof(n=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"))?n:n+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}r_.EventEmitter,new TextEncoder,new TextDecoder;class cz extends Error{constructor(e,t){var i;super(e,t),cG(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null==(i=Error.captureStackTrace)||i.call(Error,this,this.constructor)}}cG(cz,"code","ERR_JOSE_GENERIC"),cG(class extends cz{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),cG(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),cG(this,"claim",void 0),cG(this,"reason",void 0),cG(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),cG(class extends cz{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),cG(this,"code","ERR_JWT_EXPIRED"),cG(this,"claim",void 0),cG(this,"reason",void 0),cG(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_EXPIRED"),cG(class extends cz{constructor(){super(...arguments),cG(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED"),cG(class extends cz{constructor(){super(...arguments),cG(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED"),cG(class extends cz{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),cG(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),cG(class extends cz{constructor(){super(...arguments),cG(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID"),cG(class extends cz{constructor(){super(...arguments),cG(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID"),cG(class extends cz{constructor(){super(...arguments),cG(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID"),cG(class extends cz{constructor(){super(...arguments),cG(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID"),cG(class extends cz{constructor(){super(...arguments),cG(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID"),cG(class extends cz{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),cG(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY"),cG(class extends cz{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),cG(this,Symbol.asyncIterator,void 0),cG(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS"),cG(class extends cz{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),cG(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT"),cG(class extends cz{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;
2super(e,t),cG(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");Symbol.for("lk.serializer");e.s(["ConnectionState",0,ez,"ParticipantEvent",0,ep,"Room",0,cH,"RoomEvent",0,eh,"Track",0,a9,"createLocalAudioTrack",0,cL,"createLocalVideoTrack",0,cN])}]);
3
4//# debugId=a78c52f5-23bf-a9a9-052f-b052728ef4fe

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.