PageSourceSearch

https://member.dr-awe.de/app/_next/static/chunks/e3ef6e5f.10ff35039bb69d25.js

js dr-awe.de collected 2026-10-08 01:21:52 UTC 512,826 bytes, 2 lines download raw bytes

1!function(){try{var e="u">typeof window?window:"u">typeof global?global:"u">typeof globalThis?globalThis:"u">typeof self?self:{};e._sentryModuleMetadata=e._sentryModuleMetadata||{},e._sentryModuleMetadata[(new e.Error).stack]=function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];if(null!=i)for(var n in i)i.hasOwnProperty(n)&&(e[n]=i[n])}return e}({},e._sentryModuleMetadata[(new e.Error).stack],{"_sentryBundlerPluginAppKey:mentortools-frontend":!0});var t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad2b8b8a-02be-41f3-9777-ffdda4f72f62",e._sentryDebugIdIdentifier="sentry-dbid-ad2b8b8a-02be-41f3-9777-ffdda4f72f62")}catch(e){}}();"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2456],{26042:(e,t,i)=>{let n,r,a,s,o;i.d(t,{CC:()=>sb,EQ:()=>lE,KN:()=>eY,M0:()=>cf,Wv:()=>lN,YI:()=>ef,Zy:()=>sj,l6:()=>em,tZ:()=>rV,u6:()=>lO,u9:()=>eg});var c,l,d,u,h,p,m,g,f,v,k,b,y,T,S,C,E,w,R,P,I,_,M,D,O,A,N,L,x,U,F,B,j,q,V,H,W,z,G,K,J,Q,Y,X,Z,$,ee,et,ei,en,er,ea,es,eo,ec,el,ed,eu,eh,ep,em,eg,ef,ev,ek,eb,ey,eT,eS,eC,eE,ew,eR,eP,eI,e_,eM,eD,eO,eA,eN,eL,ex,eU,eF,eB,ej,eq,eV,eH,eW,ez,eG,eK,eJ,eQ,eY,eX,eZ=i(99742),e$=Object.defineProperty,e0=(e,t,i)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?e$(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i};class e1{constructor(){e0(this,"_locking"),e0(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 e2(e,t){if(!e)throw Error(t)}function e3(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 e4(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 e9(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 e6=Symbol("@bufbuild/protobuf/enum-type");function e5(e,t,i,n){e[e6]=e8(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function e8(e,t,i){let n=Object.create(null),r=Object.create(null),a=[];for(let e of t){let t=e7(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 e7(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class te{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 tt(){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 ti(e,t,i){for(let n=0;n<28;n+=7){let r=e>>>n,a=r>>>
17!=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 tn(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?ts(i,n):ta(i,n)}function tr(e,t){var i={lo:e>>>0,hi:t>>>0};if(e=i.lo,(t=i.hi)<=2097151)return String(0x100000000*t+e);let n=0xffffff&e,r=(e>>>24|t<<8)&0xffffff,a=t>>16&65535,s=n+6777216*r+6710656*a,o=r+8147497*a,c=2*a;return s>=1e7&&(o+=Math.floor(s/1e7),s%=1e7),o>=1e7&&(c+=Math.floor(o/1e7),o%=1e7),c.toString()+to(o)+to(s)}function ta(e,t){return{lo:0|e,hi:0|t}}function ts(e,t){return t=~t,e?e=~e+1:t+=1,ta(e,t)}let to=e=>{let t=String(e);return"0000000".slice(t.length)+t};function tc(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 tl(){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;t|=(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 td=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 eZ||"object"!=typeof eZ.env||"1"!==eZ.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=>e2(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>e2(/^[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),tn(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),tn(e)),dec:(e,t)=>{let i,n,r;return(n=0x80000000&(i=ta(e,t)).hi)&&(i=ts(i.lo,i.hi)),r=tr(i.lo,i.hi),n?"-"+r:r},uDec:(e,t)=>tr(e,t)}}();function tu(e,t,i){if(t===i)return!0;if(e==en.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 en.UINT64:case en.FIXED64:case en.INT64:case en.SFIXED64:case en.SINT64:return t==i}return!1}function th(e,t){switch(e){case en.BOOL:return!1;case en.UINT64:case en.FIXED64:case en.INT64:case en.SFIXED64:case en.SINT64:return 0==t?td.zero:"0";case en.DOUBLE:case en.FLOAT:return 0;case en.BYTES:return new Uint8Array(0);case en.STRING:return"";default:return 0}}function tp(e,t){switch(e){case en.BOOL:return!1===t;case en.STRING:return""===t;case en.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function tm(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i<t;i++)n[i]=e[i];return n}function tg(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}function tf(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var n,r,a,s,o=[],c=!0,l=!1;try{if(a=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;c=!1}else for(;!(c=(n=a.call(i)).done)&&(o.push(n.value),o.length!==t);c=!0);}catch(e){l=!0,r=e}
1finally{try{if(!c&&null!=i.return&&(s=i.return(),Object(s)!==s))return}finally{if(l)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return tm(e,t);var i=({}).toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?tm(e,t):void 0}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(c=en||(en={}))[c.DOUBLE=1]="DOUBLE",c[c.FLOAT=2]="FLOAT",c[c.INT64=3]="INT64",c[c.UINT64=4]="UINT64",c[c.INT32=5]="INT32",c[c.FIXED64=6]="FIXED64",c[c.FIXED32=7]="FIXED32",c[c.BOOL=8]="BOOL",c[c.STRING=9]="STRING",c[c.BYTES=12]="BYTES",c[c.UINT32=13]="UINT32",c[c.SFIXED32=15]="SFIXED32",c[c.SFIXED64=16]="SFIXED64",c[c.SINT32=17]="SINT32",c[c.SINT64=18]="SINT64",(l=er||(er={}))[l.BIGINT=0]="BIGINT",l[l.STRING=1]="STRING",(d=ea||(ea={}))[d.Varint=0]="Varint",d[d.Bit64=1]="Bit64",d[d.LengthDelimited=2]="LengthDelimited",d[d.StartGroup=3]="StartGroup",d[d.EndGroup=4]="EndGroup",d[d.Bit32=5]="Bit32";class tv{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(e4(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return e3(e),tc(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){e9(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){e4(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){e3(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return e3(e),tc(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=td.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=td.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=td.enc(e);return ti(t.lo,t.hi,this.buf),this}sint64(e){let t=td.enc(e),i=t.hi>>31;return ti(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=td.uEnc(e);return ti(t.lo,t.hi,this.buf),this}}class tk{constructor(e,t){this.varint64=tt,this.uint32=tl,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ea.Varint:for(;128&this.buf[this.pos++];);break;case ea.Bit64:this.pos+=4;case ea.Bit32:this.pos+=4;break;case ea.LengthDelimited:let n=this.uint32();this.pos+=n;break;case ea.StartGroup:for(;;){let e=tf(this.tag(),2),i=e[0],n=e[1];if(n===ea.EndGroup){if(void 0!==t&&i!==t)throw Error("invalid end group tag");break}this.skip(n,i)}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 td.dec(...this.varint64())}uint64(){return td.uDec(...this.varint64())}sint64(){let e=tf(this.varint64(),2),t=e[0],i=e[1],n=-(1&t);return t=(t>>>
11|(1&i)<<31)^n,i=i>>>1^n,td.dec(t,i)}bool(){let e=tf(this.varint64(),2),t=e[0],i=e[1];return 0!==t||0!==i}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return td.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return td.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 tb(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 th(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 ty="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),tT=[];for(let e=0;e<ty.length;e++)tT[ty[e].charCodeAt(0)]=e;tT[45]=ty.indexOf("+"),tT[95]=ty.indexOf("/");let tS={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=tT[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+=ty[n>>2],r=(3&n)<<4,i=1;break;case 1:t+=ty[r|n>>4],r=(15&n)<<2,i=2;break;case 2:t+=ty[r|n>>6],t+=ty[63&n],i=0}return i&&(t+=ty[r],t+="=",1==i&&(t+="=")),t}};function tC(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 tE(e,t){e2(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function tw(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!tp(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function tR(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?th(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function tP(e,t){if(null===e||"object"!=typeof e||!Object.getOwnPropertyNames(te.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 tI(e,t){return tP(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}en.DOUBLE,en.FLOAT,en.INT64,en.UINT64,en.INT32,en.UINT32,en.BOOL,en.STRING,en.BYTES;let t_={ignoreUnknownFields:!1},tM={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},tD=Symbol(),tO=Symbol();function tA(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 tN(e,t,i,n,r){let a=i.localName;if(i.repeated){if(e2("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tA(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(tA(e)));switch(i.kind){case"message":s.push(i.T.fromJson(e,n));break;case"enum":let t=tx(i.T,e,n.ignoreUnknownFields,!0);t!==tO&&s.push(t);break;case"scalar":try{s.push(tL(i.T,e,i.L,!0))}catch(n){let t="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tA(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(tA(t)));let o=e[a];for(let e of Object.entries(t)){let a;var s=tf(e,2);let c=s[0],l=s[1];if(null===l)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: map value null"));try{a=function(e,t){if(e===en.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return tL(e,t,er.BIGINT,!0).toString()}(i.K,c)}catch(n){let e="cannot decode map key for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tA(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}switch(i.V.kind){case"message":o[a]=i.V.T.fromJson(l,n);break;case"enum":let d=tx(i.V.T,l,n.ignoreUnknownFields,!0);d!==tO&&(o[a]=d);break;case"scalar":try{o[a]=tL(i.V.T,l,er.BIGINT,!0)}catch(n){let e="cannot decode map value for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tA(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 o=i.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let c=e[a];tP(c)?c.fromJson(t,n):(e[a]=c=o.fromJson(t,n),o.fieldWrapper&&!i.oneof&&(e[a]=o.fieldWrapper.unwrapField(c)));break;case"enum":let l=tx(i.T,t,n.ignoreUnknownFields,!1);switch(l){case tD:tR(i,e);break;case tO:break;default:e[a]=l}break;case"scalar":try{let n=tL(i.T,t,i.L,!1);n===tD?tR(i,e):e[a]=n}catch(n){let e="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tA(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}function tL(e,t,i,n){if(null===t)return n?th(e,i):tD;switch(e){case en.DOUBLE:case en.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==en.FLOAT&&e9(r),r;case en.INT32:case en.FIXED32:case en.SFIXED32:case en.SINT32:case en.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==en.UINT32||e==en.FIXED32?e4(a):e3(a),a;case en.INT64:case en.SFIXED64:case en.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;let s=td.parse(t);return i?s.toString():s;case en.FIXED64:case en.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;let o=td.uParse(t);return i?o.toString():o;case en.BOOL:if("boolean"!=typeof t)break;return t;case en.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw Error("invalid UTF8")}return t;case en.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return tS.dec(t)}throw Error()}function tx(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:tD;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 tO}throw Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(tA(t)))}function tU(e,t,i){if("map"==e.kind){e2("object"==typeof t&&null!=t);let s={},o=Object.entries(t);switch(e.V.kind){case"scalar":for(let t of o){var n=tf(t,2);let i=n[0],r=n[1];s[i.toString()]=tB(e.V.T,r)}break;case"message":for(let e of o){var r=tf(e,2);let t=r[0],n=r[1];s[t.toString()]=n.toJson(i)}break;case"enum":let c=e.V.T;for(let e of o){var a=tf(e,2);let t=a[0],n=a[1];s[t.toString()]=tF(c,n,i.enumAsInteger)}}return i.emitDefaultValues||o.length>0?s:void 0}if(e.repeated){e2(Array.isArray(t));let n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(tB(e.T,t[i]));break;case"enum":for(let r=0;r<t.length;r++)n.push(tF(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 tB(e.T,t);case"enum":return tF(e.T,t,i.enumAsInteger);case"message":return tI(e.T,t).toJson(i)}}function tF(e,t,i){var n;if(e2("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 tB(e,t){switch(e){case en.INT32:case en.SFIXED32:case en.SINT32:case en.FIXED32:case en.UINT32:return e2("number"==typeof t),t;case en.FLOAT:case en.DOUBLE:if(e2("number"==typeof t),Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";return t;case en.STRING:return e2("string"==typeof t),t;case en.BOOL:return e2("boolean"==typeof t),t;case en.UINT64:case en.FIXED64:case en.INT64:case en.SFIXED64:case en.SINT64:return e2("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case en.BYTES:return e2(t instanceof Uint8Array),tS.enc(t)}}let tj=Symbol("@bufbuild/protobuf/unknown-fields"),tq={readUnknownFields:!0,readerFactory:e=>new tk(e)},tV={writeUnknownFields:!0,writerFactory:()=>new tv};function tH(e,t,i,n,r){let a=i.repeated,s=i.localName;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?en.INT32:i.T,c=tG;if("scalar"==i.kind&&i.L>0&&(c=tz),a){let i=e[s];if(n==ea.LengthDelimited&&o!=en.STRING&&o!=en.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;a?e[s].push(tW(t,new l,r,i)):tP(e[s])?tW(t,e[s],r,i):(e[s]=tW(t,new l,r,i),!l.fieldWrapper||i.oneof||i.repeated||(e[
1s]=l.fieldWrapper.unwrapField(e[s])));break;case"map":let d=tf(function(e,t,i){let n,r,a=t.uint32(),s=t.pos+a;for(;t.pos<s;)switch(tf(t.tag(),1)[0]){case 1:n=tG(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=tG(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=tW(t,new e.V.T,i,void 0)}}if(void 0===n&&(n=th(e.K,er.BIGINT)),"string"!=typeof n&&"number"!=typeof n&&(n=n.toString()),void 0===r)switch(e.V.kind){case"scalar":r=th(e.V.T,er.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),2),u=d[0],h=d[1];e[s][u]=h}}function tW(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 tz(e,t){let i=tG(e,t);return"bigint"==typeof i?i.toString():i}function tG(e,t){switch(t){case en.STRING:return e.string();case en.BOOL:return e.bool();case en.DOUBLE:return e.double();case en.FLOAT:return e.float();case en.INT32:return e.int32();case en.INT64:return e.int64();case en.UINT64:return e.uint64();case en.FIXED64:return e.fixed64();case en.BYTES:return e.bytes();case en.FIXED32:return e.fixed32();case en.SFIXED32:return e.sfixed32();case en.SFIXED64:return e.sfixed64();case en.SINT64:return e.sint64();case en.UINT32:return e.uint32();case en.SINT32:return e.sint32()}}function tK(e,t,i,n){e2(void 0!==t);let r=e.repeated;switch(e.kind){case"scalar":case"enum":let a="enum"==e.kind?en.INT32:e.T;if(r)if(e2(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,ea.LengthDelimited).fork();let r=tf(tY(t),2)[1];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)tQ(i,a,e.no,n);else tQ(i,a,e.no,t);break;case"message":if(r)for(let r of(e2(Array.isArray(t)),t))tJ(i,n,e,r);else tJ(i,n,e,t);break;case"map":for(let r of(e2("object"==typeof t&&null!=t),Object.entries(t))){var s=tf(r,2);!function(e,t,i,n,r){e.tag(i.no,ea.LengthDelimited),e.fork();let a=n;switch(i.K){case en.INT32:case en.FIXED32:case en.UINT32:case en.SFIXED32:case en.SINT32:a=Number.parseInt(n);break;case en.BOOL:e2("true"==n||"false"==n),a="true"==n}switch(tQ(e,i.K,1,a),i.V.kind){case"scalar":tQ(e,i.V.T,2,r);break;case"enum":tQ(e,en.INT32,2,r);break;case"message":e2(void 0!==r),e.tag(2,ea.LengthDelimited).bytes(r.toBinary(t))}e.join()}(i,n,e,s[0],s[1])}}}function tJ(e,t,i,n){let r=tI(i.T,n);i.delimited?e.tag(i.no,ea.StartGroup).raw(r.toBinary(t)).tag(i.no,ea.EndGroup):e.tag(i.no,ea.LengthDelimited).bytes(r.toBinary(t))}function tQ(e,t,i,n){e2(void 0!==n);let r=tf(tY(t),2),a=r[0],s=r[1];e.tag(i,a)[s](n)}function tY(e){let t=ea.Varint;switch(e){case en.BYTES:case en.STRING:t=ea.LengthDelimited;break;case en.DOUBLE:case en.FIXED64:case en.SFIXED64:t=ea.Bit64;break;case en.FIXED32:case en.SFIXED32:case en.FLOAT:t=ea.Bit32}return[t,en[e].toLowerCase()]}function tX(e){if(void 0===e)return e;if(tP(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 t${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 t0(e,t){let i=t2(e);return t?i:t6(t9(i))}let t1=t2;function t2(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 t3=new Set(["constructor","toString","toJSON","valueOf"]),t4=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),t9=e=>{if(t4.has(e))return"".concat(e,"$");return e},t6=e=>{if(t3.has(e))return"".concat(e,"$");return e};class t5{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 t0(e,!1)}(e)}addField(e){e2(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 t8=(u=e=>new t$(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=t0(l.name,void 0!==l.oneof),l.jsonName=null!=(t=l.jsonName)?t:t1(l.name),l.repeated=null!=(i=l.repeated)&&i,"scalar"==l.kind&&(l.L=null!=(n=l.L)?n:er.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!=en.BYTES&&l.T!=en.STRING),void 0!==l.oneof){let e="string"==typeof l.oneof?l.oneof:l.oneof.name;o&&o.name==e||(o=new t5(e)),l.oneof=o,o.addField(l)}c.push(l)}return c})(e)),h=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]=th(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},t_),e):t_},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},tM),e):tM},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(tA(t)));n=null!=n?n:new e;let r=new Map,a=i.typeRegistry;for(let o of Object.entries(t)){var s=tf(o,2);let t=s[0],c=s[1],l=e.fields.findJsonName(t);if(l){if(l.oneof){if(null===c&&"scalar"==l.kind)continue;let i=r.get(l.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(l.oneof.name,'" present: "').concat(i,'", "').concat(t,'"'));r.set(l.oneof,t)}tN(n,c,l,i,e)}else{let r=!1;if((null==a?void 0:a.findExtension)&&t.startsWith("[")&&t.endsWith("]")){let s=a.findExtension(t.substring(1,t.length-1));if(s&&s.extendee.typeName==e.typeName){r=!0;let e=tf(tb(s),2),t=e[0],a=e[1];tN(t,c,s.field,i,s),function(e,t,i,n){tE(t,e);let r=t.runtime.bin.makeReadOptions(n),a=t.runtime.bin.makeWriteOptions(n);if(tC(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=tf(c.tag(),2),i=t[0],n=t[1],r=c.skip(n,i);e.getType().runtime.bin.onUnknownField(e,i,n,r)}}(n,s,a(),i)}}if(!r&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return n},writeMessage(e,t){let i,n=e.getType(),r={};try{for(i of n.fields.byNumber()){if(!tw(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&&!
1a.req))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],s=tU(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&&tC(e,a)){let i=function(e,t,i){tE(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=tf(tb(t),2),s=a[0],o=a[1];for(let e of r)t.runtime.bin.readField(s,n.readerFactory(e.data),t.field,e.wireType,n);return o()}(e,a,t),n=tU(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)=>tL(e,t,null!=i?i:er.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t&&(i||tp(e,t)))return tB(e,t)},debug:tA},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},tq),e):tq},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},tV),e):tV},listUnknownFields(e){var t;return null!=(t=e[tj])?t:[]},discardUnknownFields(e){delete e[tj]},writeUnknownFields(e,t){let i=e[tj];if(i)for(let e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){Array.isArray(e[tj])||(e[tj]=[]),e[tj].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;){var l=tf(t.tag(),2);
1if(a=l[0],s=l[1],!0===r&&s==ea.EndGroup)break;let i=o.fields.find(a);if(!i){let i=t.skip(s,a);n.readUnknownFields&&this.onUnknownField(e,a,s,i);continue}tH(e,t,i,s,n)}if(r&&(s!=ea.EndGroup||a!==i))throw Error("invalid end group tag")},readField:tH,writeMessage(e,t,i){let n=e.getType();for(let r of n.fields.byNumber()){if(!tw(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];tK(r,a,t,i)}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&tK(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:e5,initPartial(e,t){if(void 0!==e)for(let n of t.getType().fields.byMember()){let r=n.localName;if(null!=e[r])switch(n.kind){case"oneof":let a=e[r].case;if(void 0===a)continue;let s=n.findField(a),o=e[r].value;s&&"message"==s.kind&&!tP(o,s.T)?o=new s.T(o):s&&"scalar"===s.kind&&s.T===en.BYTES&&(o=tZ(o)),t[r]={case:a,value:o};break;case"scalar":case"enum":let c=e[r];n.T===en.BYTES&&(c=n.repeated?c.map(tZ):tZ(c)),t[r]=c;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===en.BYTES)for(let n of Object.entries(e[r])){var i=tf(n,2);let e=i[0],a=i[1];t[r][e]=tZ(a)}else Object.assign(t[r],e[r]);break;case"message":let l=n.V.T;for(let i of Object.keys(e[r])){let n=e[r][i];l.fieldWrapper||(n=new l(n)),t[r][i]=n}}break;case"message":let d=n.T;if(n.repeated)t[r]=e[r].map(e=>tP(e,d)?e:new d(e));else{let i=e[r];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?t[r]=tZ(i):t[r]=i:t[r]=tP(i,d)?i:new d(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)=>tu(e.T,t,r[i]));case"enum":return n.every((e,t)=>tu(en.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||tP(a)||(a=e.T.fieldWrapper.wrapField(a)),void 0===s||tP(s)||(s=e.T.fieldWrapper.wrapField(s))),e.T.equals(a,s);case"enum":return tu(en.INT32,n,r);case"scalar":return tu(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 tu(en.INT32,n.value,r.value);case"scalar":return tu(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=>tu(en.INT32,n[e],r[e]));case"scalar":let d=e.V.T;return c.every(e=>tu(d,n[e],r[e]))}}}),clone(e){let t=e.getType(),i=new t;for(let r of t.fields.byMember()){let t,a=e[r.localName];if(r.repeated)t=a.map(tX);else if("map"==r.kind)for(let e of(t=i[r.localName],Object.entries(a))){var n=tf(e,2);let i=n[0],r=n[1];t[i]=tX(r)}else t="oneof"==r.kind?r.findField(a.case)?{case:a.case,value:tX(a.value)}:{case:void 0}:tX(a);i[r.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:u,initFields:h}),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 te),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)=>new 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=e7(e);n[t.localName]=t.no,n[t.no]=t.localName}return e5(n,e,t),n},makeEnumType:e8,getEnumType:function(e){let t=e[e6];return e2(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 t7 extends te{constructor(e){super(),this.seconds=td.zero,this.nanos=0,t8.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(t8.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: invali
1d 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=td.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 t7.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new t7({seconds:td.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new t7().fromBinary(e,t)}static fromJson(e,t){return new t7().fromJson(e,t)}static fromJsonString(e,t){return new t7().fromJsonString(e,t)}static equals(e,t){return t8.util.equals(t7,e,t)}}t7.runtime=t8,t7.typeName="google.protobuf.Timestamp",t7.fields=t8.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);let ie=t8.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:t7},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:it,repeated:!0},{no:5,name:"events",kind:"message",T:ir,repeated:!0}]),it=t8.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:ii,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ii=t8.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:t7},{no:3,name:"value",kind:"scalar",T:2}]),ir=t8.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:t7},{no:7,name:"normalized_end_timestamp",kind:"message",T:t7,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ia=t8.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),is=t8.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"}]),io=t8.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),ic=t8.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),il=t8.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),id=t8.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"}]),iu=t8.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ih=t8.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ip=t8.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),im=t8.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"}]),ig=t8.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"}]),iv=t8.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ik=t8.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"}]),ib=t8.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),iy=t8.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:iT,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:nt}]),iT=t8.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),iS=t8.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:t8.getEnumType(id),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}]),iC=t8.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:t8.getEnumType(iE)},{no:4,name:"tracks",kind:"message",T:i_,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:iS},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:t8.getEnumType(iw)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:t8.getEnumType(im)},{no:18,name:"kind_details",kind:"enum",T:t8.getEnumType(iR),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:iM,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5}
vendor: 4,246 bytes, line 1
1,{no:21,name:"capabilities",kind:"enum",T:t8.getEnumType(i5),repeated:!0}]),iE=t8.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),iw=t8.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"}]),iR=t8.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"},{no:5,name:"SIMULATION"}]),iP=t8.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),iI=t8.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:iB,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:t8.getEnumType(ij)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),i_=t8.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:t8.getEnumType(il)},{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:t8.getEnumType(id)},{no:10,name:"layers",kind:"message",T:iB,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:iI,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:t8.getEnumType(iP)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:nt},{no:19,name:"audio_features",kind:"enum",T:t8.getEnumType(ik),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:t8.getEnumType(ic)},{no:21,name:"packet_trailer_features",kind:"enum",T:t8.getEnumType(ib),repeated:!0}]),iM=t8.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:t8.getEnumType(iP)},{no:5,name:"frame_encoding",kind:"message",T:iD,opt:!0},{no:6,name:"schema",kind:"message",T:iL,opt:!0}]),iD=t8.makeMessageType("livekit.DataTrackFrameEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:t8.getEnumType(iO),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),iO=t8.makeEnum("livekit.DataTrackFrameEncoding.WellKnownFrameEncoding",[{no:0,name:"WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_FRAME_ENCODING_ROS1",localName:"ROS1"},{no:2,name:"WELL_KNOWN_FRAME_ENCODING_CDR",localName:"CDR"},{no:3,name:"WELL_KNOWN_FRAME_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:4,name:"WELL_KNOWN_FRAME_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:5,name:"WELL_KNOWN_FRAME_ENCODING_CBOR",localName:"CBOR"},{no:6,name:"WELL_KNOWN_FRAME_ENCODING_MSGPACK",localName:"MSGPACK"},{no:7,name:"WELL_KNOWN_FRAME_ENCODING_JSON",localName:"JSON"}]),iA=t8.makeMessageType("livekit.DataTrackSchemaEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:t8.getEnumType(iN),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),iN=t8.makeEnum("livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding",[{no:0,name:"WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:2,name:"WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:3,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG",localName:"ROS1_MSG"},{no:4,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG",localName:"ROS2_MSG"},{no:5,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL",localName:"ROS2_IDL"},{no:6,name:"WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL",localName:"OMG_IDL"},{no:7,name:"WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA",localName:"JSON_SCHEMA"}]),iL=t8.makeMessageType("livekit.DataTrackSchemaId",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:iA}
vendor: 6,748 bytes, line 1
1]),ix=t8.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),iU=t8.makeMessageType("livekit.DataBlobKey",()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:iL,oneof:"key"}]),iF=t8.makeMessageType("livekit.DataBlob",()=>[{no:1,name:"key",kind:"message",T:iU},{no:2,name:"contents",kind:"scalar",T:12}]),iB=t8.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:t8.getEnumType(iu)},{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}]),ij=t8.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"}]),iq=t8.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:t8.getEnumType(iV)},{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:iK,oneof:"value"},{no:3,name:"speaker",kind:"message",T:iz,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:iJ,oneof:"value"},{no:7,name:"transcription",kind:"message",T:iQ,oneof:"value"},{no:8,name:"metrics",kind:"message",T:ie,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:iX,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:iZ,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:i$,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:i0,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ns,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:no,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:nc,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:iH,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),iV=t8.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),iH=t8.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:t8.getEnumType(iP)},{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}]),iW=t8.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:iK,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:iX,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:iZ,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:i$,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:i0,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:ns,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:no,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:nc,oneof:"value"}]),iz=t8.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:iG,repeated:!0}]),iG=t8.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}]),iK=t8.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}]),iJ=t8.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),iQ=t8.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:iY,repeated:!0}]),iY=t8.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}]),iX=t8.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}]),iZ=t8.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}]),i$=t8.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),i0=t8.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:i1,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),i1=t8.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}]),i2=t8.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),i3=t8.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:t8.getEnumType(i4)},{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}]),i4=t8.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),i9=t8.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:t8.getEnumType(i6)},{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}
vendor: 27,987 bytes, line 1
1,{no:13,name:"capabilities",kind:"enum",T:t8.getEnumType(i5),repeated:!0}]),i6=t8.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"}]),i5=t8.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),i8=t8.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:i7},{no:2,name:"screen",kind:"message",T:i7},{no:3,name:"resume_connection",kind:"enum",T:t8.getEnumType(ip)},{no:4,name:"disabled_codecs",kind:"message",T:ne},{no:5,name:"force_relay",kind:"enum",T:t8.getEnumType(ip)}]),i7=t8.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:t8.getEnumType(ip)}]),ne=t8.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:iT,repeated:!0},{no:2,name:"publish",kind:"message",T:iT,repeated:!0}]),nt=t8.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),ni=t8.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),nn=t8.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),nr=t8.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:t8.getEnumType(ni)},{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"}),na=t8.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),ns=t8.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:t8.getEnumType(iP)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:nr,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:na,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:t8.getEnumType(nn)}],{localName:"DataStream_Header"}),no=t8.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"}),nc=t8.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"}),nl=t8.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}]),nd=t8.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:nl}]),nu=t8.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),nh=t8.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),np=t8.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:t8.getEnumType(nh)},{no:4,name:"deployment",kind:"scalar",T:9},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]),nm=t8.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"}]),ng=t8.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),nf=t8.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),nv=t8.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),nk=t8.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),nb=t8.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),ny=t8.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),nT=t8.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:t8.getEnumType(ia)},{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:t8.getEnumType(is)},{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}]),nS=t8.makeMessageType("livekit.StreamOutput",()=>[{no:1,name:"protocol",kind:"enum",T:t8.getEnumType(nf)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}]),nC=t8.makeMessageType("livekit.SegmentedFileOutput",()=>[{no:1,name:"protocol",kind:"enum",T:t8.getEnumType(nv)},{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:t8.getEnumType(nk)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:nw,oneof:"output"},{no:6,name:"gcp",kind:"message",T:nR,oneof:"output"},{no:7,name:"azure",kind:"message",T:nP,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:nI,oneof:"output"}]),nE=t8.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:t8.getEnumType(nb)},{no:6,name:"image_codec",kind:"enum",T:t8.getEnumType(io)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:nw,oneof:"output"},{no:9,name:"gcp",kind:"message",T:nR,oneof:"output"},{no:10,name:"azure",kind:"message",T:nP,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:nI,oneof:"output"}]),nw=t8.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:n_}]),nR=t8.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:n_}]),nP=t8.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}]),nI=t8.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}]),n_=t8.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}]),nM=t8.makeMessageType("livekit.AutoParticipantEgress",()=>[{no:1,name:"preset",kind:"enum",T:t8.getEnumType(nm),oneof:"options"},{no:2,name:"advanced",kind:"message",T:nT,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:nA,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:nC,repeated:!0}]),nD=t8.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:nw,oneof:"output"},{no:3,name:"gcp",kind:"message",T:nR,oneof:"output"},{no:4,name:"azure",kind:"message",T:nP,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:nI,oneof:"output"}]),nO=t8.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:t8.getEnumType(ny)},{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:nA,oneof:"output"},{no:7,name:"stream",kind:"message",T:nS,oneof:"output"},{no:10,name:"segments",kind:"message",T:nC,oneof:"output"},{no:8,name:"preset",kind:"enum",T:t8.getEnumType(nm),oneof:"options"},{no:9,name:"advanced",kind:"message",T:nT,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:nA,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:nS,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:nC,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:nE,repeated:!0},{no:16,name:"webhooks",kind:"message",T:nd,repeated:!0}]),nA=t8.makeMessageType("livekit.EncodedFileOutput",()=>[{no:1,name:"file_type",kind:"enum",T:t8.getEnumType(ng)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:nw,oneof:"output"},{no:4,name:"gcp",kind:"message",T:nR,oneof:"output"},{no:5,name:"azure",kind:"message",T:nP,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:nI,oneof:"output"}]),nN=t8.makeMessageType("livekit.RoomEgress",()=>[{no:1,name:"room",kind:"message",T:nO},{no:3,name:"participant",kind:"message",T:nM},{no:2,name:"tracks",kind:"message",T:nD}]),nL=(()=>[{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:nN},{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:np,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}],t8.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}])),nx=t8.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),nU=t8.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),nF=t8.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:n0,oneof:"message"},{no:2,name:"answer",kind:"message",T:n0,oneof:"message"},{no:3,name:"trickle",kind:"message",T:nJ,oneof:"message"},{no:4,name:"add_track",kind:"message",T:nq,oneof:"message"},{no:5,name:"mute",kind:"message",T:nQ,oneof:"message"},{no:6,name:"subscription",kind:"message",T:n2,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:n7,oneof:"message"},{no:8,name:"leave",kind:"message",T:ri,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:rr,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:rk,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:rT,oneof:"message"},{no:13,name:"simulate",kind:"message",T:rE,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:ra,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:rw,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:re,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:rt,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:nV,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:nW,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:n3,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:n9,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:n5,oneof:"message"}]),nB=t8.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:nY,oneof:"message"},{no:2,name:"answer",kind:"message",T:n0,oneof:"message"},{no:3,name:"offer",kind:"message",T:n0,oneof:"message"},{no:4,name:"trickle",kind:"message",T:nJ,oneof:"message"},{no:5,name:"update",kind:"message",T:n1,oneof:"message"},{no:6,name:"track_published",kind:"message",T:nZ,oneof:"message"},{no:8,name:"leave",kind:"message",T:ri,oneof:"message"},{no:9,name:"mute",kind:"message",T:nQ,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ro,oneof:"message"},{no:11,name:"room_update",kind:"message",T:rc,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:rd,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:rh,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:rg,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:rb,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:n$,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:nX,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:rR,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:r_,oneof:"message"},{no:22,name:"request_response",kind:"message",T:rM,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:rO,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:ry,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:rU,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:rf,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:nH,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:nz,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:nG,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:n6,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:n8,oneof:"message"}]),nj=t8.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:iB,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:t8.getEnumType(ij)}]),nq=t8.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:t8.getEnumType(il)},{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:t8.getEnumType(id)},{no:9,name:"layers",kind:"message",T:iB,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:nj,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:t8.getEnumType(iP)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:t8.getEnumType(ic)},{no:17,name:"audio_features",kind:"enum",T:t8.getEnumType(ik),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:t8.getEnumType(ib),repeated:!0}]),nV=t8.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:t8.getEnumType(iP)},{no:4,name:"frame_encoding",kind:"message",T:iD,opt:!0},{no:5,name:"schema",kind:"message",T:iL,opt:!0}]),nH=t8.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:iM}]),nW=t8.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),nz=t8.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:iM}]),nG=t8.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:nK}}]),nK=t8.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"}),nJ=t8.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:t8.getEnumType(nL)},{no:3,name:"final",kind:"scalar",T:8}]),nQ=t8.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),nY=t8.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:iy},{no:2,name:"participant",kind:"message",T:iC},{no:3,name:"other_participants",kind:"message",T:iC,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:rs,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:i8},{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:i3},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:iT,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),nX=t8.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:rs,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:i8},{no:3,name:"server_info",kind:"message",T:i3},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),nZ=t8.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:i_}]),n$=t8.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),n0=t8.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}}]),n1=t8.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:iC,repeated:!0}]),n2=t8.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:i2,repeated:!0}]),n3=t8.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:n4,repeated:!0}]),n4=t8.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:ix}],{localName:"UpdateDataSubscription_Update"}),n9=t8.makeMessageType("livekit.StoreDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:iF}]),n6=t8.makeMessageType("livekit.StoreDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:iU}]),n5=t8.makeMessageType("livekit.GetDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"key",kind:"message",T:iU}]),n8=t8.makeMessageType("livekit.GetDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:iF}]),n7=t8.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:t8.getEnumType(iu)},{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}]),re=t8.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:t8.getEnumType(ik),repeated:!0}]),rt=t8.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),ri=t8.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:t8.getEnumType(im)},{no:3,name:"action",kind:"enum",T:t8.getEnumType(rn)},{no:4,name:"regions",kind:"message",T:rP}]),rn=t8.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),rr=t8.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:iB,repeated:!0}]),ra=t8.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}]),rs=t8.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}]),ro=t8.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:iG,repeated:!0}]),rc=t8.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:iy}]),rl=t8.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:t8.getEnumType(ih)},{no:3,name:"score",kind:"scalar",T:2}]),rd=t8.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:rl,repeated:!0}]),ru=t8.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:t8.getEnumType(nx)}]),rh=t8.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:ru,repeated:!0}]),rp=t8.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:t8.getEnumType(iu)},{no:2,name:"enabled",kind:"scalar",T:8}]),rm=t8.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:rp,repeated:!0}]),rg=t8.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:rp,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:rm,repeated:!0}]),rf=t8.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:nu,repeated:!0}]),rv=t8.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),rk=t8.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:rv,repeated:!0}]),rb=t8.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}]),ry=t8.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:iy},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:iC},{no:4,name:"other_participants",kind:"message",T:iC,repeated:!0}]),rT=t8.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:n0},{no:2,name:"subscription",kind:"message",T:n2},{no:3,name:"publish_tracks",kind:"message",T:nZ,repeated:!0},{no:4,name:"data_channels",kind:"message",T:rC,repeated:!0},{no:5,name:"offer",kind:"message",T:n0},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:rS,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:nH,repeated:!0}]),rS=t8.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),rC=t8.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:t8.getEnumType(nL)}]),rE=t8.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:t8.getEnumType(nU),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"}]),rw=t8.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),rR=t8.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),rP=t8.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:rI,repeated:!0}]),rI=t8.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}]),r_=t8.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:t8.getEnumType(iv)}]),rM=t8.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:t8.getEnumType(rD)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:nJ,oneof:"request"},{no:5,name:"add_track",kind:"message",T:nq,oneof:"request"},{no:6,name:"mute",kind:"message",T:nQ,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:ra,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:re,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:rt,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:nV,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:nW,oneof:"request"}]),rD=t8.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"}
1,{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),rO=t8.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),rA=t8.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}]),rN=t8.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:i9},{no:2,name:"connection_settings",kind:"message",T:rA},{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:nq,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:n0},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:t8.getEnumType(ig)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:rT}]),rL=t8.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:t8.getEnumType(rx)},{no:2,name:"join_request",kind:"scalar",T:12}]),rx=t8.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),rU=t8.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);var rF={exports:{}},rB=rF.exports,rj=function(){var e;return es?rF.exports:(es=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;throw 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)}
1(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},rF.exports?rF.exports=e():rB.log=e(),rF.exports)}();(p=eo||(eo={}))[p.trace=0]="trace",p[p.debug=1]="debug",p[p.info=2]="info",p[p.warn=3]="warn",p[p.error=4]="error",p[p.silent=5]="silent",(m=ec||(ec={})).Default="livekit",m.Room="livekit-room",m.TokenSource="livekit-token-source",m.Participant="livekit-participant",m.Track="livekit-track",m.Publication="livekit-track-publication",m.Engine="livekit-engine",m.Signal="livekit-signal",m.PCManager="livekit-pc-manager",m.PCTransport="livekit-pc-transport",m.E2EE="lk-e2ee",m.DataTracks="livekit-data-tracks",m.Region="livekit-region",m.ICE="livekit-ice";let rq=rj.getLogger(ec.Default);function rV(e,t){var i,n;let r,a,s=rj.getLogger(e);return(s.setDefaultLevel(rq.getLevel()),t)?(i=s,n=t,r=e=>(t,r)=>{let a=n(),s=a||r?Object.assign(Object.assign({},a),r):void 0;i[e](t,s)},(a=Object.create(i)).trace=r("trace"),a.debug=r("debug"),a.info=r("info"),a.warn=r("warn"),a.error=r("error"),a):s}Object.values(ec).map(e=>rj.getLogger(e)),rq.setDefaultLevel(eo.info);let rH=rj.getLogger(ec.E2EE),rW=[0,300,1200,2700,4800,7e3,7e3,7e3,7e3,7e3];class rz{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()}}function rG(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 rK(e){return this instanceof rK?(this.v=e,this):new rK(e)}function rJ(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 rK?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])}}function rQ(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 rY={exports:{}},rX=function(){if(el)return rY.exports;el=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)}rY.exports=r,rY.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}
1,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):[]},rY.exports}();let rZ=!0,r$=!0;function r0(e,t,i){let n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function r1(e,t,i){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable)return void r4("Unable to polyfill events");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 r2(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(rZ=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function r3(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(r$=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function r4(){"object"==typeof window&&!rZ&&"u">typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}function r9(e,t){r$&&console.warn(e+" is deprecated, please use "+t+" instead.")}function r6(e){return"[object Object]"===Object.prototype.toString.call(e)}function r5(e,t,i){let n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;let a=[];
vendor: 13,557 bytes, line 1
1return 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}let r8=r4;function r7(e,t){if(t.version>=64)return;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),r8("chrome: "+JSON.stringify(e)),r(e)})}e.video=n(e.video)}return r8("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 ae(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function at(e,t){if(!(t.version>102))if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)r1(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 ai(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 an(e,t){if(t.version>=67||!("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=>r5(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}),r1(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>r5(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let i=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 i.apply(this,arguments)}}function ar(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 aa(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ar(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");
1if(!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 as(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 ao(e,t){t.version>102||r1(e,"negotiationneeded",e=>{let i=e.target;if(!(t.version<72)&&(!i.getConfiguration||"plan-b"!==i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var ac=Object.freeze({__proto__:null,fixNegotiationNeeded:ao,shimAddTrackRemoveTrack:aa,shimAddTrackRemoveTrackWithNative:ar,shimGetSendersWithDtmf:ai,shimGetUserMedia:r7,shimMediaStream:ae,shimOnTrack:at,shimPeerConnection:as,shimSenderReceiverGetStats:an});function al(e,t){let i=e&&e.navigator;if(!i.mediaDevices)return;let n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){r9("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 ad(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 au(e,t){"object"==typeof e&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!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]}))}function ah(e,t){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection)||t.version>=151)return;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=Array.prototype.slice.call(arguments),r=e[0],a=e[1],s=e[2];return"closed"===this.signalingState?Promise.resolve(new Map):n.apply(this,[r||null]).then(e=>{if(t.version<53&&!a)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(a,s)}}function ap(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,[]);
vendor: 19,024 bytes, line 1
1return 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 am(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}),r1(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ag(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){r9("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function af(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function av(e,t){if(!("object"==typeof e&&e.RTCPeerConnection)||t.version>=110)return;let i=e.RTCPeerConnection.prototype.addTransceiver;i&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let t=(e=[...e]).length>0;t&&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=i.apply(this,arguments);if(t){let t=n.sender,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 ak(e,t){if(!("object"==typeof e&&e.RTCRtpSender)||t.version>=110)return;let i=e.RTCRtpSender.prototype.getParameters;i&&(e.RTCRtpSender.prototype.getParameters=function(){let e=i.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function ab(e,t){if(!("object"==typeof e&&e.RTCPeerConnection)||t.version>=110)return;let i=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>i.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):i.apply(this,arguments)}}function ay(e,t){if(!("object"==typeof e&&e.RTCPeerConnection)||t.version>=110)return;let i=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>i.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):i.apply(this,arguments)}}var aT=Object.freeze({__proto__:null,shimAddTransceiver:av,shimCreateAnswer:ay,shimCreateOffer:ab,shimGetDisplayMedia:function(e,t){!e.navigator.mediaDevices||e.navigator.mediaDevices&&"getDisplayMedia"in 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:ak,shimGetStats:ah,shimGetUserMedia:al,shimOnTrack:ad,shimPeerConnection:au,shimRTCDataChannel:af,shimReceiverGetStats:am,shimRemoveStream:ag,shimSenderGetStats:ap});function aS(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 aC(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 aE(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 aw(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(aR(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}).bind(t))}function aR(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){return r6(t)?Object.keys(t).reduce(function(i,n){let r=r6(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 aP(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?(r9("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 aI(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 a_(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 aM(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var aD=Object.freeze({__proto__:null,shimAudioContext:aM,shimCallbacksAPI:aE,shimConstraints:aR,shimCreateOfferLegacy:a_,shimGetUserMedia:aw,shimLocalStreamsAPI:aS,shimRTCIceServerUrls:aP,shimRemoteStreamsAPI:aC,shimTrackEventTransceiver:aI}),aO={exports:{}},aA=function(){let e;return ed?aO.exports:(ed=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&&void 0!==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}}}
1,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},aO.exports=e,aO.exports)}(),aN=aA&&aA.__esModule&&Object.prototype.hasOwnProperty.call(aA,"default")?aA.default:aA,aL=(g={__proto__:null,default:aN},[aA].forEach(function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach(function(t){if("default"!==t&&!(t in g)){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(g,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}})}),Object.freeze(g));function ax(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=aN.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,r1(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function aU(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||r1(e,"icecandidate",e=>{if(e.candidate){let t=aN.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function aF(e,t){if(!e.RTCPeerConnection||"chrome"===t.browser&&t.version>102||"firefox"===t.browser&&t.version>=113)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=aN.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=aN.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=aN.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&&"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0}),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 aB(e,t){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype)||"chrome"===t.browser&&t.version>=149||"firefox"===t.browser&&t.version>60)return;function i(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 n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=n.apply(this,arguments);return i(e,this),e},r1(e,"datachannel",e=>(i(e.channel,e.target),e))}function aj(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}
1),["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 aq(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 aV(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 aH(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 aW=Object.freeze({__proto__:null,removeExtmapAllowMixed:aq,shimAddIceCandidateNullOrEmpty:aV,shimConnectionState:aj,shimMaxMessageSize:aF,shimParameterlessSetLocalDescription:aH,shimRTCIceCandidate:ax,shimRTCIceCandidateRelayProtocol:aU,shimSendThrowTypeError:aB});!function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.window,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=r4,r=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 i=e.navigator;if(i.userAgentData&&i.userAgentData.brands){let e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e){let t=parseInt(e.version,10);if(t>=90)return{browser:"chrome",version:t}}}return i.mozGetUserMedia?(t.browser="firefox",t.version=parseInt(r0(i.userAgent,/Firefox\/(\d+)\./,1))):i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(t.browser="chrome",t.version=parseInt(r0(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null):e.RTCPeerConnection&&i.userAgent.match(/AppleWebKit\/(\d+)\./)?(t.browser="safari",t.version=parseInt(r0(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=r0(i.userAgent,/Version\/(\d+(\.?\d+))/,1)):t.browser="Not a supported browser.",t}(t),a={browserDetails:r,commonShim:aW,extractVersion:r0,disableLog:r2,disableWarnings:r3,sdp:aL};switch(r.browser){case"chrome":if(!ac||!as||!i.shimChrome){n("Chrome shim is not included in this adapter release.");break}if(null===r.version){n("Chrome shim can not determine version, not shimming.");break}n("adapter.js shimming chrome."),a.browserShim=ac,aV(t,r),aH(t),r7(t,r),ae(t),as(t,r),at(t,r),aa(t,r),ai(t),an(t,r),ao(t,r),ax(t),aU(t),aj(t),aF(t,r),aB(t,r),aq(t,r);break;case"firefox":if(!aT||!au||!i.shimFirefox){n("Firefox shim is not included in this adapter release.");break}n("adapter.js shimming firefox."),a.browserShim=aT,aV(t,r),aH(t),al(t,r),au(t,r),ah(t,r),ad(t),ag(t),ap(t),am(t),af(t),av(t,r),ak(t,r),ab(t,r),ay(t,r),ax(t),aj(t),aF(t,r),aB(t,r);break;
1case"safari":if(!aD||!i.shimSafari){n("Safari shim is not included in this adapter release.");break}n("adapter.js shimming safari."),a.browserShim=aD,aV(t,r),aH(t),aP(t),a_(t),aE(t),aS(t),aC(t),aI(t),aw(t),aM(t),ax(t),aU(t),aF(t,r),aB(t,r),aq(t,r);break;default:n("Unsupported browser!")}}({window:"u"<typeof window?void 0:window});class az extends(eu=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)}}az.resolve=e=>Reflect.get(eu,"resolve",az).call(az,e);let aG=/version\/(\d+(\.?_?\d+)+)/i;function aK(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(void 0===e&&"u"<typeof navigator)return;let i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===n||t){let e=aJ.find(e=>e.test.test(i));n=null==e?void 0:e.describe(i)}return n}let aJ=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:aQ(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:aY(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:aQ(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:aY(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:aQ(aG,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:aY(e)})}];function aQ(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 aY(e){return e.includes("mac os")?aQ(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class aX 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 aZ extends aX{}(f=eh||(eh={}))[f.NotAllowed=0]="NotAllowed",f[f.ServerUnreachable=1]="ServerUnreachable",f[f.InternalError=2]="InternalError",f[f.Cancelled=3]="Cancelled",f[f.LeaveRequest=4]="LeaveRequest",f[f.Timeout=5]="Timeout",f[f.WebSocket=6]="WebSocket",f[f.ServiceNotFound=7]="ServiceNotFound";class a$ extends aZ{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=eh[t]}static notAllowed(e,t,i){return new a$(e,eh.NotAllowed,t,i)}static timeout(e){return new a$(e,eh.Timeout)}static leaveRequest(e,t){return new a$(e,eh.LeaveRequest,void 0,t)}static internal(e,t){return new a$(e,eh.InternalError,void 0,t)}static cancelled(e){return new a$(e,eh.Cancelled)}static serverUnreachable(e,t){return new a$(e,eh.ServerUnreachable,t)}static websocket(e,t,i){return new a$(e,eh.WebSocket,t,i)}static serviceNotFound(e,t){return new a$(e,eh.ServiceNotFound,void 0,t)}}class a0 extends aX{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class a1 extends aX{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class a2 extends aX{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}}class a3 extends aX{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}}class a4 extends aX{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}}class a9 extends aX{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}}class a6 extends aX{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class a5 extends aZ{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:rD[t]}}(v=ep||(ep={}))[v.AlreadyOpened=0]="AlreadyOpened",v[v.AbnormalEnd=1]="AbnormalEnd",v[v.DecodeFailed=2]="DecodeFailed",v[v.LengthExceeded=3]="LengthExceeded",v[v.Incomplete=4]="Incomplete",v[v.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",v[v.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",v[v.HeaderTooLarge=9]="HeaderTooLarge",v[v.PayloadTooLarge=10]="PayloadTooLarge";class a8 extends aZ{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ep[t]}}class a7 extends aX{constructor(e){super(18,e),this.name="SignalReconnectError"}}(k=em||(em={})).PermissionDenied="PermissionDenied",k.NotFound="NotFound",k.DeviceInUse="DeviceInUse",k.Other="Other",(b=em||(em={})).getFailure=function(e){if(e&&"name"in e)return"NotFoundError"===e.name||"DevicesNotFoundError"===e.name?b.NotFound:"NotAllowedError"===e.name||"PermissionDeniedError"===e.name?b.PermissionDenied:"NotReadableError"===e.name||"TrackStartError"===e.name?b.DeviceInUse:b.Other};class se{}se.setTimeout=function(){return setTimeout(...arguments)},se.setInterval=function(){return setInterval(...arguments)},se.clearTimeout=function(){return clearTimeout(...arguments)},se.clearInterval=function(){return clearInterval(...arguments)},(y=eg||(eg={})).Connected="connected",y.Reconnecting="reconnecting",y.SignalReconnecting="signalReconnecting",y.Reconnected="reconnected",y.Disconnected="disconnected",y.ConnectionStateChanged="connectionStateChanged",y.Moved="moved",y.MediaDevicesChanged="mediaDevicesChanged",y.ParticipantConnected="participantConnected",y.ParticipantDisconnected="participantDisconnected",y.TrackPublished="trackPublished",y.TrackSubscribed="trackSubscribed",y.TrackSubscriptionFailed="trackSubscriptionFailed",y.TrackUnpublished="trackUnpublished",y.TrackUnsubscribed="trackUnsubscribed",y.TrackMuted="trackMuted",y.TrackUnmuted="trackUnmuted",y.LocalTrackPublished="localTrackPublished",y.LocalTrackUnpublished="localTrackUnpublished",y.LocalAudioSilenceDetected="localAudioSilenceDetected",y.ActiveSpeakersChanged="activeSpeakersChanged",y.ParticipantMetadataChanged="participantMetadataChanged",y.ParticipantNameChanged="participantNameChanged",y.ParticipantAttributesChanged="participantAttributesChanged",y.ParticipantActive="participantActive",y.RoomMetadataChanged="roomMetadataChanged",y.DataReceived="dataReceived",y.SipDTMFReceived="sipDTMFReceived",y.TranscriptionReceived="transcriptionReceived",y.ConnectionQualityChanged="connectionQualityChanged",y.TrackStreamStateChanged="trackStreamStateChanged",y.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",y.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",y.AudioPlaybackStatusChanged="audioPlaybackChanged",y.VideoPlaybackStatusChanged="videoPlaybackChanged",y.MediaDevicesError="mediaDevicesError",
1y.ParticipantPermissionsChanged="participantPermissionsChanged",y.SignalConnected="signalConnected",y.RecordingStatusChanged="recordingStatusChanged",y.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",y.EncryptionError="encryptionError",y.DCBufferStatusChanged="dcBufferStatusChanged",y.ActiveDeviceChanged="activeDeviceChanged",y.ChatMessage="chatMessage",y.LocalTrackSubscribed="localTrackSubscribed",y.MetricsReceived="metricsReceived",y.DataTrackPublished="dataTrackPublished",y.DataTrackUnpublished="dataTrackUnpublished",y.LocalDataTrackPublished="localDataTrackPublished",y.LocalDataTrackUnpublished="localDataTrackUnpublished",(T=ef||(ef={})).TrackPublished="trackPublished",T.TrackSubscribed="trackSubscribed",T.TrackSubscriptionFailed="trackSubscriptionFailed",T.TrackUnpublished="trackUnpublished",T.TrackUnsubscribed="trackUnsubscribed",T.TrackMuted="trackMuted",T.TrackUnmuted="trackUnmuted",T.LocalTrackPublished="localTrackPublished",T.LocalTrackUnpublished="localTrackUnpublished",T.LocalTrackCpuConstrained="localTrackCpuConstrained",T.LocalSenderCreated="localSenderCreated",T.ParticipantMetadataChanged="participantMetadataChanged",T.ParticipantNameChanged="participantNameChanged",T.DataReceived="dataReceived",T.SipDTMFReceived="sipDTMFReceived",T.TranscriptionReceived="transcriptionReceived",T.IsSpeakingChanged="isSpeakingChanged",T.ConnectionQualityChanged="connectionQualityChanged",T.TrackStreamStateChanged="trackStreamStateChanged",T.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",T.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",T.TrackCpuConstrained="trackCpuConstrained",T.MediaDevicesError="mediaDevicesError",T.AudioStreamAcquired="audioStreamAcquired",T.ParticipantPermissionsChanged="participantPermissionsChanged",T.PCTrackAdded="pcTrackAdded",T.AttributesChanged="attributesChanged",T.LocalTrackSubscribed="localTrackSubscribed",T.ChatMessage="chatMessage",T.Active="active",(S=ev||(ev={})).TransportsCreated="transportsCreated",S.Connected="connected",S.Disconnected="disconnected",S.Resuming="resuming",S.Resumed="resumed",S.Restarting="restarting",S.Restarted="restarted",S.SignalResumed="signalResumed",S.SignalRestarted="signalRestarted",S.Closing="closing",S.MediaTrackAdded="mediaTrackAdded",S.ActiveSpeakersUpdate="activeSpeakersUpdate",S.DataPacketReceived="dataPacketReceived",S.RTPVideoMapUpdate="rtpVideoMapUpdate",S.DCBufferStatusChanged="dcBufferStatusChanged",S.ParticipantUpdate="participantUpdate",S.RoomUpdate="roomUpdate",S.SpeakersChanged="speakersChanged",S.StreamStateChanged="streamStateChanged",S.ConnectionQualityUpdate="connectionQualityUpdate",S.SubscriptionError="subscriptionError",S.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",S.RemoteMute="remoteMute",S.SubscribedQualityUpdate="subscribedQualityUpdate",S.LocalTrackUnpublished="localTrackUnpublished",S.LocalTrackSubscribed="localTrackSubscribed",S.Offline="offline",S.SignalRequestResponse="signalRequestResponse",S.SignalConnected="signalConnected",S.RoomMoved="roomMoved",S.PublishDataTrackResponse="publishDataTrackResponse",S.UnPublishDataTrackResponse="unPublishDataTrackResponse",S.DataTrackSubscriberHandles="dataTrackSubscriberHandles",S.DataTrackPacketReceived="dataTrackPacketReceived",S.Joined="joined",S.TokenRefreshed="tokenRefreshed",S.ServerRegionsReported="serverRegionsReported",(C=ek||(ek={})).Message="message",C.Muted="muted",C.Unmuted="unmuted",C.Restarted="restarted",C.Ended="ended",C.Subscribed="subscribed",C.Unsubscribed="unsubscribed",C.CpuConstrained="cpuConstrained",C.UpdateSettings="updateSettings",C.UpdateSubscription="updateSubscription",C.AudioPlaybackStarted="audioPlaybackStarted",C.AudioPlaybackFailed="audioPlaybackFailed",C.AudioSilenceDetected="audioSilenceDetected",C.VisibilityChanged="visibilityChanged",C.VideoDimensionsChanged="videoDimensionsChanged",C.VideoPlaybackStarted="videoPlaybackStarted",C.VideoPlaybackFailed="videoPlaybackFailed",C.ElementAttached="elementAttached",C.ElementDetached="elementDetached",C.UpstreamPaused="upstreamPaused",C.UpstreamResumed="upstreamResumed",C.SubscriptionPermissionChanged="subscriptionPermissionChanged",C.SubscriptionStatusChanged="subscriptionStatusChanged",C.SubscriptionFailed="subscriptionFailed",C.TrackProcessorUpdate="trackProcessorUpdate",C.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",C.TranscriptionReceived="transcriptionReceived",C.TimeSyncUpdate="timeSyncUpdate",C.PreConnectBufferFlushed="preConnectBufferFlushed";class st{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 si=["vp8","h264"],sn=["vp8","h264","vp9","av1","h265"];function sr(e){return!!si.find(t=>t===e)}(E=eb||(eb={}))[E.PREFER_REGRESSION=0]="PREFER_REGRESSION",E[E.SIMULCAST=1]="SIMULCAST",E[E.REGRESSION=2]="REGRESSION",(w=ey||(ey={})).telephone={maxBitrate:12e3}
1,w.speech={maxBitrate:24e3},w.music={maxBitrate:48e3},w.musicStereo={maxBitrate:64e3},w.musicHighQuality={maxBitrate:96e3},w.musicHighQualityStereo={maxBitrate:128e3};let sa={h90:new st(160,90,9e4,20),h180:new st(320,180,16e4,20),h216:new st(384,216,18e4,20),h360:new st(640,360,45e4,20),h540:new st(960,540,8e5,25),h720:new st(1280,720,17e5,30),h1080:new st(1920,1080,3e6,30),h1440:new st(2560,1440,5e6,30),h2160:new st(3840,2160,8e6,30)},ss={h120:new st(160,120,7e4,20),h180:new st(240,180,125e3,20),h240:new st(320,240,14e4,20),h360:new st(480,360,33e4,20),h480:new st(640,480,5e5,20),h540:new st(720,540,6e5,25),h720:new st(960,720,13e5,30),h1080:new st(1440,1080,23e5,30),h1440:new st(1920,1440,38e5,30)},so={h360fps3:new st(640,360,2e5,3,"medium"),h360fps15:new st(640,360,4e5,15,"medium"),h720fps5:new st(1280,720,8e5,5,"medium"),h720fps15:new st(1280,720,15e5,15,"medium"),h720fps30:new st(1280,720,2e6,30,"medium"),h1080fps15:new st(1920,1080,25e5,15,"medium"),h1080fps30:new st(1920,1080,5e6,30,"medium"),original:new st(0,0,7e6,30,"medium")};function sc(e,t,i){var n,r;let a=sf(null!=e?e:{}),s=a.optionsWithoutProcessor,o=a.audioProcessor,c=a.videoProcessor,l=null==t?void 0:t.processor,d=null==i?void 0:i.processor,u=null!=s?s:{};return!0===u.audio&&(u.audio={}),!0===u.video&&(u.video={}),u.audio&&(sl(u.audio,t),null!=(n=u.audio).deviceId||(n.deviceId={ideal:"default"}),(o||l)&&(u.audio.processor=null!=o?o:l)),u.video&&(sl(u.video,i),null!=(r=u.video).deviceId||(r.deviceId={ideal:"default"}),(c||d)&&(u.video.processor=null!=c?c:d)),u}function sl(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function sd(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?sl(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 su(e){return rG(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){let i=sh();if(i){let n=i.createAnalyser();n.fftSize=2048;let r=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield sC(t),n.getByteTimeDomainData(r);let a=r.some(e=>128!==e&&0!==e);return i.close(),!a}return!1}()})}function sh(){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=()=>rG(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 sp(e){return e===sb.Source.Microphone?"audioinput":e===sb.Source.Camera?"videoinput":void 0}function sm(e){return e.split("/")[1].toLowerCase()}function sg(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?sg(e.track):{})}}function sf(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 sv(e,t){return e.width*e.height<t.width*t.height}let sk=[];(R=eT||(eT={}))[R.LOW=0]="LOW",R[R.MEDIUM=1]="MEDIUM",R[R.HIGH=2]="HIGH";class sb extends rX.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(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=sb.StreamState.Active,this.isInBackgroun
1d=!1,this._currentBitrate=0,this.log=rq,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.loggerContextCb=n.loggerContextCb,this.log=rV(null!=(i=n.loggerName)?i:ec.Track,()=>this.logContext),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=sb.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),sg(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===sb.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===sb.Kind.Video&&this.addAppVisibilityListener(),!e&&("audio"===t&&(sk.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&sk.splice(sk.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),sy(this.mediaStreamTrack,e);let i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?ek.AudioPlaybackStarted:ek.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?ek.AudioPlaybackFailed:ek.VideoPlaybackFailed,t):"AbortError"===t.name?this.log.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(n?"audio":"video"),{error:t}),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(ek.ElementAttached,e),e}detach(e){try{if(e){sT(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(ek.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{sT(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(ek.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),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.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=rV(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),sk.forEach(e=>{e.parentElement||(t=!1)}),t&&sk.push(e)}}handleAppVisibilityChanged(){return rG(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==sb.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){sA()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){sA()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function sy(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)),sM()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(sM()||sI())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function sT(e,t){if(t.srcObject instanceof MediaStream){let i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}(I=a=(P=sb||(sb={})).Kind||(P.Kind={})).Audio="audio",I.Video="video",I.Unknown="unknown",(_=s=P.Source||(P.Source={})).Camera="camera",_.Microphone="microphone",_.ScreenShare="screen_share",_.ScreenShareAudio="screen_share_audio",_.Unknown="unknown",(M=o=P.StreamState||(P.StreamState={})).Active="active",M.Paused="paused",M.Unknown="unknown",P.kindToProto=function(e){switch(e){case a.Audio:return il.AUDIO;case a.Video:return il.VIDEO;default:return il.DATA}},P.kindFromProto=function(e){switch(e){case il.AUDIO:return a.Audio;case il.VIDEO:return a.Video;default:return a.Unknown}},P.sourceToProto=function(e){switch(e){case s.Camera:return id.CAMERA;case s.Microphone:return id.MICROPHONE;case s.ScreenShare:return id.SCREEN_SHARE;case s.ScreenShareAudio:return id.SCREEN_SHARE_AUDIO;default:return id.UNKNOWN}},P.sourceFromProto=function(e){switch(e){case id.CAMERA:return s.Camera;case id.MICROPHONE:return s.Microphone;case id.SCREEN_SHARE:return s.ScreenShare;case id.SCREEN_SHARE_AUDIO:return s.ScreenShareAudio;default:return s.Unknown}},P.streamStateFromProto=function(e){switch(e){case nx.ACTIVE:return o.Active;case nx.PAUSED:return o.Paused;default:return o.Unknown}};let sS="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function sC(e){return new az(t=>se.setTimeout(t,e))}function sE(){return"addTransceiver"in RTCPeerConnection.prototype}function sw(){return"addTrack"in RTCPeerConnection.prototype}function sR(e){return"av1"===e||"vp9"===e}function sP(e){return!(!document||sD())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function sI(){var e;return(null==(e=aK())?void 0:e.name)==="Firefox"}function s_(){let e;return"u">typeof window&&void 0!==window.RTCRtpScriptTransform&&(!(e=aK())||"Chrome"!==e.name||"iOS"===e.os)}function sM(){var e;return(null==(e=aK())?void 0:e.name)==="Safari"}function sD(){let e=aK();return(null==e?void 0:e.name)==="Safari"||(null==e?void 0:e.os)==="iOS"}function sO(){var e,t;return!!sA()&&(null!=(t=null==(e=navigator.userAgentData)?void 0:e.mobile)?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function sA(){return"u">typeof document}function sN(){return"ReactNative"==navigator.product}function sL(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function sx(e){return sL(e)?e.hostname.split(".")[0]:null}function sU(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function sF(){if(!sN())return;let e=sU();if(e)return e.platform}
1function sB(){if(sA())return window.devicePixelRatio;if(sN()){let e=sU();if(e)return e.devicePixelRatio}return 1}function sj(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 sq(e){for(let t of e)t.target.handleResize(t)}function sV(e){for(let t of e)t.target.handleVisibilityChanged(t)}let sH=null,sW=()=>(sH||(sH=new ResizeObserver(sq)),sH),sz=null,sG=()=>(sz||(sz=new IntersectionObserver(sV,{root:null,rootMargin:"0px"})),sz);function sK(){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=tf(r.captureStream().getTracks(),1)[0];if(!s)throw Error("Could not get empty media stream video track");return s.enabled=i,s}function sJ(){if(!r){let e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);let n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),!(r=tf(n.stream.getAudioTracks(),1)[0]))throw Error("Could not get empty media stream audio track");r.enabled=!1}return r.clone()}class sQ{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>rG(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 sY(e){return sn.includes(e)}function sX(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 sZ(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function s$(e){switch(e.reason){case eh.LeaveRequest:return e.context;case eh.Cancelled:return im.CLIENT_INITIATED;case eh.NotAllowed:return im.USER_REJECTED;case eh.ServerUnreachable:return im.JOIN_FAILURE;default:return im.UNKNOWN_REASON}}function s0(e){return void 0!==e?Number(e):void 0}function s1(e){return void 0!==e?BigInt(e):void 0}function s2(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function s3(e){return!!e&&e.kind==sb.Kind.Audio}function s4(e){return!!e&&e.kind==sb.Kind.Video}function s9(e){return s2(e)&&s4(e)}function s6(e){return s2(e)&&s3(e)}function s5(e){return!!e&&!e.isLocal}function s8(e){return s5(e)&&s4(e)}function s7(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function oe(){return"u">typeof CompressionStream}function ot(e){return e.endsWith("/")?e:"".concat(e,"/")}function oi(e,t){return e.pathname="".concat(ot(e.pathname)).concat(t),e}function on(e){if("string"==typeof e)return nB.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return nB.fromBinary(new Uint8Array(e));throw Error("could not decode websocket message: ".concat(typeof e))}let or="lk_e2ee";function oa(){return"u">typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}(D=eS||(eS={})).SetKey="setKey",D.RatchetRequest="ratchetRequest",D.KeyRatcheted="keyRatcheted",(eC||(eC={})).KeyRatcheted="keyRatcheted",(O=eE||(eE={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",O.EncryptionError="encryptionError",(ew||(ew={})).Error="cryptorError";function os(e){return!!(null==e?void 0:e.worker)&&(oa()||s_())}function oo(e){return!!((null==e?void 0:e.timestamp)||(null==e?void 0:e.frameId))}function oc(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&&se.clearTimeout(n),n=se.setTimeout(function(){if(n=void 0,l=Date.now(),!s){let t=e.apply(u,i);
1o&&o(t),d.forEach(e=>(0,e.resolve)(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&&se.clearTimeout(n),d.forEach(t=>(0,t.reject)(e)),d=[]},u}function ol(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}rX.EventEmitter,(A=eR||(eR={}))[A.InvalidKey=0]="InvalidKey",A[A.MissingKey=1]="MissingKey",A[A.InternalError=2]="InternalError";class od extends sb{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?ek.Muted:ek.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(ek.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return rG(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&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&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 e=i.timestamp,t=i.rtpTimestamp;
1t&&this.rtpTimestamp!==t&&(this.emit(ek.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class ou extends od{constructor(e,t,i,n,r){super(e,t,sb.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>rG(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=ol(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=oc(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}lookupFrameMetadata(e){var t;let i=e.rtpTimestamp;return null==(t=this.frameMetadataExtractor)?void 0:t.lookupMetadata(i)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===sb.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?sT(this._mediaStreamTrack,t):sy(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 oh(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){if(e)return this.stopObservingElement(e),super.detach(e);let t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null==(e=this.prevStats)?void 0:e.decoderImplementation}getReceiverStats(){return rG(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=>{"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 rG(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 se.setTimeout(()=>{this.updateVisibility()},100);this.lastVisible=s,this.emit(ek.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(ek.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=null==(e=this.adaptiveStreamSettings)?void 0:e.pixelDensity;return"screen"===t?sB():t?t:sB()>2?2:1}}class oh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let i=e.target,n=e.isIntersecting;i===this.element&&(this.isIntersecting=n,this.isPiP=op(this.element),this.visibilityChangedAt=Date.now(),null==(t=this.handleVisibilityChanged)||t.call(this))}
1,this.onEnterPiP=()=>{var e,t;null==(t=null==(e=window.documentPictureInPicture)?void 0:e.window)||t.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var e;this.isPiP=op(this.element),null==(e=this.handleVisibilityChanged)||e.call(this)})})},this.onLeavePiP=()=>{var e;this.isPiP=op(this.element),null==(e=this.handleVisibilityChanged)||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:om(e),this.isPiP=sA()&&op(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=om(this.element),this.isPiP=op(this.element),this.element.handleResize=()=>{var e;null==(e=this.handleResize)||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,sG().observe(this.element),sW().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=sG())||e.unobserve(this.element),null==(t=sW())||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 op(e){var t,i;return document.pictureInPictureElement===e||null!=(t=window.documentPictureInPicture)&&!!t.window&&om(e,null==(i=window.documentPictureInPicture)?void 0:i.window)}function om(e,t){let i=t||window,n=e.offsetTop,r=e.offsetLeft,a=e.offsetWidth,s=e.offsetHeight,o=e.hidden,c=getComputedStyle(e).display;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 og extends rX.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;let n=e.data,r=n.kind,a=n.data;switch(r){case"error":if(rq.error(a.error.message),a.uuid){let e=this.decryptDataRequests.get(a.uuid);if(null==e?void 0:e.reject){e.reject(a.error);break}let t=this.encryptDataRequests.get(a.uuid);if(null==t?void 0:t.reject){t.reject(a.error);break}}this.emit(eE.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===(null==(t=this.room)?void 0:t.localParticipant.identity))this.emit(eE.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){let e=null==(i=this.room)?void 0:i.getParticipantByIdentity(a.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(eE.ParticipantEncryptionStatusChanged,a.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(eS.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":let s=this.decryptDataRequests.get(a.uuid);(null==s?void 0:s.resolve)&&s.resolve(a);break;case"encryptDataResponse":let o=this.encryptDataRequests.get(a.uuid);(null==o?void 0:o.resolve)&&o.resolve(a);break;case"packetTrailerMetadata":this.handleFrameMetadata(a.trackId,a.rtpTimestamp,a.ssrc,a.metadata)}},this.onWorkerError=e=>{rq.error("e2ee worker encountered an error:",{error:e.error}),this.emit(eE.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(!(oa()||"u">typeof window&&void 0!==window.RTCRtpScriptTransform))throw new a0("tried to setup end-to-e
1nd encryption on an unsupported browser");if(rq.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:rH.getLevel()}};this.worker&&(rq.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){rq.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):rq.warn("ignoring server sent trailer as it's empty")}handleFrameMetadata(e,t,i,n){if(this.room){for(let r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let a of r.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof ou&&a.track.frameMetadataExtractor)return void a.track.frameMetadataExtractor.storeMetadata(t,i,n)}}setupEngine(e){e.on(ev.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(eg.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==iP.NONE,t.identity)),e.on(eg.ConnectionStateChanged,t=>
1{t===eY.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==iP.NONE,e.identity)})})}).on(eg.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(eg.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(eg.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(ef.LocalSenderCreated,(e,t)=>rG(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(ef.LocalTrackPublished,e=>{if(!s4(e.track)||!sD())return;let t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:sm(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)}),t.on(eS.SetKey,(e,t)=>this.postKey(e,null==t||t)).on(eS.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return rG(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 sQ;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 sQ;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 n=e.key,r=e.participantIdentity,a=e.keyIndex;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)return;if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");let n="video"===e.kind&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?sm(i.mimeType):void 0,n)}setupE2EESender(e,t){var i,n,r;if(!s2(e)||!t){t||rq.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,s4(e)?null!=(n=null==(i=e.publishOptions)?void 0:i.frameMetadata)?n:null==(r=e.publishOptions)?void 0:r.packetTrailer:void 0)}handleReceiver(e,t,i,n,r){return rG(this,void 0,void 0,function*(){if(this.worker){if(s_())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:t,codec:n,hasPacketTrailer:r});else{if(or in e&&n)return void this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i,hasPacketTrailer:r}});let a=e.writableStream,s=e.readableStream;if(!a||!s){let t=e.createEncodedStreams();e.writableStream=t.writable,a=t.writable,e.readableStream=t.readable,s=t.readable}let o={kind:"decode",data:{readableStream:s,writableStream:a,trackId:t,codec:n,participantIdentity:i,isReuse:or in e,hasPacketTrailer:r}};this.worker.postMessage(o,[s,a])}e[or]=!0}})}handleSender(e,t,i,n){var r;if(!(or in e)&&this.worker){if(!(null==(r=this.room)?void 0:r.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(s_()){rq.info("initialize script transform");let r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:oo(n),packetTrailer:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{rq.info("initialize encoded streams");let r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:oo(n),packetTrailer:n}};
1this.worker.postMessage(a,[r.readable,r.writable])}e[or]=!0}}}class of{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,i){for(0!==this.activeSsrc&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=300;){let e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,i)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class ov{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{let t=e.data;if("metadata"===t.kind){let e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{rq.error("frame metadata worker encountered an error:",{error:e.error})},this.worker=null==e?void 0:e.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),e.on(eg.TrackSubscribed,(e,t,i)=>{"video"===e.kind&&this.setupReceiver(e,t.trackInfo)}).on(eg.TrackUnsubscribed,e=>{this.teardownTrack(e)}).on(eg.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var i,n,r;let a=e.receiver;if(!a)return;if(!((null==t?void 0:t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0)){(null==(i=this.room)?void 0:i.hasE2EESetup)||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!os(this.worker?{worker:this.worker}:void 0)&&!(null==(n=this.room)?void 0:n.hasE2EESetup))return void rq.warn("frame metadata transform not supported; skipping extraction");let s=new of,o=e.mediaStreamID;this.extractors.set(o,s),e.frameMetadataExtractor=s,null!=(r=this.room)&&r.hasE2EESetup||this.setupWorkerReceiver(a,o,!0)}setupPassthroughReceiver(e,t){if(s_()){"transform"in e&&(e.transform=null);return}this.worker&&os({worker:this.worker})&&!this.workerPipelines.has(e)?this.setupWorkerReceiver(e,t,!1):this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let i,n=!(arguments.length>2)||void 0===arguments[2]||arguments[2],r=this.worker;if(!r)return;if(s_()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}let a=this.workerPipelines.get(e);if(a){r.postMessage({kind:"updateTrackId",data:{oldTrackId:a,newTrackId:t,hasPacketTrailer:n}}),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e))return void rq.warn("createEncodedStreams not supported");try{i=e.createEncodedStreams()}catch(e){rq.warn("failed to create encoded streams",{error:e});return}let s={kind:"decode",data:{readableStream:i.readable,writableStream:i.writable,trackId:t,hasPacketTrailer:n}};r.postMessage(s,[i.readable,i.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){let t=e.mediaStreamID,i=this.extractors.get(t);i&&(i.dispose(),this.extractors.delete(t)),e instanceof ou&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(let e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear(),null==(e=this.worker)||e.terminate()}}class ok{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new ok),this._instance}addFailedConnectionAttempt(e){var t;let i=sx(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,sC(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){let t=new URL(e),i=t&&sx(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),i=t&&sx(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}ok._instance=null;let ob="default";class oy{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new oy),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return rG(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=oy.userMediaPromiseMap)?void 0:n.size)>0){rq.debug("awaiting getUserMedia promise");try{e?yield oy.userMediaPromiseMap.get(e):yield Promise.all(oy.userMediaPromiseMap.values())}catch(e){rq.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(i&&!(sM()&&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
1h(e=>{e.stop()})}return t._previousDevices=r,e&&(r=r.filter(t=>t.kind===e)),r}()})}normalizeDeviceId(e,t,i){return rG(this,void 0,void 0,function*(){if(t!==ob)return t;let n=yield this.getDevices(e),r=n.find(e=>e.deviceId===ob);if(!r)return void rq.warn("could not reliably determine default device");let a=n.find(e=>e.deviceId!==ob&&e.groupId===(null!=i?i:r.groupId));return a?null==a?void 0:a.deviceId:void rq.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?oy.userMediaPromiseMap.has(e):oy.userMediaPromiseMap.size>0}}oy.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],oy.userMediaPromiseMap=new Map;class oT{static u16(e){return new oT(e,65535)}static u32(e){return new oT(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 oT(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 oT(e,this.maxSize)}isBefore(e){let t=this.value>>>0,i=(e.value>>>0)-t>>>0;return 0!==i&&i<this.maxSize+1}}class oS{static fromRtpTicks(e){return new oS(e,9e4)}static rtpRandom(){let e=Math.round(0xffffffff*Math.random());return oS.fromRtpTicks(e)}constructor(e,t){this.timestamp=oT.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new oS(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class oC{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new oC(t,new Date,e)}static startingAtTime(e,t,i){return new oC(i,e,t)}static rtpStartingNow(e){return oC.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return oC.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=oC.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 oE(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."))}(N=eP||(eP={}))[N.Reserved=0]="Reserved",N[N.TooLarge=1]="TooLarge";class ow extends aZ{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=eP[t]}isReason(e){return this.reason===e}static tooLarge(){return new ow("Value too large to be a valid track handle",eP.TooLarge)}static reserved(e){return new ow("0x".concat(e.toString(16)," is a reserved value."),eP.Reserved)}}let oR={fromNumber(e){if(0===e)throw ow.reserved(e);if(e>65535)throw ow.tooLarge();return e}};class oP{constructor(){this.value=0}get(){return(this.value+=1,this.value>65535)?null:this.value}reset(){this.value=0}}let oI=e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==iP.NONE});(L=eI||(eI={}))[L.WAITING=0]="WAITING",L[L.RUNNING=1]="RUNNING",L[L.COMPLETED=2]="COMPLETED";class o_{constructor(){this.pendingTasks=new Map,this.taskMutex=new e1,this.nextTaskIndex=0}run(e){return rG(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:eI.WAITING};this.pendingTasks.set(t.id,t);let i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=eI.RUNNING,yield e()}finally{t.status=eI.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return rG(this,void 0,void 0,function*(){return this.run(()=>rG(this,void 0,void 0,function*(){}))})}
1snapshot(){return Array.from(this.pendingTasks.values())}}class oM{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 e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.closeCode,i=e.reason;return r.close(t,i)};this.opened=new az((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 i=t.data;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 az((e,t)=>{let i=()=>rG(this,void 0,void 0,function*(){let i=new az(e=>{r.readyState===WebSocket.CLOSED||r.addEventListener("close",t=>{e(t)},{once:!0})}),n=yield az.race([sC(250),i]);n?e(n):t(a$.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=t=>{e({closeCode:t.code,reason:t.reason}),r.removeEventListener("error",i)},r.addEventListener("error",i)}),n.signal&&(n.signal.onabort=()=>r.close()),this.close=a}}let oD=["syncState","trickle","offer","answer","simulate","leave"];(x=e_||(e_={}))[x.CONNECTING=0]="CONNECTING",x[x.CONNECTED=1]="CONNECTED",x[x.RECONNECTING=2]="RECONNECTING",x[x.DISCONNECTING=3]="DISCONNECTING",x[x.DISCONNECTED=4]="DISCONNECTED";class oO{get currentState(){return this.state}get isDisconnected(){return this.state===e_.DISCONNECTING||this.state===e_.DISCONNECTED}get isEstablishingConnection(){return this.state===e_.CONNECTING||this.state===e_.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=e_.DISCONNECTED,this.log=rq,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.loggerContextCb=i.loggerContextCb,this.log=rV(null!=(e=i.loggerName)?e:ec.Signal,()=>this.logContext),this.useJSON=t,this.requestQueue=new o_,this.queuedRequests=[],this.closingLock=new e1,this.connectionLock=new e1,this.state=e_.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 rG(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=e_.CONNECTING,r.options=i,yield r.connect(e,t,i,n,a,s)}()})}reconnect(e,t,i,n){return rG(this,void 0,void 0,function*(){return this.options?(this.state=e_.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")})}connect(e,t,i,n){return rG(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 i9({capabilities:i.clientInfoCapabilities,sdk:i6.JS,protocol:17,clientProtocol:2,version:"2.21.0"}),sN()&&(p.os=null!=(o=sF())?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)}),oi(i,"rtc")}(e,t);return i?n:oi(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",sN()?"reactnative":"js"),h.set("version",l.version),h.set("protocol",l.protocol.toString()),h.set("client_protocol",l.clientProtocol.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 rG(this,void 0,void 0,function*(){let r,a,s=new URLSearchParams;s.set("access_token",e);let o=new rN({clientInfo:t,connectionSettings:new rA({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(oe()){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(c)),t.close();let i=[],n=e.readable.getReader();for(;;){let e=yield n.read(),t=e.done,r=e.value;if(t)break;
1i.push(r)}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=rx.GZIP}else r=c,a=rx.NONE;let l=new rL({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=oi(new URL(sZ(f)),"validate").toString();return new Promise((e,t)=>rG(r,void 0,void 0,function*(){var r,a;try{let s=!1,o=e=>rG(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);if(u.searchParams.has("access_token")&&u.searchParams.set("access_token","<redacted>"),this.ws){let e=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-e,"ms"))}this.log.info("signal connecting to ".concat(u),{reconnect:i.reconnect,reconnectReason:i.reconnectReason}),this.ws=new oM(f);try{let n,s;this.ws.closed.then(e=>{this.isEstablishingConnection&&t(a$.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state}),this.state===e_.CONNECTED&&this.handleOnClose(e.reason||"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(a$.internal("Websocket error during a (re)connection attempt: ".concat(e)))});let o=yield this.ws.opened.catch(e=>rG(this,void 0,void 0,function*(){if(this.state!==e_.CONNECTED){this.state=e_.DISCONNECTED,clearTimeout(l);let i=yield this.handleConnectionError(e,v);t(i);return}this.handleWSError(e),t(e)}));if(clearTimeout(l),!o)return;let c=o.readable.getReader();this.streamWriter=o.writable.getWriter();try{n=yield Promise.race([c.read(),new Promise((e,t)=>{s=setTimeout(()=>{t(a$.timeout("signal connection timed out while waiting for the first message"))},5e3)})])}catch(e){c.releaseLock(),t(e),this.close();return}finally{clearTimeout(s)}if(c.releaseLock(),!n.value)throw a$.internal("no message received as first message");let u=on(n.value),h=this.validateFirstMessage(u,null!=(r=i.reconnect)&&r);if(!h.isValid)return void t(h.error);(null==(a=u.message)?void 0:a.case)==="join"&&(this.pingTimeoutDuration=u.message.value.pingTimeout,this.pingIntervalDuration=u.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(u.message.value));let p=h.shouldProcessFirstMessage?u:void 0;d(o,p),e(h.response)}catch(e){t(e)}finally{c()}}finally{m()}}))}()})}startReadingLoop(e,t){return rG(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield sC(this.signalLatency));let t=yield e.read(),i=t.done,n=t.value;if(i)break;let r=on(n);this.handleSignalResponse(r)}})}close(){return rG(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([e_.DISCONNECTING||e_.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=e_.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,sC(250)])}}catch(t){e.log.debug("websocket error while closing",{error:t})}finally{t&&(e.state=e_.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:oN(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:oN(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new nJ({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new nQ({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return rG(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 ra({requestId:r,metadata:e,name:t,attributes:n}
1)}),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 rr({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new rk({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:td.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new rw({timestamp:td.parse(Date.now()),rtt:td.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new re({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ri({reason:im.CLIENT_INITIATED,action:rn.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new nV({pubHandle:e,name:t,encryption:i?iP.GCM:iP.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new nW({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new n3({updates:[new n4({trackSid:e,subscribe:t})]})})}sendRequest(e){return rG(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=oD.indexOf(e.case)>=0,rq.trace("request allowed to bypass queue:",{canPass:n,req:e}),!n)&&t.state===e_.RECONNECTING)return void t.queuedRequests.push(()=>rG(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield sC(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));let r=new nF({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary().buffer)}catch(e){t.log.error("error sending signal message",{error:e})}}()})}handleSignalResponse(e){var t,i;let n=e.message;if(void 0==n)return void this.log.debug("received unsupported message");let r=!1;if("answer"===n.case){let e=oA(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){let e=oA(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
1(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",{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 rG(this,void 0,void 0,function*(){if(this.state===e_.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){(this.clearPingTimeout(),this.pingTimeoutDuration)?this.pingTimeout=se.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&se.clearTimeout(this.pingTimeout)}startPingInterval(){(this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration)?(this.log.debug("start ping interval"),this.pingInterval=se.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set")}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&se.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=e_.CONNECTED,this.log.info("signal 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===e_.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"),{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 rG(this,void 0,void 0,function*(){try{let i=yield fetch(t);switch(i.status){case 404:let n=yield i.text();if(n.includes("requested room does not exist"))return a$.notAllowed(n,i.status);return a$.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:let r=yield i.text();return a$.notAllowed(r,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 oA(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 oN(e,t){return new n0({sdp:e.sdp,type:e.type,id:t})}class oL{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);return!!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 i of this._map.entries()){var t=tf(i,2);let n=t[0];t[1].expiresAt<e&&this._map.delete(n)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){for(let i of(this.cleanup(),this._map.entries())){var t=tf(i,2);let n=t[0],r=t[1];r.expiresAt>=Date.now()&&e(r.value,n,this.asValueMap())}}map(e){this.cleanup();let t=[],i=this.asValueMap();for(let r of i.entries()){var n=tf(r,2);let a=n[0],s=n[1];t.push(e(s,a,i))}return t}asValueMap(){let e=new Map;for(let i of this._map.entries()){var t=tf(i,2);let n=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(n,r.value)}return e}}var ox={},oU={},oF={exports:{}};function oB(){if(eM)return oF.exports;eM=1;var e=oF.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
1*)(?: (\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","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg: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"}
1,{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")})}),oF.exports}var oj=function(){if(eN)return ox;eN=1;var e=function(){var e,t,i,n,r,a;return eD?oU:(eD=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=oB(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/),oU.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},oU.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},oU.parseFmtpConfig=oU.parseParams,oU.parsePayloads=function(e){return e.toString().split(" ").map(Number)},oU.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},oU.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})})},oU.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}})})},oU)}(),t=function(){if(eA)return eO;eA=1;var e=oB(),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 eO=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var 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].forEac
1h(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 ox.grammar=oB(),ox.write=t,ox.parse=e.parse,ox.parseParams=e.parseParams,ox.parseFmtpConfig=e.parseFmtpConfig,ox.parsePayloads=e.parsePayloads,ox.parseRemoteCandidates=e.parseRemoteCandidates,ox.parseImageAttributes=e.parseImageAttributes,ox.parseSimulcastStreamList=e.parseSimulcastStreamList,ox}();let oq="offerAnswered",oV="rtpVideoPayloadTypes";class oH extends rX.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=rq,this.iceLog=rq,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=oc(e=>rG(this,void 0,void 0,function*(){this.emit("negotiationStarted");try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),20),this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,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.loggerOptions=i,this.log=rV(null!=(t=i.loggerName)?t:ec.PCTransport,()=>this.logContext),this.iceLog=rV(ec.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new e1}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:e.candidate.candidate}),null==(t=this.onIceCandidate)||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;this.iceLog.debug("ICE candidate error",{event:e}),null==(t=this.onIceCandidateError)||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),null==(t=this.onIceConnectionStateChange)||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),null==(t=this.onSignalingStatechange)||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),null==(t=this.onConnectionStateChange)||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;this.log.debug("data channel opened by peer",{label:e.channel.label,id:e.channel.i
1d}),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 rG(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return rG(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",{offerId:t,latestOfferId:this.latestOfferId}),!1;if("offer"===e.type){let t,i,n,s,o=(r=e,t=[],i=[],n=oj.parse(null!=(a=r.sdp)?a:""),s=0,n.media.forEach(e=>{var n;let r=oK(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}),c=o.stereoMids,l=o.nackMids;this.remoteStereoMids=c,this.remoteNackMids=l}else if("answer"===e.type){if(this.pendingInitialOffer&&this._pc){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=oj.parse(null!=(i=e.sdp)?i:"");t.media.forEach(e=>{oG(e)}),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(e,oj.write(t))}let t=oj.parse(null!=(n=e.sdp)?n:"");t.media.forEach(e=>{let t=oK(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})});let r=this.getPlaceholderMids();r.size>0&&oz(t.media,e=>r.has(oK(e.mid))),s=oj.write(t)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,"answer"===e.type&&(this.latestAcknowledgedOfferId=t,this.emit(oq,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit
1("negotiationComplete"),e.sdp&&oj.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(oV,e.rtp)})),!0})}createInitialOffer(){return rG(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");let t=this.latestOfferId+1;this.latestOfferId=t;let i=yield this.pc.createOffer();this.pendingInitialOffer={sdp:i.sdp,type:i.type};let n=oj.parse(null!=(e=i.sdp)?e:"");return n.media.forEach(e=>{oG(e)}),i.sdp=oj.write(n),{offer:i,offerId:t}}finally{t()}})}createAndSendOffer(e){return rG(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.iceLog.debug("restarting ICE"),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");return}}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection");this.log.debug("starting to negotiate");let i=this.latestOfferId+1;this.latestOfferId=i;let n=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:n.sdp});let r=oj.parse(null!=(t=n.sdp)?t:"");r.media.forEach(e=>{oG(e),"audio"===e.type?oW(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i)return!0;sR(t.codec)&&!sM()&&this.ensureVideoDDExtensionForSVC(e,r);let n=Math.round(.9*t.maxbr),a=t.isScreenShare?n:Math.min(n,1e3),s=!1;for(let t of e.fmtp)if(t.payload===i){s=!0,t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(a));break}return s||e.fmtp.push({payload:i,config:"x-google-start-bitrate=".concat(a)}),!0})});let a=this.getPlaceholderMids();if(a.size>0&&oz(r.media,e=>a.has(oK(e.mid))),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:i});yield this.setMungedSDP(n,oj.write(r)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return rG(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),i=oj.parse(null!=(e=t.sdp)?e:"");return i.media.forEach(e=>{oG(e),"audio"===e.type&&oW(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,oj.write(i)),t})}getPlaceholderMids(){var e,t,i=null!=(t=null==(e=this._pc)?void 0:e.getTransceivers())?t:[];let n=new Set;for(let e of i)e.mid&&!e.sender.track&&n.add(e.mid);return n}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 a3("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 a3("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()}getMaxMessageSize(){var e,t;return null==(t=null==(e=this._pc)?void 0:e.sctp)?void 0:t.maxMessageSize}getConnectedAddress(){return rG(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",i=new Map,n=new Map;
1if((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)})}setMungedSDP(e,t,i){return rG(this,void 0,void 0,function*(){var n,r;let a=e.sdp;if(t){e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description")),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"),{error:i,mungedSdp:t,originalSdp:a}),e.sdp=a}}try{i?yield null==(n=this._pc)?void 0:n.setRemoteDescription(e):yield null==(r=this._pc)?void 0:r.setLocalDescription(e)}catch(s){let n="unknown error";s instanceof Error?n=s.message:"string"==typeof s&&(n=s);let r={error:n,sdp:e.sdp};throw t&&t!==a&&(r.mungedSdp=t),!i&&this.pc.remoteDescription&&(r.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:r}),new a4(n)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null==(i=e.ext)?void 0:i.some(e=>e.uri===sS))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;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:sS})}}}function oW(e,t,i){let n=oK(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 oz(e,t){var i,n;let r=new Map,a=new Set;for(let n of e){let e=t(n);for(let t of null!=(i=n.fmtp)?i:[])e?r.has(t.payload)||r.set(t.payload,t.config):(r.set(t.payload,t.config),a.add(t.payload))}if(0!==r.size){for(let i of e)if(t(i))for(let e of null!=(n=i.fmtp)?n:[]){let t=r.get(e.payload);void 0!==t&&e.config!==t&&(e.config=t)}}}function oG(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 oK(e){return"number"==typeof e?e.toFixed(0):e}let oJ={audioPreset:ey.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:so.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!0,preConnectBuffer:!1},oQ={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},oY={deviceId:{ideal:"default"},resolution:sa.h720.resolution},oX={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new rz,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},oZ={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};(U=eL||(eL={}))[U.NEW=0]="NEW",U[U.CONNECTING=1]="CONNECTING",U[U.CONNECTED=2]="CONNECTED",U[U.FAILED=3]="FAILED",U[U.CLOSING=4]="CLOSING",U[U.CLOSED=5]="CLOSED";class o${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=oZ.peerConnectionTimeout,this.log=rq,this.iceLog=rq,this.updateState=()=>{var e,t;let i=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>"connected"===e)?this.state=eL.CONNECTED:n.some(e=>"failed"===e)?this.state=eL.FAILED:n.some(e=>"connecting"===e)?this.state=eL.CONNECTING:n.every(e=>"closed"===e)?this.state=eL.CLOSED:n.some(e=>"closed"===e)?this.state=eL.CLOSING:n.every(e=>"new"===e)&&(this.state=eL.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(eL[i]," to ").concat(eL[this.state])),null==(e=this.onStateChange)||e.call(this,this.state,this.publisher.getConnectionState(),null==(t=this.subscriber)?void 0:t.getConnectionState()))},this.loggerOptions=t,this.log=rV(null!=(n=t.loggerName)?n:ec.PCManager,()=>
1this.logContext),this.iceLog=rV(ec.ICE,()=>this.logContext),this.isPublisherConnectionRequired="subscriber-primary"!==e,this.isSubscriberConnectionRequired="subscriber-primary"===e,this.publisher=new oH(i,t),this._mode=e,"publisher-only"!==e&&(this.subscriber=new oH(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,nL.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,nL.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=eL.NEW,this.connectionLock=new e1,this.remoteOfferLock=new e1}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 rG(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",{error:e})}}yield Promise.all([this.publisher.close(),null==(e=this.subscriber)?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return rG(this,void 0,void 0,function*(){this.iceLog.warn("triggering ICE restart"),this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return rG(this,void 0,void 0,function*(){var i;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===nL.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null==(i=this.subscriber)?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return rG(this,void 0,void 0,function*(){var i,n,r;this.log.debug("received server offer",{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.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),null==(i=this.subscriber)||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return rG(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.publisher.negotiate()),yield Promise.all(null==(i=this.requiredTransports)?void 0:i.map(i=>this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return rG(this,void 0,void 0,function*(){return new az((t,i)=>{let n=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>n){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let r=!1,a=()=>{r||(r=!0,clearTimeout(c),this.publisher.off(oq,s),e.signal.removeEventListener("abort",o))},s=e=>{e>n&&(a(),t())},o=()=>{a(),i(new a4("negotiation aborted"))},c=setTimeout(()=>{a(),i(new a4("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",o),this.publisher.on(oq,s),this.publisher.negotiate(e=>{a(),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}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}
1createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===nL.PUBLISHER||e===nL.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 rG(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)=>rG(i,void 0,void 0,function*(){let i=()=>{this.log.warn("abort transport connection"),se.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=se.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),r(a$.internal("could not establish pc connection"))},n);for(;this.state!==eL.CONNECTED;)if(yield sC(50),null==t?void 0:t.signal.aborted)return void r(a$.cancelled("room connection has been cancelled"));se.clearTimeout(a),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class o0{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new e1,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters("data channel replaced"),this.handle=e}detach(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"data channel torn down";this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return rG(this,void 0,void 0,function*(){let e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}})}waitForHeadroomWithoutLock(){return rG(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new a3("engine closed");let e=this.getChannel();if(!e)throw new a3("DataChannel not found, kind: ".concat(this.kind));if(this.isBelowHighWaterMark(e))return;let t=this.waiterAbortController.signal;yield new az((i,n)=>{let r=()=>{o(),i()},a=()=>{o(),n(new a3("DataChannel ".concat(this.kind," closed while draining the buffer")))},s=()=>{o(),n(new a3("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},o=()=>{e.removeEventListener("bufferedamountlow",r),e.removeEventListener("close",a),t.removeEventListener("abort",s)};t.aborted?s():(e.addEventListener("bufferedamountlow",r),e.addEventListener("close",a),t.addEventListener("abort",s))})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;let t=this.getChannel();if(!t)return;let i=this.isBelowLowWaterMark(t);i!==this.bufferStatusLow&&(this.bufferStatusLow=i,null==(e=this.onBufferStatusChanged)||e.call(this,i))}}class o1 extends o0{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return rG(this,void 0,void 0,function*(){let t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case"drop":if(!this.isBelowLowWaterMark(t)){this.dropCount+=1,this.dropCount%100==0&&rq.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount));return}}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(e){if(e instanceof TypeError)rq.error(e);else throw e}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=se.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;let e=this.getChannel();e&&(e.bufferedAmountLowThreshold=Math.min(Math.max(this.statByterate/10,this.lowWaterMark),this.highWaterMark))},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(se.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}}class o2{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter(e=>!e.sent)}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(let e of this.buffer)e.sent=!1;this._sentSize=0}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(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class o3 extends o0{constructor(e){super(e),this.messageBuffer=new o2,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){let e=this.sequence;return this.sequence+=1,e}send(e,t){return rG(this,void 0,void 0,function*(){if(this.isDeferringSends())return void this.messageBuffer.push({data:e,sequence:t,sent:!1});let i=this.getChannel();if(i){try{yield this.waitForHeadroomWithLock()}catch(i){if(this.isEngineClosed())throw i;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends())return void this.messageBuffer.push({data:e,sequence:t,sent:!1});this.messageBuffer.push({data:e,sequence:t,sent:!0}),i.send(e),this.refreshBufferStatus()}})}replay(e){return rG(this,void 0,void 0,function*(){let t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);let i=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let e=this.messageBuffer.getUnsent();e.length>0;e=this.messageBuffer.getUnsent())for(let i of e)yield this.waitForHeadroomWithoutLock(),t.send(i.data),this.messageBuffer.markSent(i)}finally{i()}this.refreshBufferStatus()})}refreshBufferStatus(){let e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new o2,this.sequence=1}}(F=ex||(ex={}))[F.RELIABLE=0]="RELIABLE",F[F.LOSSY=1]="LOSSY",F[F.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY";let o4="_lossy",o9="_reliable",o6="_data_track";class o5{constructor(e){this.opts=e;const t=t=>({kind:t,lowWaterMark:t===ex.RELIABLE?65536:8192,highWaterMark:t===ex.RELIABLE?1048576:262144,isEngineClosed:e.isEngineClosed,onBufferStatusChanged:i=>e.onBufferStatusChanged(t,i)});this.reliable=new o3(Object.assign(Object.assign({},t(ex.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new o1(Object.assign(Object.assign({},t(ex.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new o1(Object.assign(Object.assign({},t(ex.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case ex.RELIABLE:return this.reliable;case ex.LOSSY:return this.lossy;case ex.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!t)return this.channelFor(e).channelHandle;switch(e){case ex.RELIABLE:return this.reliableSub;case ex.LOSSY:return this.lossySub;case ex.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(let e of[this.lossy,this.reliable,this.dataTrack]){let t=e.channelHandle;t&&(t.onmessage=null,t.onerror=null,t.onclose=null)}let t=(e,t,i)=>{t.onmessage=i,t.onerror=this.opts.onDataError,t.onclose=()=>this.opts.onChannelClose(e.kind),t.bufferedAmountLowThreshold=e.lowWaterMark,t.onbufferedamountlow=()=>e.refreshBufferStatus(),e.attach(t)};
1t(this.lossy,e.createPublisherDataChannel(o4,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(o9,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(o6,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===o9)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===o4)this.lossySub=e,t=this.opts.onDataMessage;else{if(e.label!==o6)return!1;this.dataTrackSub=e,t=this.opts.onDataTrackMessage}return e.onmessage=t,!0}teardown(){let e=e=>{e&&(e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null,e.close())};for(let t of[this.lossy,this.reliable,this.dataTrack]){let i=t.channelHandle;t.detach("peer connections cleaned up"),e(i)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}}let o8="u">typeof MediaRecorder;class o7{constructor(){throw Error("MediaRecorder is not available in this environment")}}let ce=o8?MediaRecorder:o7;class ct extends ce{constructor(e,t){let i,n;if(!o8)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=>rG(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 ci extends sb{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=oc(()=>rG(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>rG(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(ek.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new e1,this.pauseUpstreamLock=new e1,this.trackChangeLock=new e1,this.trackChangeLock.lock().then(t=>rG(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!==sb.Kind.Video)return;let e=this._mediaStreamTrack.getSettings(),t=e.width,i=e.height;if(t&&i)return{width:t,height:i}}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 rG(this,void 0,void 0,function*(){var n;let r;if(e!==this._mediaStreamTrack||t){if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{sT(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&&(sy(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),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.forEac
1h(t=>{sy(null!=r?r:e,t)}))}})}waitForDimensions(){return rG(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===sb.Kind.Audio)throw Error("cannot get dimensions for audio tracks");(null==(i=aK())?void 0:i.os)==="iOS"&&(yield sC(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield sC(50)}throw new a1("unable to get track dimensions after timeout")}()})}setDeviceId(e){return rG(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===sX(e)||((this._constraints.deviceId=e,this.isMuted)?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),sX(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return rG(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){if(e.source===sb.Source.ScreenShare)return;let i=e._mediaStreamTrack.getSettings(),n=i.deviceId,r=i.groupId,a=e.kind===sb.Kind.Audio?"audioinput":"videoinput";return t?oy.getInstance().normalizeDeviceId(a,n,r):n}()})}mute(){return rG(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return rG(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return rG(this,void 0,void 0,function*(){let i=yield this.trackChangeLock.lock();try{let i,n;if(!this.sender)throw new a1("unable to replace an unpublished track");"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())}finally{i()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return rG(this,void 0,void 0,function*(){})}restart(e,t){return rG(this,void 0,void 0,function*(){this.manuallyStopped=!1;let i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let i=e,n=i.deviceId,r=i.facingMode,a=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 s={audio:!1,video:!1};this.kind===sb.Kind.Video?s.video=!n&&!r||{deviceId:n,facingMode:r}:s.audio=!n||Object.assign({deviceId:n},a),this.attachedElements.forEach(e=>{sT(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let o=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===sb.Kind.Video&&(yield o.applyConstraints(a)),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(ek.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?ek.Muted:ek.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 rG(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),sO()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackgroun
1d||!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 rG(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(ek.UpstreamPaused,this);let t=aK();if((null==t?void 0:t.name)==="Safari"&&0>sj(t.version,"12.0"))throw new a0("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 rG(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(ek.UpstreamResumed,this),(null==(e=this.sender.transport)?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return rG(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 rG(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,localTrack:t};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(sy(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&&(sT(t._mediaStreamTrack,e),sy(t.processor.processedTrack,e));yield null==(n=t.sender)?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(ek.TrackProcessorUpdate,t.processor)}finally{r()}yield t.onSenderTrackSwapped()}()})}getProcessor(){return this.processor}stopProcessor(){return rG(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()}yield e.onSenderTrackSwapped()}()})}internalStopProcessor(){return rG(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(ek.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!o8)return void this.log.warn("MediaRecorder is not available, cannot start prec
1onnect 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 ct(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 cn extends ci{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,sb.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>rG(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=ol(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ek.AudioTrackFeatureUpdate,this,ik.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ek.AudioTrackFeatureUpdate,this,ik.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return rG(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===sb.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 rG(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===sb.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 rG(this,void 0,void 0,function*(){let t;if(e){let i=sd({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}applyConstraints(e){return rG(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{let t=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),t}finally{t()}})}restart(e,t){let i=Object.create(null,{restart:{get:()=>super.restart}});return rG(this,void 0,void 0,function*(){let n=yield i.restart.call(this,e,t);return this.checkForSilence(),n})}startMonitor(){!sA()||this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}setProcessor(e){return rG(this,void 0,void 0,function*(){var t;let i=yield this.trackChangeLock.lock();try{if(!sN()&&!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,localTrack:this};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
1(ek.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return rG(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 rG(this,void 0,void 0,function*(){let e=yield su(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(ek.AudioSilenceDetected)),e})}}let cr=Object.values(sa),ca=Object.values(ss),cs=Object.values(so),co=[sa.h180,sa.h360],cc=[ss.h180,ss.h360],cl=["q","h","f"];function cd(e,t,i,n){var r,a,s;let o,c,l=null==n?void 0:n.videoEncoding;e&&(l=null==n?void 0:n.screenShareEncoding);let d=null==n?void 0:n.simulcast,u=null==n?void 0:n.scalabilityMode,h=null==n?void 0:n.videoCodec;if(!l&&!d&&!u||!t||!i)return[{}];l||(l=function(e,t,i,n){let r=function(e,t,i){if(e)return cs;let n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?cr:ca}(e,t,i),a=r[0].encoding,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,h),rq.debug("using video encoding",l));let p=l.maxFramerate,m=new st(t,i,l.maxBitrate,l.maxFramerate,l.priority);if(u&&sR(h)){let e=new cg(u),t=[];if(e.spatial>3)throw Error("unsupported scalabilityMode: ".concat(u));let i=aK();if(sD()||sN()||(null==i?void 0:i.name)==="Chrome"&&0>sj(null==i?void 0:i.version,"113")){let n="h"==e.suffix?2:3,a=((r=i)||(r=aK()),(null==r?void 0:r.name)==="Safari"&&sj(r.version,"18.3")>0||(null==r?void 0:r.os)==="iOS"&&!!(null==r?void 0:r.osVersion)&&sj(r.osVersion,"18.3")>0);for(let i=0;i<e.spatial;i+=1)t.push({rid:cl[2-i],maxBitrate:l.maxBitrate/Math.pow(n,i),maxFramerate:m.encoding.maxFramerate,scaleResolutionDownBy:a?Math.pow(2,i):void 0});t[0].scalabilityMode=u}else t.push({maxBitrate:l.maxBitrate,maxFramerate:m.encoding.maxFramerate,scalabilityMode:u});return m.encoding.priority&&(t[0].priority=m.encoding.priority,t[0].networkPriority=m.encoding.priority),rq.debug("using svc encoding",{encodings:t}),t}if(!d)return[l];if((o=e?null!=(a=cm(null==n?void 0:n.screenShareSimulcastLayers))?a:ch(e,m):null!=(s=cm(null==n?void 0:n.videoSimulcastLayers))?s:ch(e,m)).length>0){let e=o[0];o.length>1&&(c=tf(o,2)[1]);let n=Math.max(t,i);if(n>=960&&c)return cp(t,i,[e,c,m],p);if(n>=480)return cp(t,i,[e,m],p)}return cp(t,i,[m])}function cu(e,t,i){var n,r,a,s;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&rq.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===sb.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),cd(e.source===sb.Source.ScreenShare,c,l,i)}function ch(e,t){if(e)return[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(e=>{var i,n;return new st(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 i=t.width,n=t.height,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?co:cc}function cp(e,t,i,n){let r=[];if(i.forEach((i,a)=>{if(a>=cl.length)return;let s=Math.min(e,t),o={rid:cl[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=aK(),d=(null==l?void 0:l.name)==="Firefox"&&"iOS"!==l.os||0===a;i.encoding.priority&&d&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),r.push(o)}),sN()&&"ios"===sF()){let e;r.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;r.forEach(i=>
1{var n;i.maxFramerate!=e&&(t&&(t=!1,rq.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),rq.info('Setting framerate of encoding "'.concat(null!=(n=i.rid)?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return r}function cm(e){if(e)return e.slice().sort((e,t)=>{let i=e.encoding,n=t.encoding;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 cg{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)?e:"")}}class cf extends ci{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,sb.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>rG(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(ek.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;let r=null==(n=this.prevStats)?void 0:n.get(i);e+=ol(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new e1}get isSimulcast(){return!!this.sender&&!!(this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!sA())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 rG(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var t,i,n,r,a,s,o=!0,c=rQ(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 rG(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var t,i,n,r,a,s,o=!0,c=rQ(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 rG(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!==sb.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 rG(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!==sb.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())
1)t.mediaStreamTrack.enabled=!e}getSenderStats(){return rG(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)=>{var i,n;return(null!=(i=t.frameWidth)?i:0)-(null!=(n=e.frameWidth)?n:0)}),t})}setPublishingQuality(e){let t=[];for(let i=eT.LOW;i<=eT.HIGH;i+=1)t.push(new rp({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(sR(this.codec),t)}restartTrack(e){return rG(this,void 0,void 0,function*(){let t;if(e){let i=sd({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=rQ(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}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return rG(this,void 0,void 0,function*(){yield this.refreshSen
1derEncodings()})}refreshSenderEncodings(){return rG(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;let t=yield this.senderLock.lock();try{let t;try{t=yield this.waitForDimensions()}catch(e){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:e}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;let n=this.source===sb.Source.ScreenShare,r=cd(n,t.width,t.height,Object.assign({},this.publishOptions));for(let n of(yield this.applyEncodingsToSender(this.sender,r),this.encodings=r,this.lastEncodedDimensions=t,this.simulcastCodecs)){var i=tf(n,2);let t=i[0],r=i[1];if(!r.sender||(null==(e=r.sender.transport)?void 0:e.state)==="closed"||!sr(t))continue;let a=Object.assign({},this.publishOptions),s=cu(this,t,a);s&&(yield this.applyEncodingsToSender(r.sender,s),r.encodings=s)}}catch(e){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:e}))}finally{t()}})}applyEncodingsToSender(e,t){return rG(this,void 0,void 0,function*(){let i=e.getParameters();
1i.encodings&&i.encodings.length===t.length&&(i.encodings.forEach((e,i)=>{if(!1===e.active)return;let n=t[i];void 0!==n.scaleResolutionDownBy&&(e.scaleResolutionDownBy=n.scaleResolutionDownBy),void 0!==n.maxBitrate&&(e.maxBitrate=n.maxBitrate),void 0!==n.maxFramerate&&(e.maxFramerate=n.maxFramerate),void 0!==n.priority&&(e.priority=n.priority,e.networkPriority=n.priority)}),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:i.encodings})),yield e.setParameters(i))})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return rG(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=rQ(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 rG(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 rG(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(sR(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,i=rQ(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 cv(e.sender,e.encodings,o.qualities,this.senderLock,sR(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(sR(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 rG(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 cv(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return rG(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&&sR(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 rG(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),sO()&&this.isInBackgroun
1d&&this.source===sb.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function cv(e,t,i,n,r,a,s){return rG(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(),o=n.encodings;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=ck(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),sI()&&(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 ck(e){switch(e){case"f":default:return eT.HIGH;case"h":return eT.MEDIUM;case"q":return eT.LOW}}function cb(e,t,i,n){if(!i)return[new iB({quality:eT.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){let n=new cg(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 iB({quality:Math.min(eT.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 iB({quality:ck(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 cy="leave-reconnect";(B=eU||(eU={}))[B.New=0]="New",B[B.Connected=1]="Connected",B[B.Disconnected=2]="Disconnected",B[B.Reconnecting=3]="Reconnecting",B[B.Closed=4]="Closed";class cT extends rX.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=oZ.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=eU.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.shouldFailOnV1Path=!1,this.log=rq,this.reliableReceivedState=new oL(3e4),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>rG(this,[e],void 0,function(e){var t=this;let i=e.channel;return function*(){i&&t.dataChannels.adoptSubscriberChannel(i)&&t.log.debug("on data channel ".concat(i.id,", ").concat(i.label))}()}),this.handleDataMessage=e=>rG(this,void 0,void 0,function*(){var t,i,n,r,a;let s=yield this.dataProcessLock.lock();try{let s=yield this.decodeDataMessage(e);if(!s)return;let o=iq.fromBinary(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(ev.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");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=iW.fromBinary(e.payload),i=new iq({value:t.value,participantIdentity:o.participantIdentity,participantSid:o.participantSid});(null==(r=i.value)?void 0:r.case)==="user"&&cS(i,i.value.value),this.emit
1(ev.DataPacketReceived,i,o.value.value.encryptionType)}else(null==(a=o.value)?void 0:a.case)==="user"&&cS(o,o.value.value),this.emit(ev.DataPacketReceived,o,iP.NONE)}finally{s()}}),this.handleDataTrackMessage=e=>rG(this,void 0,void 0,function*(){let t=yield this.decodeDataMessage(e);t&&this.emit("dataTrackPacketReceived",t)}),this.handleDataError=e=>{if(this._isClosed)return;let t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if("u">typeof RTCErrorEvent&&e instanceof RTCErrorEvent&&e.error){let i=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(i.message),{error:i,errorDetail:i.errorDetail,sctpCauseCode:i.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleDataChannelClose=e=>()=>{var t;this._isClosed||(null==(t=this.pcManager)?void 0:t.publisher.getConnectionState())!=="connected"||this.log.error("publisher data channel '".concat(ex[e],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected")),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.emit(ev.Disconnected),this.close()},n=Date.now()-this.reconnectStart,r=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null===r?i(n):(e===cy&&(r=0),this.log.debug("reconnecting in ".concat(r,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(ev.TokenRefreshed,this.token),this.reconnectTimeout=se.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),r))},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===eU.Connected&&e();let i=()=>{this.off(ev.Disconnected,n),e()},n=()=>{this.off(ev.Restarted,i),t()};this.once(ev.Restarted,i),this.once(ev.Disconnected,n)}),this.onRtpMapAvailable=e=>{let t=new Map;e.forEach(e=>{let i=e.codec.toLowerCase();sY(i)&&t.set(e.payload,i)}),this.emit(ev.RTPVideoMapUpdate,t)},this.handleBrowserOnLine=()=>rG(this,void 0,void 0,function*(){!this.url||(yield fetch(sZ(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===e_.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===e_.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ig.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>rG(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(sZ(this.url),{method:"HEAD"}),sC(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=rV(null!=(t=e.loggerName)?t:ec.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new oO(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new e1,this.dataProcessLock=new e1,this.dataChannels=new o5({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:e=>this.handleDataMessage(e),onDataTrackMessage:e=>this.handleDataTrackMessage(e),onDataError:e=>this.handleDataError(e),onChannelClose:e=>this.handleDataChannelClose(e)(),onBufferStatusChanged:(e,t)=>this.emit(ev.DCBufferStatusChanged,t,e)}),this.client.onParticipantUpdate=e=>this.emit(ev.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(ev.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(ev.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(ev.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(ev.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(ev.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(ev.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(ev.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>
1this.emit(ev.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(ev.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 rG(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;r._isNewlyCreated=!1,r.url=e,r.token=t,r.signalOpts=i,r.maxJoinAttempts=i.maxRetries;try{let l;r.joinAttempts+=1,r.setupSignalClientCallbacks();let d=!a&&oe()&&!sI();if(d){r.pcManager||(yield r.configure(),r.applyInitialPublisherLayout());let e=yield null==(s=r.pcManager)?void 0:s.publisher.createInitialOffer();e&&(l=oN(e.offer,e.offerId))}if(null==n?void 0:n.aborted)throw a$.cancelled("Connection aborted");if(!a&&r.shouldFailOnV1Path)throw r.shouldFailOnV1Path=!1,a$.serviceNotFound("Simulated v1 path failure","v0-rtc");let u=yield r.client.join(e,t,i,n,a,l);r._isClosed=!1,r.latestJoinResponse=u,r.participantSid=null==(o=u.participant)?void 0:o.sid,r.subscriberPrimary=u.subscriberPrimary,d?null==(c=r.pcManager)||c.updateConfiguration(r.makeRTCConfiguration(u)):(!r.pcManager&&(yield r.configure(u,!a),a||r.applyInitialPublisherLayout()),(!r.subscriberPrimary||u.fastPublish)&&r.negotiate().catch(e=>{r.log.error(e)})),r.registerOnLineListener(),r.clientConfiguration=u.clientConfiguration,r.emit(ev.SignalConnected,u);let h=u.serverInfo;return h||(h={version:u.serverVersion,region:u.serverRegion}),r.log.info("connected to Livekit Server ".concat(Object.entries(h).map(e=>{let t=tf(e,2),i=t[0],n=t[1];return"".concat(i,": ").concat(n)}).join(", "))),{joinResponse:u,serverInfo:h}}catch(s){if(s instanceof a$){if(s.reason===eh.ServerUnreachable){if(r.log.warn("Couldn't connect to server, attempt ".concat(r.joinAttempts," of ").concat(r.maxJoinAttempts)),r.joinAttempts<r.maxJoinAttempts)return r.join(e,t,i,n,a)}else if(s.reason===eh.ServiceNotFound)return r.log.warn("Initial connection failed: ".concat(s.message," – Retrying")),r.pcManager&&(r.pcManager.onStateChange=void 0,yield r.cleanupPeerConnections()),r.join(e,t,i,n,!0)}throw s}}()})}close(){return rG(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(ev.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return rG(this,void 0,void 0,function*(){var e;this.dataChannels.teardown(),yield null==(e=this.pcManager)?void 0:e.close(),this.pcManager=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(){return rG(this,void 0,void 0,function*(){for(let e of(yield this.client.close(),this.client.resetCallbacks(),Object.keys(this.pendingTrackResolvers)))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new a1("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 t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",{error:e})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null==(e=this.dataChannelForKind(ex.RELIABLE,!0))?void 0:e.readyState}getConnectedServerAddress(){return rG(this,void 0,void 0,function*(){var e;return null==(e=this.pcManager)?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return rG(this,void 0,void 0,function*(){var i;if(!this.pcManager||this.pcManager.currentState===eL.NEW){if(e){this.participantSid=null==(i=e.participant)?void 0:i.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new o$(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new o$("publisher-only",this.loggerOptions,e)}
1this.emit(ev.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)=>rG(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(e)),["closed","disconnected","failed"].includes(t)&&(this.publisherConnectionPromise=void 0),e===eL.CONNECTED){let e=this.pcState===eU.New;this.pcState=eU.Connected,e&&this.emit(ev.Connected,this.latestJoinResponse)}else e===eL.FAILED&&(this.pcState===eU.Connected||this.pcState===eU.Reconnecting)&&(this.pcState=eU.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?ig.RR_SUBSCRIBER_FAILED:ig.RR_PUBLISHER_FAILED));let n=this.client.isDisconnected||this.client.currentState===e_.RECONNECTING,r=[eL.FAILED,eL.CLOSING,eL.CLOSED].includes(e);n&&r&&!this._isClosed&&this.emit(ev.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(ev.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>rG(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",{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",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>rG(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",{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),{cid:e.cid});let i=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(ev.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ev.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(ev.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(ev.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ev.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(ev.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(ev.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(ev.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(ev.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ig.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(null==e?void 0:e.action,")"),{reason:null==e?void 0:e.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(ev.ServerRegionsReported,e.regions)),e.action){case rn.DISCONNECT:this.emit(ev.Disconnected,null==e?void 0:e.reason),this.close();break;case rn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(cy);break;case rn.RESUME:this.handleDisconnect(cy)}}}makeRTCConfiguration(e){var t;let i=Object.assign({},this.rtcConfig);if(((null==(t=this.signalOpts)?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!s_())&&oa()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(e.iceServers&&!i.iceServers){let t=[];e.iceServers.forEach(e=>{let i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.pu
1sh(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ip.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(){this.createDataChannels(),sN()||this.addMediaSections(3,3)}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.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return rG(this,void 0,void 0,function*(){return e.data instanceof ArrayBuffer?new Uint8Array(e.data):e.data instanceof Blob?new Uint8Array((yield e.data.arrayBuffer())):void this.log.error("unsupported data type",{data:e.data})})}createSender(e,t,i){return rG(this,void 0,void 0,function*(){let n;if(sE())n=yield this.createTransceiverRTCRtpSender(e,t,i);else if(sw())this.log.warn("using add-track fallback"),n=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new a3("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(n,t),n})}createSimulcastSender(e,t,i,n){return rG(this,void 0,void 0,function*(){let r;if(sE())r=yield this.createSimulcastTransceiverSender(e,t,i,n);else if(sw())this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new a3("Cannot stream on this device");return r&&this.setupFrameMetadataSender(r,i),r})}get frameMetadataWorker(){var e,t;return null==(t=null!=(e=this.options.frameMetadata)?e:this.options.packetTrailer)?void 0:t.worker}setupFrameMetadataSender(e){var t,i,n;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=this.frameMetadataWorker;if(!a||(null==(t=this.signalOpts)?void 0:t.e2eeEnabled))return;let s=null!=(i=r.frameMetadata)?i:r.packetTrailer,o=oo(s);if(s_()){o&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:s}));return}if(!os(null!=(n=this.options.frameMetadata)?n:this.options.packetTrailer)||!("createEncodedStreams"in e)){o&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}let c=e.createEncodedStreams(),l=c.readable,d=c.writable;o?a.postMessage({kind:"encode",data:{readableStream:l,writableStream:d,packetTrailer:s}},[l,d]):l.pipeTo(d)}createTransceiverRTCRtpSender(e,t,i){return rG(this,void 0,void 0,function*(){if(!this.pcManager)throw new a3("publisher is closed");let n=[];e.mediaStream&&n.push(e.mediaStream),s4(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 rG(this,void 0,void 0,function*(){if(!this.pcManager)throw new a3("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 rG(this,void 0,void 0,function*(){if(!this.pcManager)throw new a3("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return rG(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed){if(this.attemptingReconnect)return void this.log.warn("already attempting reconnect, returning early");((null==(t=this.clientConfiguration)?void 0:t.resumeConnection)===ip.DISABLED||(null!=(n=null==(i=this.pcManager)?void 0:i.currentState)?n:eL.NEW)===eL.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;t instanceof a3?(this.log.debug("received unrecoverable error",{error:t}),e=!1):t instanceof a7||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",ig.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit
1(ev.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",{error:e})}return null}restartConnection(e){return rG(this,void 0,void 0,function*(){var t,i,n;try{let i;if(!this.url||!this.token)throw new a3("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(ev.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"),new a7;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===eh.NotAllowed)throw new a3("could not reconnect, token might be expired");throw new a7}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(ev.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==e_.CONNECTED)throw new a7("Signal connection got severed during reconnect");null==(t=this.regionStrategy)||t.resetAttempts(),this.emit(ev.Restarted)}catch(t){let e=yield null==(i=this.regionStrategy)?void 0:i.getNextUrl();if(e)return void(yield this.restartConnection(e));throw null==(n=this.regionStrategy)||n.resetAttempts(),t}})}resumeConnection(e){return rG(this,void 0,void 0,function*(){let t;if(!this.url||!this.token)throw new a3("could not reconnect, url or token not saved");if(!this.pcManager)throw new a3("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(ev.Resuming);try{this.setupSignalClientCallbacks(),t=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,{error:t})),t instanceof a$&&t.reason===eh.NotAllowed)throw new a3("could not reconnect, token might be expired");if(t instanceof a$&&t.reason===eh.LeaveRequest)throw t;throw new a7(e)}
1if(this.emit(ev.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==e_.CONNECTED)throw new a7("Signal connection got severed during reconnect");this.client.setReconnected();let i=this.dataChannelForKind(ex.RELIABLE);(null==i?void 0:i.readyState)==="open"&&null===i.id&&this.createDataChannels(),(null==t?void 0:t.lastMessageSeq)&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(e=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:e}))}),this.emit(ev.Resumed)})}waitForPCInitialConnection(e,t){return rG(this,void 0,void 0,function*(){if(!this.pcManager)throw new a3("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return rG(this,void 0,void 0,function*(){this.pcState=eU.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield sC(2e3),!this.pcManager)throw new a3("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=eU.Connected}catch(e){throw this.pcState=eU.Disconnected,a$.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return rG(this,void 0,void 0,function*(){let i=new iq({destinationIdentities:[e],kind:iV.RELIABLE,value:{case:"rpcAck",value:new i$({requestId:t})}});yield this.sendDataPacket(i,ex.RELIABLE)})}sendDataPacket(e,t){return rG(this,void 0,void 0,function*(){var i,n;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 iW({value:e.value})}(e);if(t){let i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new iH({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===ex.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());let r=e.toBinary(),a=Math.min(null!=(n=null==(i=this.pcManager)?void 0:i.getMaxPublisherMessageSize())?n:64e3,64e3);if(void 0!==a&&0!==a&&r.byteLength>a)throw new a9("cannot publish data packet larger than ".concat(a," bytes (got ").concat(r.byteLength,")"));t===ex.RELIABLE?yield this.reliableChannel.send(r,e.sequence):yield this.lossyChannel.send(r)})}sendDataTrackFrame(e){return rG(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(ex.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return rG(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(ex.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return rG(this,void 0,void 0,function*(){return this.flowControlFor(e).waitForHeadroomWithLock()})}ensureDataTransportConnected(e){return rG(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 a3("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=>{t.log.error(e)});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 sC(50)}throw a$.internal("could not establish ".concat(a," connection, state: ").concat(r.getICEConnectionState()))}()})}ensurePublisherConnected(e){return rG(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&!![eL.CONNECTING,eL.CONNECTED].includes(this.pcManager.currentState)&&!!this.client.ws&&this.client.ws.readyState!==WebSocket.CLOSED}negotiate(){return rG(this,void 0,void 0,function*(){return new az((e,t)=>rG(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new a4("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.dataChannels.hasPublisherChannels||this.createDataChannels();let i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new a4("cannot negotiate on closed engine")),this.on(ev.Closing,n),this.on(ev.Restarting,n),this.pcManager.publisher.off(oV,this.onRtpMapAvailable),this.pcManager.publisher.once(oV,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),e()}catch(n){if(i.signal.aborted)return void e();n instanceof a4&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ig.RR_UNKNOWN),n instanceof Error?t(n):t(Error(String(n)))}
1finally{this.off(ev.Closing,n),this.off(ev.Restarting,n)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}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");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 rT({answer:"publisher-only"===this.pcManager.mode?l?oN({sdp:l.sdp,type:l.type}):void 0:u?oN({sdp:u.sdp,type:u.type}):void 0,offer:"publisher-only"===this.pcManager.mode?c?oN({sdp:c.sdp,type:c.type}):void 0:d?oN({sdp:d.sdp,type:d.type}):void 0,subscription:new n2({trackSids:p,subscribe:!h,participantTracks:[]}),publishTracks:(o=[],t.forEach(e=>{void 0!==e.track&&o.push(new nZ({cid:e.track.mediaStreamID,track:e.trackInfo}))}),o),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:m,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new rS({publisherSid:t,lastSeq:e})),publishDataTracks:i.map(e=>{let t;return new nH({info:new iM({sid:(t=e).sid,pubHandle:t.pubHandle,name:t.name,encryption:t.usesE2ee?iP.GCM:iP.NONE})})})}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){let e=[],t=(t,i)=>{(null==t?void 0:t.id)!==void 0&&null!==t.id&&e.push(new rC({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(ex.LOSSY),nL.PUBLISHER),t(this.dataChannelForKind(ex.RELIABLE),nL.PUBLISHER),t(this.dataChannelForKind(ex.LOSSY,!0),nL.SUBSCRIBER),t(this.dataChannelForKind(ex.RELIABLE,!0),nL.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&se.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){sA()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){sA()&&(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=>tf(e,1)[0]===i);if(e)return e[1]}}}function cS(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}let cC=rV(ec.Region);class cE{static fetchRegionSettings(e,t,i){return rG(this,void 0,void 0,function*(){let n=yield cE.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 rG(this,void 0,void 0,function*(){clearTimeout(cE.settingsTimeouts.get(e.hostname)),cE.settingsTimeouts.set(e.hostname,setTimeout(()=>rG(this,void 0,void 0,function*(){try{let i=yield cE.fetchRegionSettings(e,t);cE.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof a$&&n.reason===eh.NotAllowed)return void cC.debug("token is not val
1id, cancelling auto region refresh");cC.debug("auto refetching of region settings failed",{error:n}),cE.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){cE.cache.set(e.hostname,i),cE.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){let t=cE.settingsTimeouts.get(e);t&&(clearTimeout(t),cE.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=cE.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{let t=cE.connectionTrackers.get(e);t&&0===t.connectionCount&&(cC.debug("stopping region refetch after disconnect delay",{hostname:e}),cE.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){let t=cE.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){let e=this.serverUrl.hostname,t=cE.connectionTrackers.get(e);t||(t={connectionCount:0},cE.connectionTrackers.set(e,t)),t.connectionCount++,cE.cancelCleanup(e)}notifyDisconnected(){let e=this.serverUrl.hostname,t=cE.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&cE.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;let i=this.getServerUrl(),n=cE.cache.get(i.hostname);cE.scheduleRefetch(this.serverUrl,this.token,null!=(t=null==n?void 0:n.maxAgeInMs)?t:5e3)}isCloud(){return sL(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return rG(this,void 0,void 0,function*(){return cE.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return rG(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=cE.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),cE.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),cC.info("switching to region: ".concat(e.region),{region:e.region}),e.url}})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){cE.updateCachedRegionSettings(this.serverUrl,this.token,e)}}function cw(){return new CompressionStream("deflate-raw")}function cR(){return new DecompressionStream("deflate-raw")}function cP(e,t){return rG(this,void 0,void 0,function*(){let i=new DecompressionStream("deflate-raw"),n=i.writable.getWriter();return n.write(e).catch(()=>{}),n.close().catch(()=>{}),cI(i.readable,t)})}function cI(e,t){return rG(this,void 0,void 0,function*(){let i=e.getReader(),n=[],r=0;for(;;){let e=yield i.read(),a=e.done,s=e.value;if(a)break;if(n.push(s),r+=s.byteLength,"number"==typeof t&&r>t)throw yield i.cancel(),new a8("Decompressed payload exceeds the maximum payload size of ".concat(t," bytes"),ep.PayloadTooLarge)}let a=new Uint8Array(r),s=0;for(let e of n)a.set(e,s),s+=e.byteLength;return a})}cE.cache=new Map,cE.settingsTimeouts=new Map,cE.connectionTrackers=new Map,cE.fetchLock=new e1;class c_{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 a8("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ep.Incomplete);else if(this.bytesReceived>this.totalByteSize)throw new a8("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ep.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class cM extends c_{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:()=>rG(this,void 0,void 0,function*(){var i;try{let t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;let n=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(n.done)return this.validateBytesReceived(!0),"number"==typeof this.totalByteSize&&(null==(i=this.onProgress)||i.call(this,1)),{done:!0,value:void 0};return this.handleChunkReceived(n.value),{done:!1,value:n.value.content}}catch(e){throw t(),e}}),return(){return rG(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return rG(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=rQ(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)}()})}}class cD extends c_{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;let i=s0(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:()=>rG(this,void 0,void 0,function*(){var r;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),"number"==typeof this.totalByteSize&&(null==(r=this.onProgress)||r.call(this,1)),{done:!0,value:void 0};{let e;this.handleChunkReceived(n.value);try{e=t.decode(n.value.content)}catch(e){throw new a8("Cannot decode datastream chunk ".concat(n.value.chunkIndex," as text: ").concat(e),ep.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw n(),e}}),return(){return rG(this,void 0,void 0,function*(){return n(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return rG(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=rQ(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 cO{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e9;this.log=rq,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;for(let t of(this.bufferedPackets=[],e)){let e=t.packet,i=t.encryptionType;this.handleDataStreamPacket(e,i)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new a8('A text stream handler for topic "'.concat(e,'" has already been set.'),ep.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new a8('A byte stream handler for topic "'.concat(e,'" has already been set.'),ep.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}
1validateParticipantHasNoActiveDataStreams(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 a=new a8("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ep.AbnormalEnd);for(let e of i){var n=tf(e,2);let t=n[0];n[1].controller.error(a),this.byteStreamControllers.delete(t)}for(let e of t){var r=tf(e,2);let t=r[0];r[1].controller.error(a),this.textStreamControllers.delete(t)}}}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;switch(e.contentHeader.case){case"byteHeader":{let r,a,s=this.byteStreamHandlers.get(e.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let o={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:s0(e.timestamp),attributes:e.attributes,encryptionType:i};switch(e.compression){case nn.DEFLATE_RAW:if(!oe())return void rq.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));a=!0;break;case nn.NONE:a=!1;break;default:rq.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}let c=e.inlineContent;if(void 0!==c)return void s(new cM(o,cA(e.streamId,a?cP(c,this.maxPayloadByteLength):c),s0(e.totalLength)),{identity:t});let l=new ReadableStream({start:i=>{if(r=i,this.byteStreamControllers.has(e.streamId))throw new a8("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ep.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new cM(o,a?function(e,t,i){let n;return e.pipeThrough(cN(t)).pipeThrough(cL()).pipeThrough(cR()).pipeThrough(cx(t,i)).pipeThrough((n=0,new TransformStream({transform:(e,i)=>{e.byteLength>0&&(i.enqueue(new no({streamId:t,chunkIndex:s1(n),content:e})),n+=1)}})))}(l,e.streamId,this.maxPayloadByteLength):l,s0(e.totalLength)),{identity:t});return}case"textHeader":{let n,r,a=this.textStreamHandlers.get(e.topic);if(!a)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let s={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};switch(e.compression){case nn.DEFLATE_RAW:if(!oe())return void rq.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));r=!0;break;case nn.NONE:r=!1;break;default:rq.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}let o=e.inlineContent;if(void 0!==o){let i=r?cP(o,this.maxPayloadByteLength):o;a(new cD(s,cA(e.streamId,i),s0(e.totalLength)),{identity:t});return}let c=new ReadableStream({start:i=>{if(n=i,this.textStreamControllers.has(e.streamId))throw new a8("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ep.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now(),sendingParticipantIdentity:t})}});a(new cD(s,r?function(e,t,i){let n,r,a,s;return e.pipeThrough(cN(t)).pipeThrough(cL()).pipeThrough(cR()).pipeThrough(cx(t,i)).pipeThrough((n=new TextDecoder("utf-8",{fatal:!0}),r=new TextEncoder,a=0,s=e=>{try{return e?n.decode(e,{stream:!0}):n.decode()}catch(e){throw new a8("Cannot decode compressed data stream ".concat(t," as text: ").concat(e),ep.DecodeFailed)}},new TransformStream({transform:(e,i)=>{let n=s(e);n.length>0&&(i.enqueue(new no({streamId:t,chunkIndex:s1(a),content:r.encode(n)})),a+=1)},flush:e=>{let i=s();i.length>0&&(e.enqueue(new no({streamId:t,chunkIndex:s1(a),content:r.encode(i)})),a+=1)}})))}(c,e.streamId,this.maxPayloadByteLength):c,s0(e.totalLength)),{identity:t});return}}}handleStreamChunk(e,t){let i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new a8("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ep.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 a8("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ep.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 a8("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ep.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),e.reason?i.controller.error(new a8("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),ep.AbnormalEnd)):i.controller.close()),this.textStreamControllers.delete(e.streamId));let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new a8("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ep.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),e.reason?n.controller.error(new a8("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),ep.AbnormalEnd)):n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}function cA(e,t){return new ReadableStream({start:i=>rG(this,void 0,void 0,function*(){try{let n=yield t;i.enqueue(new no({streamId:e,chunkIndex:BigInt(0),content:n})),i.close()}catch(e){i.error(e)}})})}function cN(e){let t=-1;return new TransformStream({transform:(i,n)=>{let r=s0(i.chunkIndex);if(r<=t)return void rq.warn("ignoring duplicate chunk ".concat(r," for compressed data stream ").concat(e," (last processed: ").concat(t,")"));if(r>t+1)throw new a8("Missing chunk(s) ".concat(t+1,"..").concat(r-1," for compressed data stream ").concat(e," - cannot continue decompressing"),ep.Incomplete);t=r,n.enqueue(i)}})}function cL(){return new TransformStream({transform:(e,t)=>
1{t.enqueue(e.content)}})}function cx(e,t){let i=0;return new TransformStream({transform:(n,r)=>{if((i+=n.byteLength)>t)throw new a8("Data stream ".concat(e," exceeds the maximum payload size of ").concat(t," bytes"),ep.PayloadTooLarge);r.enqueue(n)}})}class cU{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 rG(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null==(e=this.onClose)||e.call(this)})}}class cF extends cU{}class cB extends cU{}function cj(e,t,i){var n;return new ns({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:s1(e.timestamp),totalLength:s1(e.size),attributes:e.attributes,compression:null!=(n=null==i?void 0:i.compression)?n:nn.NONE,inlineContent:null==i?void 0:i.inlineContent,contentHeader:{case:"textHeader",value:new nr({version:null==t?void 0:t.version,attachedStreamIds:e.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:(null==t?void 0:t.type)==="update"?ni.UPDATE:ni.CREATE})}})}function cq(e,t){var i;return new ns({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:s1(e.timestamp),totalLength:s1(e.size),attributes:e.attributes,compression:null!=(i=null==t?void 0:t.compression)?i:nn.NONE,inlineContent:null==t?void 0:t.inlineContent,contentHeader:{case:"byteHeader",value:new na({name:e.name})}})}function cV(e,t){return new iq({destinationIdentities:t,value:{case:"streamHeader",value:e}})}let cH=new TextEncoder;class cW{constructor(e,t,i,n,r){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=i,this.getRemoteParticipantCapabilities=n,this.getAllRemoteParticipantIdentities=r}setupEngine(e){this.engine=e}sendText(e,t){return rG(this,void 0,void 0,function*(){var i,n,r,a,s;let o=crypto.randomUUID(),c=cH.encode(e),l=c.byteLength,d=null==(i=null==t?void 0:t.compress)||i,u={id:o,mimeType:"text/plain",timestamp:Date.now(),topic:null!=(n=null==t?void 0:t.topic)?n:"",size:l,attributes:null==t?void 0:t.attributes,encryptionType:(null==(r=this.engine.e2eeManager)?void 0:r.isDataChannelEncryptionEnabled)?iP.GCM:iP.NONE},h=d&&oe()&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)&&this.allRecipientsSupportCompression(null==t?void 0:t.destinationIdentities)?cz.fromStream(s7(c).pipeThrough(cw())):null;if((!(null==t?void 0:t.attachments)||0===t.attachments.length)&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)){let e=c,i=nn.NONE;if(h){let t=yield h.collect();t.byteLength<c.byteLength&&(e=t,i=nn.DEFLATE_RAW)}let n=cV(cj(u,void 0,{compression:i,inlineContent:e}),null==t?void 0:t.destinationIdentities);if(n.toBinary().byteLength<=15e3)return yield this.engine.sendDataPacket(n,ex.RELIABLE),null==(a=null==t?void 0:t.onProgress)||a.call(t,1),u}let p=null==(s=null==t?void 0:t.attachments)?void 0:s.map(()=>crypto.randomUUID()),m=p?p.length+1:1,g=Array(m).fill(0),f=(e,i)=>{var n;g[i]=e,null==(n=null==t?void 0:t.onProgress)||n.call(t,g.reduce((e,t)=>e+t,0)/m)};if(h){u.attachedStreamIds=p;let e=cV(cj(u,void 0,{compression:nn.DEFLATE_RAW}),null==t?void 0:t.destinationIdentities);yield this.sendChunkedByteStream(e,o,null==t?void 0:t.destinationIdentities,h.stream().pipeThrough(cG(c.length,e=>f(e,0)))),0===c.length&&f(1,0)}else{let i=yield this.streamText({streamId:o,totalSize:l,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:p,attributes:null==t?void 0:t.attributes});yield i.write(e),f(1,0),yield i.close(),u=i.info}return(null==t?void 0:t.attachments)&&p&&(yield Promise.all(t.attachments.map((e,i)=>rG(this,void 0,void 0,function*(){return this._sendFile(p[i],e,{topic:t.to
1pic,mimeType:e.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:e=>{f(e,i+1)}})})))),u})}sendBytes(e,t){return rG(this,void 0,void 0,function*(){var i,n,r,a,s,o,c;let l=crypto.randomUUID(),d=null==t?void 0:t.destinationIdentities,u=null==(i=null==t?void 0:t.compress)||i,h={id:l,name:null!=(n=null==t?void 0:t.name)?n:"unknown",mimeType:null!=(r=null==t?void 0:t.mimeType)?r:"application/octet-stream",timestamp:Date.now(),topic:null!=(a=null==t?void 0:t.topic)?a:"",size:e.byteLength,attributes:null==t?void 0:t.attributes,encryptionType:(null==(s=this.engine.e2eeManager)?void 0:s.isDataChannelEncryptionEnabled)?iP.GCM:iP.NONE},p=cG(e.length,null==t?void 0:t.onProgress),m=u&&oe()&&this.allRecipientsSupportV2(d)&&this.allRecipientsSupportCompression(d)?cz.fromStream(s7(e).pipeThrough(p).pipeThrough(cw())):null;if(this.allRecipientsSupportV2(d)){let i=e,n=nn.NONE;if(m){let t=yield m.collect();t.byteLength<e.byteLength&&(i=t,n=nn.DEFLATE_RAW)}let r=cV(cq(h,{compression:n,inlineContent:i}
1),d);if(r.toBinary().byteLength<=15e3)return yield this.engine.sendDataPacket(r,ex.RELIABLE),null==(o=null==t?void 0:t.onProgress)||o.call(t,1),h}let g=cV(cq(h,{compression:m?nn.DEFLATE_RAW:nn.NONE}),d),f=m?m.stream():s7(e).pipeThrough(p);return yield this.sendChunkedByteStream(g,l,d,f),0===e.length&&(null==(c=null==t?void 0:t.onProgress)||c.call(t,1)),h})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(e=>this.getRemoteParticipantClientProtocol(e)>=2)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(e=>this.getRemoteParticipantCapabilities(e).includes(i5.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,i,n){return rG(this,void 0,void 0,function*(){var r,a,s,o;let c=this.engine;yield cK(c,e);let l=0;try{for(var d,u=!0,h=rQ(function(e,t){return rJ(this,arguments,function*(){let i=e.getReader(),n=new Uint8Array(0);try{for(;;){let e=yield rK(i.read()),r=e.done,a=e.value;if(r)break;if(0===a.byteLength)continue;let s=new Uint8Array(n.byteLength+a.byteLength);for(s.set(n),s.set(a,n.byteLength),n=s;n.byteLength>=t;)yield yield rK(n.slice(0,t)),n=n.slice(t)}n.byteLength>0&&(yield yield rK(n))}finally{i.releaseLock()}})}(n,15e3));!(r=(d=yield h.next()).done);u=!0){o=d.value,u=!1;let e=new iq({destinationIdentities:i,value:{case:"streamChunk",value:new no({content:o,streamId:t,chunkIndex:s1(l)})}});yield c.sendDataPacket(e,ex.RELIABLE),l+=1}}catch(e){a={error:e}}finally{try{!u&&!r&&(s=h.return)&&(yield s.call(h))}finally{if(a)throw a.error}}yield cJ(t,i,c)})}streamText(e){return rG(this,void 0,void 0,function*(){var t,i,n;let r=null!=(t=null==e?void 0:e.streamId)?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,s={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)?iP.GCM:iP.NONE,attachedStreamIds:null==e?void 0:e.attachedStreamIds},o=cV(cj(s,e),a);yield cK(this.engine,o);let c=0,l=this.engine,d=new WritableStream({write(e){return rG(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 iq({destinationIdentities:a,value:{case:"streamChunk",value:new no({content:t,streamId:r,chunkIndex:s1(c)})}});yield l.sendDataPacket(e,ex.RELIABLE),c+=1}})},close(){return rG(this,void 0,void 0,function*(){yield cJ(r,a,l)})},abort(e){console.log("Sink error:",e)}}),u=()=>rG(this,void 0,void 0,function*(){yield h.close()});l.once(ev.Closing,u);let h=new cF(d,s,()=>this.engine.off(ev.Closing,u));return h})}sendFile(e,t){return rG(this,void 0,void 0,function*(){let i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return rG(this,void 0,void 0,function*(){var n,r,a,s,o;let c=null==i?void 0:i.destinationIdentities,l=(null==(n=null==i?void 0:i.compress)||n)&&oe()&&this.allRecipientsSupportV2(c)&&this.allRecipientsSupportCompression(c),d={id:e,name:t.name,mimeType:null!=(r=null==i?void 0:i.mimeType)?r:t.type,topic:null!=(a=null==i?void 0:i.topic)?a:"",timestamp:Date.now(),size:t.size,encryptionType:(null==(s=this.engine.e2eeManager)?void 0:s.isDataChannelEncryptionEnabled)?iP.GCM:iP.NONE},u=cV(cq(d,{compression:l?nn.DEFLATE_RAW:nn.NONE}),c),h=t.stream().pipeThrough(cG(t.size,null==i?void 0:i.onProgress)),p=l?h.pipeThrough(cw()):h;return yield this.sendChunkedByteStream(u,e,c,p),0===t.size&&(null==(o=null==i?void 0:i.onProgress)||o.call(i,1)),d})}streamBytes(e){return rG(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)?iP.GCM:iP.NONE},l=cV(cq(c),o);yield cK(this.engine,l);let d=0,u=new e1,h=this.engine,p=this.log;return new cB(new WritableStream({write(e){return rG(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 iq({destinationIdentities:o,value:{case:"streamChunk",value:new no({content:t,streamId:s,chunkIndex:s1(d)})}});yield h.sendDataPacket(n,ex.RELIABLE),d+=1,i+=t.byteLength}}finally{t()}})},close(){return rG(this,void 0,void 0,function*(){yield cJ(s,o,h)})},abort(e){p.error("Sink error:",e)}}),c)})}}class cz{constructor(e){this.state=e}static fromStream(e){return new cz({type:"stream",stream:e})}collect(){return rG(this,void 0,void 0,function*(){switch(this.state.type){case"stream":let e=yield cI(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}})}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return s7(this.state.bytes)}}}function cG(e,t){let i=0;return new TransformStream({transform(n,r){i+=n.byteLength,t&&"number"==typeof e&&e>0&&t(Math.min(i/e,1)),r.enqueue(n)}})}function cK(e,t){return rG(this,void 0,void 0,function*(){if(t.toBinary().byteLength>15e3)throw new a8("data stream header exceeds the ".concat(15e3,"-byte limit; reduce attribute size"),ep.HeaderTooLarge);yield e.sendDataPacket(t,ex.RELIABLE)})}function cJ(e,t,i){return rG(this,void 0,void 0,function*(){let n=new iq({destinationIdentities:t,value:{case:"streamTrailer",value:new nc({streamId:e})}});yield i.sendDataPacket(n,ex.RELIABLE)})}function cQ(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 cY(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))},e),t.signal}(j=eF||(eF={}))[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 cX extends aZ{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=eF[t]}static tooShort(){return new cX("Too short to contain a valid header",eF.TooShort)}static headerOverrun(){return new cX("Header exceeds total packet length",eF.HeaderOverrun)}static missingExtWords(){return new cX("Extension word indicator is missing",eF.MissingExtWords)}static unsupportedVersion(e){return new cX("Unsupported version ".concat(e),eF.UnsupportedVersion)}
1static invalidHandle(e){return new cX("invalid track handle: ".concat(e.message),eF.InvalidHandle,{cause:e})}static malformedExt(e){return new cX("Extension with tag ".concat(e," is malformed"),eF.MalformedExt)}}(q=eB||(eB={}))[q.TooSmallForHeader=0]="TooSmallForHeader",q[q.TooSmallForPayload=1]="TooSmallForPayload";class cZ extends aZ{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=eB[t]}static tooSmallForHeader(){return new cZ("Buffer cannot fit header",eB.TooSmallForHeader)}static tooSmallForPayload(){return new cZ("Buffer cannot fit payload",eB.TooSmallForPayload)}}class c${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)}}(V=ej||(ej={}))[V.UserTimestamp=2]="UserTimestamp",V[V.E2ee=1]="E2ee";class c0 extends c${}class c1 extends c0{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+c1.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,c1.tag),t+=1,e.setUint8(t,c1.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:c1.tag,lengthBytes:c1.lengthBytes,timestamp:this.timestamp}}}c1.tag=ej.UserTimestamp,c1.lengthBytes=8;class c2 extends c0{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+c2.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,c2.tag),t+=1,e.setUint8(t,c2.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:c2.tag,lengthBytes:c2.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}c2.tag=ej.E2ee,c2.lengthBytes=13;class c3 extends c${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=oE(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 ej.UserTimestamp:if(n.byteLength-r<c1.lengthBytes)throw cX.malformedExt(e);t=new c1(n.getBigUint64(r)),r+=a;break;case ej.E2ee:if(n.byteLength-r<c2.lengthBytes)throw cX.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 c2(s,o),r+=a;break;default:if(n.byteLength-r<a)throw cX.malformedExt(e);r+=a}}return[new c3({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 c4={from:e=>({payload:e.payload,extensions:new c3({userTimestamp:e.userTimestamp?new c1(e.userTimestamp):void 0})}),lossyIntoFrame(e){var t;return{payload:e.payload,userTimestamp:null==(t=e.extensions.userTimestamp)?void 0:t.timestamp}}},c9=Symbol.for("lk.track"),c6=Symbol.for("lk.data-track");class c5{constructor(e,t,i){this.trackSymbol=c9,this.isLocal=!1,this.typeSymbol=c6,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),i=tf(t,2),n=i[0];return i[1].catch(()=>{}),n}catch(e){throw e}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class c8 extends c${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 c3}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((2+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-2-e}}toBinaryLengthBytes(){let e=this.extensionsMetrics(),t=e.lengthBytes,i=e.paddingLengthBytes,n=12;return t>0&&(n+=2+t+i),n}toBinaryInto(e){let t;if(e.byteLength<this.toBinaryLengthBytes())throw cZ.tooSmallForHeader();let i=0;switch(this.marker){case eq.Inter:t=0;break;case eq.Final:t=1;break;case eq.Start:t=2;break;case eq.Single:t=3}i|=t<<3;let n=this.extensionsMetrics(),r=n.lengthBytes,a=n.lengthWords,s=n.paddingLengthBytes;r>0&&(i|=4);let o=0;if(e.setUint8(o,i),o+=1,e.setUint8(o,0),o+=1,e.setUint16(o,this.trackHandle),o+=2,e.setUint16(o,this.sequence.value),o+=2,e.setUint16(o,this.frameNumber.value),o+=2,e.setUint32(o,this.timestamp.asTicks()),o+=4,r>0){e.setUint16(o,a-1),o+=2;let t=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));o+=t;for(let t=0;t<s;t+=1)e.setUint8(o,0),o+=1}let c=this.toBinaryLengthBytes();if(o!==c)throw Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(o," bytes but expected length 
1was ").concat(c," bytes"));return c}static fromBinary(e){let t,i,n=oE(e);if(n.byteLength<12)throw cX.tooShort();let r=0,a=n.getUint8(r);r+=1;let s=a>>5&7;if(s>0)throw cX.unsupportedVersion(s);switch(a>>3&3){case 2:t=eq.Start;break;case 1:t=eq.Final;break;case 3:t=eq.Single;break;default:t=eq.Inter}r+=1;try{i=oR.fromNumber(n.getUint16(r))}catch(e){if(e instanceof ow&&(e.isReason(eP.Reserved)||e.isReason(eP.TooLarge)))throw cX.invalidHandle(e);throw e}r+=2;let o=oT.u16(n.getUint16(r));r+=2;let c=oT.u16(n.getUint16(r));r+=2;let l=oS.fromRtpTicks(n.getUint32(r));r+=4;let d=new c3;if((a>>2&1)>0){if(n.byteLength-r<2)throw cX.missingExtWords();let e=n.getUint16(r),t=4*(e+1)-2;if((r+=2)+t>n.byteLength)throw cX.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),a=tf(c3.fromBinary(i),2),s=a[0],o=a[1];d=s,r+=o}return[new c8({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()}}}(H=eq||(eq={}))[H.Start=0]="Start",H[H.Inter=1]="Inter",H[H.Final=2]="Final",H[H.Single=3]="Single";class c7 extends c${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 cZ.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=oE(e),i=tf(c8.fromBinary(t),2),n=i[0],r=i[1];return[new c7(n,new Uint8Array(t.buffer.slice(t.byteOffset+r,t.byteOffset+t.byteLength))),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}let le=rV(ec.DataTracks);class lt extends aZ{constructor(e,t,i,n){super(19,"Frame ".concat(i," dropped: ").concat(e),n),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=eV[t],this.frameNumber=i}static interrupted(e,t){return new lt("Interrupted by the start of a new frame ".concat(t),eV.Interrupted,e)}static unknownFrame(e){return new lt("Initial packet was never received.",eV.UnknownFrame,e)}static bufferFull(e){return new lt("Reorder buffer is full.",eV.BufferFull,e)}static incomplete(e,t,i){return new lt("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),eV.Incomplete,e)}}(W=eV||(eV={}))[W.Interrupted=0]="Interrupted",W[W.UnknownFrame=1]="UnknownFrame",W[W.BufferFull=2]="BufferFull",W[W.Incomplete=3]="Incomplete";class li{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case eq.Single:return this.frameFromSingle(e,t);case eq.Start:return this.beginPartial(e,t);case eq.Inter:case eq.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==eq.Single)throw Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));let n=null!=(i=null==t?void 0:t.maxPartialFrames)?i:1;if(this.partials.size>=n){let i=this.peekOldestPartialFrameNumber();if("number"!=typeof i)throw Error("Depacketizer.frameFromSingle: no olde
1st frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(i),null==t?void 0:t.throwOnInterruption)throw lt.interrupted(i,e.header.frameNumber.value);le.warn("Data track frame ".concat(i," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var i;if(e.header.marker!==eq.Start)throw Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));let n=e.header.sequence,r=e.header.frameNumber.value,a={startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},s=null!=(i=null==t?void 0:t.maxPartialFrames)?i:1;for(;this.partials.size>=s;){let e=this.peekOldestPartialFrameNumber();if("number"!=typeof e)break;if(this.partials.delete(e),null==t?void 0:t.throwOnInterruption)throw lt.interrupted(e,r);le.warn("Data track partials full (max ".concat(s,"), evicted oldest frame ").concat(e," to make room for new frame ").concat(r,"."))}return this.partials.set(r,a),null}pushToPartial(e){if(e.header.marker!==eq.Inter&&e.header.marker!==eq.Final)throw Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));let t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),lt.unknownFrame(t);if(i.payloads.size>=li.MAX_BUFFER_PACKETS)throw this.partials.delete(t),lt.bufferFull(t);return(i.payloads.has(e.header.sequence.value)&&le.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),i.payloads.set(e.header.sequence.value,e.payload),e.header.marker===eq.Final)?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){let n=t.payloads.size,r=0;for(let e of t.payloads.values())r+=e.length;let a=new Uint8Array(r),s=t.startSequence.clone(),o=0;for(;;){let n=t.payloads.get(s.value);if(!n)break;t.payloads.delete(s.value);let r=a.length-o;if(n.length>r)throw Error("Depacketizer.finalize: Expected at least ".concat(n.length," more bytes left in the payload buffer, only got ").concat(r," bytes."));if(a.set(n,o),o+=n.length,s.value!=i){s.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),lt.incomplete(e,n,i-t.startSequence.value+1)}}li.MAX_BUFFER_PACKETS=128,(z=eH||(eH={}))[z.Unpublished=0]="Unpublished",z[z.Timeout=1]="Timeout",z[z.Disconnected=2]="Disconnected",z[z.Cancelled=4]="Cancelled";class ln extends aZ{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=eH[t]}static unpublished(){return new ln("The track has been unpublished and is no longer available",eH.Unpublished)}static timeout(){return new ln("Request to subscribe to data track timed-out",eH.Timeout)}static disconnected(){return new ln("Cannot subscribe to data track when disconnected",eH.Disconnected)}static cancelled(){return new ln("Subscription to data track cancelled by caller",eH.Cancelled)}}let lr=rV(ec.DataTracks);class la{constructor(e){var t,i;const n=null!==e.e2eeManager;if(e.info.usesE2ee!==n)throw Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const r=new li;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=null!=(t=e.e2eeManager)?t:null,this.depacketizer=r,this.options=null!=(i=e.pipelineOptions)?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return rG(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,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(e){return lr.warn("Data frame depacketize error: ".concat(e)),null}return t}decryptIfNeeded(e){return rG(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 lr.error("Missing E2EE meta"),null;try{n=yield r.handleEncryptedData(e.payload,a.iv,this.publisherIdentity,a.keyIndex)}catch(e){return lr.error("Error decrypting packet: ".concat(e)),null}return e.payload=n.payload,e})}}let ls=rV(ec.DataTracks);class lo extends rX.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())
1)"active"===t.subscription.type&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let i=this.descriptors.get(e);i?(i.pipelineOptions=t,"active"===i.subscription.type&&i.subscription.pipeline.setOptions(t)):ls.warn("Unknown track ".concat(e,", cannot set pipeline options."))}openSubscriptionStream(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16,n=null,r=new sQ,a=this.descriptors.get(e),s=()=>{null==t||t.removeEventListener("abort",c)},o=()=>{(s(),n)?a&&this.descriptors.get(a.info.sid)===a?"active"!==a.subscription.type?ls.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):(a.subscription.streamControllers.delete(n),0===a.subscription.streamControllers.size&&this.unSubscribeRequest(a.info.sid)):ls.warn("Unknown track ".concat(e,", skipping cancel...")):ls.warn("ReadableStream subscribed to ".concat(e," was not started."))},c=()=>{var e;n&&((null==a?void 0:a.subscription.type)==="active"&&a.subscription.streamControllers.delete(n),n.error(ln.cancelled()),null==(e=r.reject)||e.call(r,ln.cancelled()),o())};return[new ReadableStream({start:i=>{n=i,this.subscribeRequest(e,t).then(()=>rG(this,void 0,void 0,function*(){var n,o,l;if(!a||this.descriptors.get(a.info.sid)!==a){ls.error("Unknown track ".concat(e));let t=ln.disconnected();i.error(t),null==(n=r.reject)||n.call(r,t);return}if("active"!==a.subscription.type){ls.error("Subscription for track ".concat(e," is not active"));let t=ln.disconnected();i.error(t),null==(o=r.reject)||o.call(r,t);return}(null==t?void 0:t.aborted)?c():(null==t||t.addEventListener("abort",c),a.subscription.streamControllers.set(i,s),null==(l=r.resolve)||l.call(r))})).catch(e=>{var t;i.error(e),null==(t=r.reject)||t.call(r,e)})},cancel:()=>{o()}},new CountQueuingStrategy({highWaterMark:i})),r.promise]}subscribeRequest(e,t){return rG(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)=>rG(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=cQ([i,n].filter(e=>void 0!==e)),a=new sQ;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,ln.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 sQ,pendingRequestCount:1,cancel:()=>{var e,t;let n=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:i.info.sid,subscribe:!1}),"pending"===n.type&&(null==(t=(e=n.completionFuture).reject)||t.call(e,r.aborted?ln.timeout():ln.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});let r=cY(1e4);yield n(i,t,r);return}case"pending":i.subscription.pendingRequestCount+=1,yield n(i,t);return;case"active":return}})}querySubscribed(){return rG(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 ls.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat(null==(t=i.subscription)?void 0:t.type));this.closeStreamControllers(i.subscription.streamControllers,e);let n=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let n of e){var i=tf(n,2);let e=i[0];(0,i[1])();try{e.close()}catch(e){ls.warn("Failed to close readable stream for track ".concat(t,": ").concat(e))}}}receiveSfuPublicationUpdates(e){return rG(this,void 0,void 0,function*(){if(0===e.size)return;let t=new Map;for(let n of e.entries()){var i=tf(n,2);let e=i[0],r=i[1],a=new Set;for(let t of r)a.add(t.sid),!this.descriptors.has(t.sid)&&(this.handleSidReassigned(e,t)||(yield this.handleTrackPublished(e,t)));t.set(e,a)}for(let e of t.entries()){var n=tf(e,2);let t=n[0],i=n[1];for(let e of Array.from(this.descriptors.entries()).filter(e=>{let i=tf(e,2);return i[0],i[1].publisherIdentity===t}).map(e=>tf(e,1)[0]).filter(e=>!i.has(e)))this.handleTrackUnpublished(e)}})}queryPublications(){return rG(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return rG(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid))return void ls.error("Existing descriptor for track ".concat(t.sid));let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);let n=new c5(i.info,this,{publisherIdentity:e});
1this.emit("trackPublished",{track:n})})}handleSidReassigned(e,t){let i=Array.from(this.descriptors.entries()).find(i=>{let n=tf(i,2);n[0];let r=n[1];return r.publisherIdentity===e&&r.info.pubHandle===t.pubHandle});if(!i)return!1;let n=tf(i,2),r=n[0],a=n[1],s=a.info,o=s.name,c=s.usesE2ee;if(o!==t.name||c!==t.usesE2ee)return ls.warn("Info mismatch for ".concat(r,", treating as new publication")),!1;let l=t.sid;if(ls.debug("SID reassigned: ".concat(r," -> ").concat(l)),!this.descriptors.delete(r))return!1;switch(a.info.sid=l,a.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:l,subscribe:!0})}return"active"===a.subscription.type&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,l),this.descriptors.set(l,a),!0}handleTrackUnpublished(e){let t=this.descriptors.get(e);t?(this.descriptors.delete(e),"active"===t.subscription.type&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})):ls.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(let i of e.entries()){var t=tf(i,2);let e=t[0],n=t[1];this.registerSubscriberHandle(e,n)}}registerSubscriberHandle(e,t){var i,n;let r=this.descriptors.get(t);if(!r)return void ls.error("Unknown track ".concat(t));switch(r.subscription.type){case"none":return void ls.warn("No subscription for ".concat(t));case"active":this.subscriptionHandles.delete(r.subscription.subcriptionHandle),r.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case"pending":{ls.debug("data track subscription activated",{sid:t,handle:e});let a=new la({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:r.pipelineOptions}),s=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),null==(n=(i=s.completionFuture).resolve)||n.call(i)}}}packetReceived(e){return rG(this,void 0,void 0,function*(){let t;try{var i=c7.fromBinary(e);t=tf(i,1)[0]}catch(e){ls.error("Failed to deserialize packet: ".concat(e));return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n)return void ls.warn("Unknown subscriber handle ".concat(t.header.trackHandle));let r=this.descriptors.get(n);if(!r)return void ls.error("Missing descriptor for track ".concat(n));if("active"!==r.subscription.type)return void ls.warn("Received packet for track ".concat(n," without active subscription"));let a=yield r.subscription.pipeline.processPacket(t);if(a)for(let e of r.subscription.streamControllers.keys()){if(null!==e.desiredSize&&e.desiredSize<=0){ls.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=c4.lossyIntoFrame(a);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let t of this.descriptors){var e=tf(t,2);let i=e[0];"none"!==e[1].subscription.type&&this.emit("sfuUpdateSubscription",{sid:i,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;case"pending":null==(i=(t=n.subscription.completionFuture).reject)||i.call(t,ln.disconnected());break;case"active":this.unSubscribeRequest(n.info.sid)}}reset(){var e,t;
1for(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,ln.disconnected())),"active"===i.subscription.type&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class lc extends aZ{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=eW[t]}static mtuTooShort(){return new lc("MTU is too short to send frame",eW.MtuTooShort)}}(G=eW||(eW={}))[G.MtuTooShort=0]="MtuTooShort";class ll{constructor(e,t){this.sequence=oT.u16(0),this.frameNumber=oT.u16(0),this.clock=oC.rtpStartingNow(oS.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?eq.Single:0===e?eq.Start:e===t-1?eq.Final:eq.Inter}*packetize(e,t){var i,n;let r=this.frameNumber.getThenIncrement(),a={marker:eq.Inter,trackHandle:this.handle,sequence:oT.u16(0),frameNumber:r,timestamp:null!=(i=null==t?void 0:t.now)?i:this.clock.now(),extensions:e.extensions},s=new c8(a).toBinaryLengthBytes();if(s>=this.mtuSizeBytes)throw lc.mtuTooShort();let o=this.mtuSizeBytes-s,c=Math.ceil(e.payload.byteLength/o);for(let t=0,i=0;i<e.payload.byteLength;t=(n=[t+1,i+o])[0],i=n[1]){let n=this.sequence.getThenIncrement(),r=new c8(Object.assign(Object.assign({},a),{marker:ll.computeFrameMarker(t,c),sequence:n})),s=Math.min(o,e.payload.byteLength-i),l=new Uint8Array(e.payload.buffer,e.payload.byteOffset+i,s);yield new c7(r,l)}}}(K=ez||(ez={}))[K.NotAllowed=0]="NotAllowed",K[K.DuplicateName=1]="DuplicateName",K[K.Timeout=2]="Timeout",K[K.LimitReached=3]="LimitReached",K[K.Disconnected=4]="Disconnected",K[K.Cancelled=5]="Cancelled",K[K.InvalidName=6]="InvalidName",K[K.Unknown=7]="Unknown";class ld extends aZ{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=ez[t],this.rawMessage=null==i?void 0:i.rawMessage}static notAllowed(e){return new ld("Data track publishing unauthorized",ez.NotAllowed,{rawMessage:e})}static duplicateName(e){return new ld("Track name already taken",ez.DuplicateName,{rawMessage:e})}static invalidName(e){return new ld("Track name is invalid",ez.InvalidName,{rawMessage:e})}static timeout(){return new ld("Publish data track timed-out. Does the LiveKit server support data tracks?",ez.Timeout)}static limitReached(e){return new ld("Data track publication limit reached",ez.LimitReached,{rawMessage:e})}static unknown(e,t){return new ld("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),ez.Unknown)}static disconnected(){return new ld("Room disconnected",ez.Disconnected)}static cancelled(){return new ld("Publish data track cancelled by caller",ez.Cancelled)}}(J=eG||(eG={}))[J.TrackUnpublished=0]="TrackUnpublished",J[J.Dropped=1]="Dropped";class lu extends aZ{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=eG[t]}static trackUnpublished(){return new lu("Track is no longer published",eG.TrackUnpublished)}static dropped(e){return new lu("Frame was dropped",eG.Dropped,{cause:e})}}(Q=eK||(eK={}))[Q.Packetizer=0]="Packetizer",Q[Q.Encryption=1]="Encryption";class lh extends aZ{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=eK[t]}static packetizer(e){return new lh("Error packetizing frame",eK.Packetizer,{cause:e})}static encryption(e){return new lh("Error encrypting frame",eK.Encryption,{cause:e})}}class lp{constructor(e,t){this.trackSymbol=c9,this.isLocal=!0,this.typeSymbol=c6,this.handle=null,this.log=rq,this.flushedFuture=new sQ,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;null==(t=(e=this.flushedFuture).resolve)||t.call(e),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,i;this.isFlushed=e.isFlushed,e.isFlushed&&(null==(i=(t=this.flushedFuture).resolve)||i.call(t),this.flushedFuture=new sQ)},this.options=e,this.manager=t,this.log=rV(ec.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){let n=new lp(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 rG(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 lu.trackUnpublished();let t=c4.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}flush(){return rG(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return rG(this,void 0,void 0,function*(){if(!this.handle)return void rq.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 lm{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new ll(e.info.pubHandle,lm.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return rJ(this,arguments,function*(){let t=yield rK(this.encryptIfNeeded(e));try{yield rK((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:rK(e[n](t)),done:!1}:r?r(t):t}:r}}(rQ(this.packetizer.packetize(t)))))}catch(e){if(e instanceof lc)throw lh.packetizer(e);throw e}})}encryptIfNeeded(e){return rG(this,void 0,void 0,function*(){let t;if(!this.e2eeManager)return e;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw lh.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new c2(t.keyIndex,t.iv),e})}}lm.TRANSPORT_MTU_BYTES=16e3;let lg=rV(ec.DataTracks);class lf extends rX.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new oP,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=null!=(t=null==e?void 0:e.e2eeManager)?t:null}static withDescriptors(e){let t=new lf;return t.descriptors=e,t}updateE2eeManager(e){for(let t of(this.e2eeManager=e,this.descriptors.values())
1)"active"===t.type&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return null!=(t=this.descriptors.get(e))?t:null}tryProcessAndSend(e,t){return rG(this,void 0,void 0,function*(){let i=this.getDescriptor(e);if((null==i?void 0:i.type)!=="active"||"unpublished"===i.publishState)throw lu.trackUnpublished();if("republishing"===i.publishState)throw lu.dropped("Data track republishing");try{try{for(var n,r,a,s,o,c,l=!0,d=rQ(i.pipeline.processFrame(t));!(n=(c=yield d.next()).done);l=!0){s=c.value,l=!1;let t=null!=(o=this.inFlightPacketCounter.get(e))?o:0;this.inFlightPacketCounter.set(e,t+1),0===t&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:s.toBinary()})}}catch(e){r={error:e}}finally{try{!l&&!n&&(a=d.return)&&(yield a.call(d))}finally{if(r)throw r.error}}}catch(e){throw lu.dropped(e)}})}handlePacketSendComplete(e){var t;let i=(null!=(t=this.inFlightPacketCounter.get(e))?t:0)-1;i<0&&(lg.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),i=0),this.inFlightPacketCounter.set(e,i),0===i&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return rG(this,void 0,void 0,function*(){let i=this.handleAllocator.get();if(!i)throw ld.limitReached();let n=cY(1e4),r=t?cQ([t,n]):n;if(this.descriptors.has(i))throw Error("Descriptor for handle already exists");let a={type:"pending",completionFuture:new sQ};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?ld.timeout():ld.cancelled()))):lg.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:lp.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>"active"===e.type).map(e=>e.info)}unpublishRequest(e){return rG(this,void 0,void 0,function*(){let t=this.descriptors.get(e);t?"active"!==t.type?lg.warn("Track ".concat(e," not active")):(this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})):lg.warn("No descriptor for ".concat(e))})}receivedSfuPublishResponse(e,t){var i,n,r,a;let s=this.descriptors.get(e);if(!s)return void lg.warn("No descriptor for ".concat(e));switch(this.descriptors.delete(e),s.type){case"pending":if("ok"===t.type){let r,a=t.data;lg.debug("SFU accepted publish request for handle ".concat(e),{sid:a.sid});let o=a.usesE2ee?this.e2eeManager:null;this.descriptors.set(a.pubHandle,(r=a,{type:"active",info:r,publishState:"published",pipeline:new lm({info:r,e2eeManager:o}),unpublishingFuture:new sQ})),null==(n=(i=s.completionFuture).resolve)||n.call(i)}else lg.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),null==(a=(r=s.completionFuture).reject)||a.call(r,t.error);return;case"active":if("republishing"!==s.publishState)return void lg.warn("Track ".concat(e," already active"));if("error"===t.type)return void lg.warn("Republish failed for track ".concat(e));lg.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)?lg.warn("Track ".concat(e," not active")):(n.publishState="unpublished",null==(i=(t=n.unpublishingFuture).resolve)||i.call(t)):lg.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(let n of this.descriptors.entries()){var i=tf(n,2);let r=i[0],a=i[1];switch(a.type){case"pending":this.descriptors.delete(r),null==(t=(e=a.completionFuture).reject)||t.call(e,ld.disconnected());break;
1case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return rG(this,void 0,void 0,function*(){var e,t,i,n;for(let r of(this.handleAllocator.reset(),this.descriptors.values()))switch(r.type){case"pending":null==(t=(e=r.completionFuture).reject)||t.call(e,ld.disconnected());break;case"active":null==(n=(i=r.unpublishingFuture).resolve)||n.call(i),yield this.unpublishRequest(r.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}}class lv extends Error{constructor(e,t,i,n){super(t),this.code=e,this.message=lT(t,lv.MAX_MESSAGE_BYTES),this.data=i?lT(i,lv.MAX_DATA_BYTES):void 0,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}static fromProto(e){return new lv(e.code,e.message,e.data)}toProto(){return new i1({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new lv(lv.ErrorCode[e],lv.ErrorMessage[e],t,i)}}lv.MAX_MESSAGE_BYTES=256,lv.MAX_DATA_BYTES=15360,lv.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},lv.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 lk="lk.rpc_request",lb="lk.rpc_response";function ly(e){return new TextEncoder().encode(e).length}function lT(e,t){if(ly(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)}(Y=eJ||(eJ={})).RPC_REQUEST_ID="lk.rpc_request_id",Y.RPC_REQUEST_METHOD="lk.rpc_request_method",Y.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",Y.RPC_REQUEST_VERSION="l
1k.rpc_request_version";class lS extends rX.EventEmitter{constructor(e,t,i,n){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=n}performRpc(e){return rG(this,arguments,void 0,function(e){var t=this;let i=e.destinationIdentity,n=e.method,r=e.payload,a=e.responseTimeout,s=void 0===a?15e3:a;return function*(){let e=t.getRemoteParticipantClientProtocol(i);if(ly(r)>15360&&e<1)throw lv.builtIn("REQUEST_PAYLOAD_TOO_LARGE");let a=t.getServerVersion();if(a&&0>sj(a,"1.8.0"))throw lv.builtIn("UNSUPPORTED_SERVER");let o=Math.max(s,8e3),c=crypto.randomUUID(),l=new sQ,d=null,u=setTimeout(()=>{var e;t.pendingAcks.delete(c),null==(e=l.reject)||e.call(l,lv.builtIn("CONNECTION_TIMEOUT")),t.pendingResponses.delete(c),null!==d&&clearTimeout(d)},7e3);t.pendingAcks.set(c,{resolve:()=>{clearTimeout(u)},participantIdentity:i}),t.pendingResponses.set(c,{completionFuture:l,participantIdentity:i}),yield t.publishRpcRequest(i,c,n,r,o,e),d=setTimeout(()=>{var e;t.pendingResponses.delete(c),null==(e=l.reject)||e.call(l,lv.builtIn("RESPONSE_TIMEOUT"))},s);let h=l.promise.finally(()=>{clearTimeout(d),t.pendingAcks.has(c)&&(t.log.warn("RPC response received before ack",c),t.pendingAcks.delete(c),clearTimeout(u))});return[c,h]}()})}publishRpcRequest(e,t,i,n,r,a){return rG(this,void 0,void 0,function*(){a>=1?yield this.outgoingDataStreamManager.sendText(n,{topic:lk,destinationIdentities:[e],attributes:{[eJ.RPC_REQUEST_ID]:t,[eJ.RPC_REQUEST_METHOD]:i,[eJ.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[eJ.RPC_REQUEST_VERSION]:"".concat(2)}}):this.emit("sendDataPacket",{packet:new iq({destinationIdentities:[e],kind:iV.RELIABLE,value:{case:"rpcRequest",value:new iZ({id:t,method:i,payload:n,responseTimeoutMs:r,version:1})}})})})}handleIncomingDataStream(e,t,i){return rG(this,void 0,void 0,function*(){let n,r=i[eJ.RPC_REQUEST_ID];if(!r)return void this.log.warn("RPC data stream malformed: ".concat(eJ.RPC_REQUEST_ID," not set."));let a=this.pendingResponses.get(r);if(a&&a.participantIdentity!==t)return void this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(a.participantIdentity,". Ignoring."));try{n=yield e.readAll()}catch(e){this.log.warn("Error reading RPC response payload: ".concat(e)),this.handleIncomingRpcResponseFailure(r,lv.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:e}));return}this.handleIncomingRpcResponseSuccess(r,n)})}handleIncomingRpcResponseSuccess(e,t){var i,n;let r=this.pendingResponses.get(e);r?(null==(n=(i=r.completionFuture).resolve)||n.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,n;let r=this.pendingResponses.get(e);r?(null==(n=(i=r.completionFuture).reject)||n.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(let t of this.pendingAcks){var i=tf(t,2);let n=i[0];i[1].participantIdentity===e&&this.pendingAcks.delete(n)}for(let i of this.pendingResponses){var n=tf(i,2);let a=n[0];var r=n[1];let s=r.participantIdentity,o=r.completionFuture;s===e&&(null==(t=o.reject)||t.call(o,lv.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(a))}}}class lC extends rX.EventEmitter{constructor(e,t,i){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i}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)}handleIncomingRpcRequest(e,t){return rG(this,void 0,void 0,function*(){var i;let n;if(this.publishRpcAck(e,t.id),1!==t.version)return void this.publishRpcResponsePacket(e,t.id,null,lv.builtIn("UNSUPPORTED_VERSION"));let r=this.rpcHandlers.get(t.method);if(!r)return void this.publishRpcResponsePacket(e,t.id,null,lv.builtIn("UNSUPPORTED_METHOD"));try{n=yield r({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(r){let n;r instanceof lv?n=r:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),r),n=lv.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!=(i=null==r?void 0:r.message)?i:r),{cause:r})),this.publishRpcResponsePacket(e,t.id,null,n);return}yield this.publishRpcResponse(e,t.id,null!=n?n:"")})}handleIncomingDataStream(e,t,i){return rG(this,void 0,void 0,function*(){let n,r,a=i[eJ.RPC_REQUEST_ID],s=i[eJ.RPC_REQUEST_METHOD],o=parseInt(i[eJ.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),c=parseInt(i[eJ.RPC_REQUEST_VERSION],10);if(!a||!s||Number.isNaN(o)||Number.isNaN(c)){this.log.warn("RPC data stream malformed: ".concat(eJ.RPC_REQUEST_ID," / ").concat(eJ.RPC_REQUEST_METHOD," / ").concat(eJ.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(eJ.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,a,null,lv.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,a),2!==c)return void this.publishRpcResponsePacket(t,a,null,lv.builtIn("UNSUPPORTED_VERSION"));
1try{n=yield e.readAll()}catch(e){this.log.warn("Error reading RPC request payload: ".concat(e)),this.publishRpcResponsePacket(t,a,null,lv.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:e}));return}let l=this.rpcHandlers.get(s);if(!l)return void this.publishRpcResponsePacket(t,a,null,lv.builtIn("UNSUPPORTED_METHOD"));try{r=yield l({requestId:a,callerIdentity:t,payload:n,responseTimeout:o})}catch(i){let e;i instanceof lv?e=i:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),i),e=lv.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,a,null,e);return}yield this.publishRpcResponse(t,a,null!=r?r:"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new iq({destinationIdentities:[e],kind:iV.RELIABLE,value:{case:"rpcAck",value:new i$({requestId:t})}})})}publishRpcResponsePacket(e,t,i,n){this.emit("sendDataPacket",{packet:new iq({destinationIdentities:[e],kind:iV.RELIABLE,value:{case:"rpcResponse",value:new i0({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}})})}publishRpcResponse(e,t,i){return rG(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=1)return void(yield this.outgoingDataStreamManager.sendText(i,{topic:lb,destinationIdentities:[e],attributes:{[eJ.RPC_REQUEST_ID]:t}}));if(ly(i)>15360){this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),this.publishRpcResponsePacket(e,t,null,lv.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,i,null)})}}class lE extends od{constructor(e,t,i,n,r,a){super(e,t,sb.Kind.Audio,i,a),this.monitorReceiver=()=>rG(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=ol(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;sN()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(sN())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return rG(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(sP(t))return t.setSinkId(e)}))})}attach(e){let t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&sP(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(ek.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(ek.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 rG(this,void 0,void 0,function*(){let e;if(this.receiver&&this.receiver.getStats)return(yield this.receiver.getStats()).forEac
1h(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 lw extends rX.EventEmitter{constructor(e,t,i,n){var r;super(),this.metadataMuted=!1,this.encryption=iP.NONE,this.log=rq,this.handleMuted=()=>{this.emit(ek.Muted)},this.handleUnmuted=()=>{this.emit(ek.Unmuted)},this.log=rV(null!=(r=null==n?void 0:n.loggerName)?r:ec.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=sb.Source.Unknown}setTrack(e){this.track&&(this.track.off(ek.Muted,this.handleMuted),this.track.off(ek.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ek.Muted,this.handleMuted),e.on(ek.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),sg(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==iP.NONE}get audioTrack(){if(s3(this.track))return this.track}get videoTrack(){if(s4(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=sb.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===sb.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}))}}(Z=(X=lw||(lw={})).SubscriptionStatus||(X.SubscriptionStatus={})).Desired="desired",Z.Subscribed="subscribed",Z.Unsubscribed="unsubscribed",($=X.PermissionStatus||(X.PermissionStatus={})).Allowed="allowed",$.NotAllowed="not_allowed";class lR extends lw{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(ek.Ended)},this.handleCpuConstrained=()=>{this.track&&s4(this.track)&&this.emit(ek.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(ek.Ended,this.handleTrackEnded),this.track.off(ek.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ek.Ended,this.handleTrackEnded),e.on(ek.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 rG(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.mute()})}unmute(){return rG(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.unmute()})}pauseUpstream(){return rG(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.pauseUpstream()})}resumeUpstream(){return rG(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(!s3(this.track))return[];{let t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ik.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ik.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ik.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ik.TF_STEREO),(null==(e=this.options)?void 0:e.dtx)||i.add(ik.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ik.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}}}function lP(e,t){return rG(this,void 0,void 0,function*(){null!=e||(e={});let i=!1,n=sf(e),r=n.audioProcessor,a=n.videoProcessor,s=n.optionsWithoutProcessor,o=s.audio,c=s.video;if(r&&"object"==typeof s.audio&&(s.audio.processor=r),a&&"object"==typeof s.video&&(s.video.processor=a),e.audio&&"object"==typeof s.audio&&"string"==typeof s.audio.deviceId){let e=s.audio.deviceId;s.audio.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:e}})}if(s.video&&"object"==typeof s.video&&"string"==typeof s.video.deviceId){let e=s.video.deviceId;s.video.deviceId={exact:e},i=!0,c=Object.assign(Object.assign({},s.video),{deviceId:{ideal:e}})}!0===s.audio?s.audio={deviceId:"default"}:"object"==typeof s.audio&&null!==s.audio&&(s.audio=Object.assign(Object.assign({},s.audio),{deviceId:s.audio.deviceId||"default"})),!0===s.video?s.video={deviceId:"default"}:"object"!=typeof s.video||s.video.deviceId||(s.video.deviceId="default");let l=sd(sc(s,oQ,oY)),d=navigator.mediaDevices.getUserMedia(l);
1s.audio&&(oy.userMediaPromiseMap.set("audioinput",d),d.catch(()=>oy.userMediaPromiseMap.delete("audioinput"))),s.video&&(oy.userMediaPromiseMap.set("videoinput",d),d.catch(()=>oy.userMediaPromiseMap.delete("videoinput")));try{let e=yield d;return yield Promise.all(e.getTracks().map(i=>rG(this,void 0,void 0,function*(){let n,s="audio"===i.kind?l.audio:l.video;"boolean"!=typeof s&&(n=s);let o=i.getSettings().deviceId;(null==n?void 0:n.deviceId)&&sX(n.deviceId)!==o?n.deviceId=o:n||(n={deviceId:o});let c=function(e,t,i){switch(e.kind){case"audio":return new cn(e,t,!1,void 0,i);case"video":return new cf(e,t,!1,i);default:throw new a1("unsupported track type: ".concat(e.kind))}}(i,n,t);return c.kind===sb.Kind.Video?c.source=sb.Source.Camera:c.kind===sb.Kind.Audio&&(c.source=sb.Source.Microphone),c.mediaStream=e,s3(c)&&r?yield c.setProcessor(r):s4(c)&&a&&(yield c.setProcessor(a)),c})))}catch(n){if(!i)throw n;return lP(Object.assign(Object.assign({},e),{audio:o,video:c}),t)}})}(ee=eQ||(eQ={})).Excellent="excellent",ee.Good="good",ee.Poor="poor",ee.Lost="lost",ee.Unknown="unknown";class lI extends rX.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===iw.AGENT}get isActive(){var e;return(null==(e=this.participantInfo)?void 0:e.state)===iE.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]:iw.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=eQ.Unknown,this.log=rq,this.loggerOptions=a,this.log=rV(null!=(s=null==a?void 0:a.loggerName)?s:ec.Participant,()=>this.logContext),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){let i=tf(t,2)[1];if(i.source===e)return i}}getTrackPublicationByName(e){for(let t of this.trackPublications){let i=tf(t,2)[1];if(i.trackName===e)return i}}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new sQ,this.once(ef.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(sb.Source.Camera);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(sb.Source.Microphone);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(sb.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===iE.ACTIVE&&(null==(t=this.participantInfo)?void 0:t.state)!==iE.ACTIVE&&this.emit(ef.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(ef.ParticipantMetadataChanged,i)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(ef.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>
10&&this.emit(ef.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(ef.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ef.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case ih.EXCELLENT:return eQ.Excellent;case ih.GOOD:return eQ.Good;case ih.POOR:return eQ.Poor;case ih.LOST:return eQ.Lost;default:return eQ.Unknown}}(e),t!==this._connectionQuality&&this.emit(ef.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=>s3(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(this.log.debug("adding track publication",{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(ek.Muted,()=>{this.emit(ef.TrackMuted,e)}),e.on(ek.Unmuted,()=>{this.emit(ef.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case sb.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case sb.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class l_ extends lI{constructor(e,t,i,n,r,a,s,o){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=iP.NONE,this.e2eeStateMutex=new e1,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sQ)},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)),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 sQ),null==(i=(t=this.signalConnectedFuture).resolve)||i.call(t)},this.handleSignalRequestResponse=e=>{let t=e.requestId,i=e.reason,n=e.message,r=this.pendingSignalRequests.get(t);if(r&&(i!==rD.OK&&r.reject(new a5(n,i)),this.pendingSignalRequests.delete(t)),"publishDataTrack"===e.request.case){let t;switch(e.reason){case rD.NOT_ALLOWED:t=ld.notAllowed(e.message);break;case rD.DUPLICATE_NAME:t=ld.duplicateName(e.message);break;case rD.INVALID_NAME:t=ld.invalidName(e.message);break;case rD.LIMIT_EXCEEDED:t=ld.limitReached(e.message);break;default:t=ld.unknown(e.reason,e.message)}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:"error",error:t})}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{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 rv({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",sg(e))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",sg(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>
1{this.log.debug("upstream resumed",sg(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.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",sg(t)),this.emit(ef.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>rG(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",{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=rQ(i);!(n=(c=yield d.next()).done);l=!0)s=c.value,l=!1,sr(s)&&(this.log.debug("publish ".concat(s," for ").concat(t.videoTrack.sid),sg(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",{trackSid:e.trackSid})},this.handleTrackEnded=e=>rG(this,void 0,void 0,function*(){if(e.source===sb.Source.ScreenShare||e.source===sb.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",sg(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();
1else if(s6(e)||s9(e))try{if(sA())try{let t=yield null==navigator?void 0:navigator.permissions.query({name:e.source===sb.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),sg(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",sg(e)),s6(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",sg(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.roomOutgoingDataStreamManager=r,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=s,this.rpcServerManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==iP.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(ev.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(ev.Connected,this.handleReconnected).on(ev.SignalConnected,this.handleSignalConnected).on(ev.SignalRestarted,this.handleReconnected).on(ev.SignalResumed,this.handleReconnected).on(ev.Restarting,this.handleReconnecting).on(ev.Resuming,this.handleReconnecting).on(ev.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ev.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ev.Closing,this.handleClosing).on(ev.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return rG(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return rG(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return rG(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return rG(this,arguments,void 0,function(e){var t=this;let i=e.metadata,n=e.name,r=e.attributes;return function*(){return new az((e,a)=>rG(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},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=tf(e,2),i=t[0],n=t[1];return this.attributes[i]===n||""===n&&!this.attributes[i]}))){this.pendingSignalRequests.delete(c),e();return}yield sC(50)}a(new a5("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(sb.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(sb.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(sb.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return rG(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?iP.GCM:iP.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 rG(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",{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",{source:e}),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case sb.Source.Camera:t=yield this.createTracks({video:null==i||i});break;case sb.Source.Microphone:t=yield this.createTracks({audio:null==i||i});break;case sb.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new a1(e)}}
1catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(ef.MediaDevicesError,i,sp(e)),this.pendingPublishing.delete(e),i}for(let n of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===sb.Source.Microphone&&s3(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),n.startPreConnectBuffer())}try{let e=[];for(let i of t)this.log.info("publishing track",sg(i)),e.push(this.publishTrack(i,n));let i=yield Promise.all(e);r=tf(i,1)[0]}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",{source:e})),r&&r.track)if(e===sb.Source.ScreenShare){let e=[this.unpublishTrack(r.track)],t=this.getTrackPublication(sb.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),r=tf((yield Promise.all(e)),1)[0]}else yield r.mute();return r})}enableCameraAndMicrophone(){return rG(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(sb.Source.Camera)||this.pendingPublishing.has(sb.Source.Microphone))){this.pendingPublishing.add(sb.Source.Camera),this.pendingPublishing.add(sb.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(sb.Source.Camera),this.pendingPublishing.delete(sb.Source.Microphone)}}})}createTracks(e){return rG(this,void 0,void 0,function*(){var t,i;null!=e||(e={});let n=sc(e,null==(t=this.roomOptions)?void 0:t.audioCaptureDefaults,null==(i=this.roomOptions)?void 0:i.videoCaptureDefaults);try{return(yield lP(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(s3(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=sb.Source.Microphone,this.emit(ef.AudioStreamAcquired)),s4(e)&&(this.cameraError=void 0,e.source=sb.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return rG(this,void 0,void 0,function*(){var t,i,n;let r,a;if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new a0("getDisplayMedia not supported");void 0!==e.resolution||(null==(r=aK())?void 0:r.name)==="Safari"&&r.version.startsWith("17.")||(null==r?void 0:r.os)==="iOS"&&(null==r?void 0:r.osVersion)&&sj(r.osVersion,"17")>=0||(e.resolution=so.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=sM()?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 a1("no video track found");let l=new cf(c[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});l.source=sb.Source.ScreenShare,e.contentHint&&(l.mediaStreamTrack.contentHint=e.contentHint);let d=[l];if(o.getAudioTracks().length>0){this.emit(ef.AudioStreamAcquired);let e=new cn(o.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=sb.Source.ScreenShareAudio,d.push(e)}return d})}publishTrack(e,t){return rG(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;return new Promise((t,i)=>{let n=()=>{clearTimeout(s),this.engine.off(ev.Restarted,r),this.engine.off(ev.Closing,a)},r=()=>{n(),t()},a=()=>{n(),i(Error("engine closed before restart completed"))},s=setTimeout(()=>{n(),i(Error("timed out waiting for engine restart"))},e);this.engine.once(ev.Restarted,r),this.engine.once(ev.Closing,a)})}publishOrRepublishTrack(e,t){return rG(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return function*(){var a,s;let o,c;if(s6(e)&&e.setAudioContext(i.audioContext),yield null==(a=i.reconnectFuture)?void 0:a.promise,i.republishPromise&&!n&&(yield i.republishPromise),s2(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)o=e.getConstraints();else{let t;switch(o=e.constraints,e.source){case sb.Source.Microphone:t="audioinput";break;case sb.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(o=Object.assign(Object.assign({},o),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new cn(e,o,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new cf(e,o,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new a1("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&&(c=t)}),c)return i.log.warn("track has already been published, skipping",sg(c)),c;let l=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),d="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!=(s=l.forceStereo)?s:d;u&&(void 0===l.dtx&&i.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",sg(e)),void 0===l.red&&i.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!=l.dtx||(l.dtx=!1),null!=l.red||(l.red=!1)),!function(){let e=aK(),t="17.2";if(e)if("Safari"!==e.name&&"iOS"!==e.os)return!0;else if("iOS"===e.os&&e.osVersion&&sj(e.osVersion,t)>=0)return!0;else if("Safari"===e.name&&sj(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"),l.simulcast=!1),l.source&&(e.source=l.source);let h=new Promise((t,n)=>rG(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==e_.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:sg(e)});let i=!1,r=setTimeout(()=>{i=!0,e.stop(),n(new a6("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),i)return;let a=yield this.publish(e,l,u);t(a)}else try{let i=yield this.publish(e,l,u);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,h);try{return yield h}catch(a){if(!r&&a instanceof a4)return i.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:a}),i.pendingPublishPromises.delete(e),yield i.waitForNextEngineRestart(),yield i.publishOrRepublishTrack(e,t,n,!0);throw a}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new sQ),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",sg(e)),!1;let t=this.permissions,i=t.canPublish,n=t.canPublishSources;return!!(i&&(0===n.length||n.map(e=>(function(e){switch(e){case id.CAMERA:return sb.Source.Camera;case id.MICROPHONE:return sb.Source.Microphone;case id.SCREEN_SHARE:return sb.Source.ScreenShare;case id.SCREEN_SHARE_AUDIO:return sb.Source.ScreenShareAudio;default:return sb.Source.Unknown}})(e)).includes(e.source)))||(this.log.warn("insufficient permissions to publish",sg(e)),!1)}publish(e,t,i){return rG(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 a6("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>s2(e)&&t.source===e.source)&&e.source!==sb.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),sg(e)),t.stopMicTrackOnMute&&s3(e)&&(e.stopOnMute=!0),e.source===sb.Source.ScreenShare&&sI()&&(t.simulcast=!1),"av1"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||sM()||sI())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)||sI())return!1;if(sM()){let e=aK();if((null==e?void 0:e.version)&&0>sj(e.version,"16")||(null==e?void 0:e.os)==="iOS"&&(null==e?void 0:e.osVersion)&&0>sj(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===sm(e.mime))&&(t.videoCodec=sm(this.enabledPublishVideoCodecs[0].mime));let g=t.videoCodec;e.on(ek.Muted,this.onTrackMuted),e.on(ek.Unmuted,this.onTrackUnmuted),e.on(ek.Ended,this.handleTrackEnded),e.on(ek.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ek.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ek.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let f=[],v=!(null==(n=t.dtx)||n),k=e.getSourceTrackSettings();k.autoGainControl&&f.push(ik.TF_AUTO_GAIN_CONTROL),k.echoCancellation&&f.push(ik.TF_ECHO_CANCELLATION),k.noiseSuppression&&f.push(ik.TF_NOISE_SUPPRESSION),k.channelCount&&k.channelCount>
11&&f.push(ik.TF_STEREO),v&&f.push(ik.TF_NO_DTX),s6(e)&&e.hasPreConnectBuffer&&f.push(ik.TF_PRECONNECT_BUFFER);let b=this.normalizeRequestedFrameMetadataOptions(e,t),y=new nq({cid:e.mediaStreamTrack.id,name:t.name,type:sb.kindToProto(e.kind),muted:e.isMuted,source:sb.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,packetTrailerFeatures:b});if(e.kind===sb.Kind.Video){let i;try{i=yield e.waitForDimensions()}catch(n){let t=null!=(s=null==(a=this.roomOptions.videoCaptureDefaults)?void 0:a.resolution)?s:sa.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},sg(e)),{dims:i}))}y.width=i.width,y.height=i.height,s9(e)&&(sR(g)&&(e.source===sb.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",sg(e)))),t.scalabilityMode=null!=(o=t.scalabilityMode)?o:"L3T3_KEY"),y.simulcastCodecs=[new nj({codec:g,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:"vp8"}),t.backupCodec&&g!==t.backupCodec.codec&&y.encryption===iP.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),y.simulcastCodecs.push(new nj({codec:t.backupCodec.codec,cid:""})))),p=cd(e.source===sb.Source.ScreenShare,y.width,y.height,t),y.layers=cb(y.width,y.height,p,sR(t.videoCodec))}else e.kind===sb.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 a3("cannot publish track when not connected");let T=()=>rG(this,void 0,void 0,function*(){var i,n,r;if(!this.engine.pcManager)throw new a3("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,p),s9(e)&&(e.publishOptions=t),this.emit(ef.LocalSenderCreated,e.sender,e),s9(e)&&(null!=t.degradationPreference||(t.degradationPreference=function(e){switch(e.source){case sb.Source.Camera:return"maintain-framerate";case sb.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}(e)),e.setDegradationPreference(t.degradationPreference)),p){if(sI()&&e.kind===sb.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 if(e.codec&&sY(e.codec)){let t=sR(e.codec)?null!=(r=null==(n=p[0])?void 0:n.maxBitrate)?r:0:p.reduce((e,t)=>{var i;return e+(null!=(i=t.maxBitrate)?i:0)},0);t>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:y.cid,codec:e.codec,maxbr:t/1e3,isScreenShare:e.source===sb.Source.ScreenShare})}}yield this.engine.negotiate()}),S=new Promise((t,i)=>rG(this,void 0,void 0,function*(){var n;try{m=yield this.engine.addTrack(y),t(m)}catch(t){if(e.sender&&(null==(n=this.engine.pcManager)?void 0:n.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(e){this.log.error(e)}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({},sg(e)),{error:t}))})}i(t)}}));if(this.enabledPublishVideoCodecs.length>0&&0===b.length)m=(yield Promise.all([S,T()]))[0];else{let i;if((m=yield S).codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===sb.Kind.Video){let n=sm(i);n!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},sg(e)),{codec:n})),t.videoCodec=n,p=cd(e.source===sb.Source.ScreenShare,y.width,y.height,t))}yield T()}let C=new lR(e.kind,m,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(ek.CpuConstrained,e=>this.onTrackCpuConstrained(e,C)),C.options=t,e.sid=m.sid,s9(e)&&(e.publishOptions=t,y.width&&y.height&&(e.lastEncodedDimensions={width:y.width,height:y.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:p,trackInfo:m}),s9(e)?e.startMonitor(this.engine.client):s6(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit
1(ef.LocalTrackPublished,C),s6(e)&&m.audioFeatures.includes(ik.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();this.on(ef.LocalTrackSubscribed,t=>{if(t.trackSid===m.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed");this.log.debug("finished recording preconnect buffer",sg(e)),e.stopPreConnectBuffer()}}),t&&new Promise((n,r)=>rG(this,void 0,void 0,function*(){try{this.log.debug("waiting for agent",sg(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",sg(e));let f=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:C.trackSid,sampleRate:String(null!=(l=k.sampleRate)?l:"48000"),channels:String(null!=(d=k.channelCount)?d:"1")}});try{for(var a,s,o,c,l,d,u,h=!0,p=rQ(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",sg(e))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},sg(e)),{error:t}))})}return C})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||os(null!=(e=this.roomOptions.frameMetadata)?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var i;let n,r=null!=(i=t.frameMetadata)?i:t.packetTrailer;if(e.kind!==sb.Kind.Video||!oo(r))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),sg(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];let a=(n=[],(null==r?void 0:r.timestamp)&&n.push(ib.PTF_USER_TIMESTAMP),(null==r?void 0:r.frameId)&&n.push(ib.PTF_FRAME_ID),n),s=function(e){if(!e||0===e.length)return;let t={};return e.includes(ib.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(ib.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}(a);return t.frameMetadata=s,t.packetTrailer=s,a}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return rG(this,void 0,void 0,function*(){var n;let r;if(this.encryptionType!==iP.NONE)return;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new a1("track is not published");if(!s9(e))throw new a1("track is not a video track");let a=Object.assign(Object.assign({},null==(n=this.roomOptions)?void 0:n.publishDefaults),i),s=cu(e,t,a);if(!s)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",sg(e));let o=e.addSimulcastTrack(t,s);if(!o)return;let c=this.normalizeRequestedFrameMetadataOptions(e,a),l=new nq({cid:o.mediaStreamTrack.id,type:sb.kindToProto(e.kind),muted:e.isMuted,source:sb.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:o.mediaStreamTrack.id}]});if(l.layers=cb(l.width,l.height,s),!this.engine||this.engine.isClosed)throw new a3("cannot publish track when not connected");let d=()=>rG(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,a,s),yield this.engine.negotiate()}),u=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:s,trackInfo:u})})}unpublishTrack(e,t){return rG(this,void 0,void 0,function*(){var i,n;if(s2(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.debug("awaiting publish promise before attempting to unpublish",sg(e)),yield t)}let r=this.getPublicationForTrack(e),a=r?sg(r):void 0;if(this.log.info("unpublishing track",a),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",a);(e=r.track).off(ek.Muted,this.onTrackMuted),e.off(ek.Unmuted,this.onTrackUnmuted),e.off(ek.Ended,this.handleTrackEnded),e.off(ek.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ek.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ek.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<eL.FAILED&&o)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",s=!0);try{s=this.engine.removeTrack(o)}catch(e){this.log.warn(e),s=!0}if(s9(e)){for(let t of e.simulcastCodecs){let e=tf(t,2)[1];if(e.sender){try{s=this.engine.removeTrack(e.sender)}catch(e){this.log.warn(e),s=!0}e.sender=void 0}}e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case sb.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case sb.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}
vendor: 3,201 bytes, line 1
1return this.emit(ef.LocalTrackUnpublished,r),r.setTrack(void 0),s&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return rG(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return rG(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 az((n,r)=>rG(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=>rG(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==sb.Source.ScreenShare&&t.source!==sb.Source.ScreenShareAudio&&(s6(t)||s9(t))&&!t.isUserProvided&&(this.log.debug("restarting existing track",{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 rG(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?ex.RELIABLE:ex.LOSSY,r=i.reliable?iV.RELIABLE:iV.LOSSY,a=i.destinationIdentities,s=i.topic,o=new iq({kind:r,value:{case:"user",value:new iK({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:s})}});yield t.engine.sendDataPacket(o,n)}()})}publishDtmf(e,t){return rG(this,void 0,void 0,function*(){let i=new iq({kind:iV.RELIABLE,value:{case:"sipDtmf",value:new iJ({code:e,digit:t})}});yield this.engine.sendDataPacket(i,ex.RELIABLE)})}sendChatMessage(e,t){return rG(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 iq({value:{case:"chatMessage",value:new iX(Object.assign(Object.assign({},i),{timestamp:td.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,ex.RELIABLE),this.emit(ef.ChatMessage,i),i})}editChatMessage(e,t){return rG(this,void 0,void 0,function*(){let i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new iq({value:{case:"chatMessage",value:new iX(Object.assign(Object.assign({},i),{timestamp:td.parse(i.timestamp),editTimestamp:td.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,ex.RELIABLE),this.emit(ef.ChatMessage,i),i})}sendText(e,t){return rG(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return rG(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return rG(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}sendBytes(e,t){return rG(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)})}streamBytes(e){return rG(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(e=>{let t=tf(e,2);return t[0],t[1]})}
1registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(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()}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({},sg(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 sQ),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{let n=i.track;n&&(e instanceof MediaStreamTrack?(s6(n)||s9(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return rG(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>tf(t,1)[0].source===e);if(t)return t[1];yield sC(20)}})}publishDataTrack(e){return rG(this,void 0,void 0,function*(){let t=new lp(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class lM extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class lD extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,n;super.set(e,t);let r=null==(i=this.pending)?void 0:i.get(e);if(r){for(let e of r)e.isResolved||null==(n=e.resolve)||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return rG(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 lM("The operation was aborted.",t.reason);let n=new sQ(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 lM("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0}),n.promise.finally(()=>{t.removeEventListener("abort",e)})}return n.promise})}}class lO extends lw{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(ek.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 n2({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new i2({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ek.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?lw.SubscriptionStatus.Unsubscribed:super.isSubscribed?lw.SubscriptionStatus.Subscribed:lw.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?lw.PermissionStatus.Allowed:lw.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)&&(s8(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&s8(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!=(e=this.requestedMaxQuality)?e:eT.HIGH}setTrack(e){let t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(ek.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(ek.VisibilityChanged,this.handleVisibilityChange),n.off(ek.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit
1(ek.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ek.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ek.VisibilityChanged,this.handleVisibilityChange),e.on(ek.Ended,this.handleEnded),this.emit(ek.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(ek.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?ek.Muted:ek.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(ek.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ek.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return s8(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new n7({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===sb.Kind.Video){let r=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(r)sv(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&&sv(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 quality",Object.assign(Object.assign({},this.logContext),{quality:eT.HIGH})),e.quality=eT.HIGH)}this.emit(ek.UpdateSettings,e)}}class lA extends lI{static fromParticipantInfo(e,t,i,n){return new lA(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,t.dataTracks.map(e=>new c5(oI(e),n,{publisherIdentity:t.identity})),t.clientProtocol,t.capabilities)}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]:iw.STANDARD,c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],l=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0,d=arguments.length>10&&void 0!==arguments[10]?arguments[10]:[];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 lD(c.map(e=>[e.info.name,e])),this.volumeMap=new Map,this.clientProtocol=l,this.capabilities=d}addTrackPublication(e){super.addTrackPublication(e),e.on(ek.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),sg(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(ek.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(ek.SubscriptionPermissionChanged,t=>{this.emit(ef.TrackSubscriptionPermissionChanged,e,t)}),e.on(ek.SubscriptionStatusChanged,t=>{this.emit(ef.TrackSubscriptionStatusChanged,e,t)}),e.on(ek.Subscribed,t=>
1{this.emit(ef.TrackSubscribed,t,e)}),e.on(ek.Unsubscribed,t=>{this.emit(ef.TrackUnsubscribed,t,e)}),e.on(ek.SubscriptionFailed,t=>{this.emit(ef.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]:sb.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]:sb.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(ef.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),sg(o))),this.emit(ef.TrackSubscriptionFailed,t);return}return(s="video"===e.kind?new ou(e,t,n,r):new lE(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)&&s5(s)&&s3(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=sb.kindFromProto(e.type);if(!t)return;(a=new lO(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!==sb.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:sg(s),newTrack:sg(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),sg(e))),this.unpublishTrack(e.trackSid,!0))}
1),i.forEach(e=>{this.emit(ef.TrackPublished,e)}),!0}unpublishTrack(e,t){let i=this.trackPublications.get(e);if(!i)return;let n=i.track;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case sb.Kind.Audio:this.audioTrackPublications.delete(e);break;case sb.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(ef.TrackUnpublished,i)}setAudioOutput(e){return rG(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(i=>{var n;s3(i.track)&&s5(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 i of this.dataTracks.entries()){var t=tf(i,2);let n=t[0];e===t[1].info.sid&&this.dataTracks.delete(n)}}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)}}(et=eY||(eY={})).Disconnected="disconnected",et.Connecting="connecting",et.Connected="connected",et.Reconnecting="reconnecting",et.SignalReconnecting="signalReconnecting";class lN extends rX.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,r,a,s,o;if(super(),t=this,this.state=eY.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new e1,this.isVideoPlaybackBlocked=!1,this.log=rq,this.bufferedEvents=[],this.isResuming=!1,this.connect=(e,t,i)=>rG(this,void 0,void 0,function*(){var n;if(!(!("u"<typeof RTCPeerConnection)&&(sE()||sw())))if(sN())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===eY.Connected)return this.log.info("already connected to room ".concat(this.name)),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(eY.Connecting),(null==(n=this.regionUrlProvider)?void 0:n.getServerUrl().toString())!==ot(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),sL(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new cE(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",{error:e})}));let a=(n,s,o)=>rG(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 ok.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!==eh.Cancelled&&t.reason!==eh.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===eh.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(e);return}}[eh.InternalError,eh.ServerUnreachable,eh.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),ok.getInstance().addFailedConnectionAttempt(e)),!i||(null==(l=this.abortController)?void 0:l.signal.aborted)?(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,s$(t)),s(t)):(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i)),this.recreateEngine(!0),yield a(n,s,i))}else{let e=im.UNKNOWN_REASON;t instanceof a$&&(e=s$(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),s(t)}}}),s=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sQ((e,t)=>{a(e,t,s)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,r,a)=>rG(this,void 0,void 0,function*(){let s=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(r),maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},a.signal,!r.singlePeerConnection),o=s.joinResponse,c=s.serverInfo;if(this.serverInfo=c,!c.version)throw new a2("unknown server version");return"0.15.1"===c.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),r.dynacast=!1),o}),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",{error:e})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>rG(this,void 0,void 0,function*(){var r,a;this.state===eY.Reconnecting||this.isResuming||(null==(r=this.engine)?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),(null==(a=this.regionUrlProvider)?void 0:a.isCloud())&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},oZ),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
1(eg.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",{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}sA()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),sA()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(eY.Connected),this.emit(eg.Connected),ok.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 rG(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===eY.Disconnected)return void e.log.debug("already disconnected");if(e.log.info("disconnect from room"),e.state===eY.Connecting||e.state===eY.Reconnecting||e.isResuming){let t="Abort connection attempt due to user initiated disconnect";e.log.warn(t),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,im.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>rG(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>rG(this,void 0,void 0,function*(){let e=[],t=aK();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=sJ();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.startAudio()))}),document.body.append(i),this.once(eg.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}
1this.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=>(this.options.webAudioMix||(e.muted=!1),e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>rG(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.handleRestarting=()=>{for(let e of(this.clearConnectionReconcile(),this.isResuming=!1,this.remoteParticipants.values()))this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(eY.Reconnecting)&&this.emit(eg.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>rG(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),{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",{error:e})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:e.serverRegion})}catch(e){return}this.setAndEmitConnectionState(eY.Connected),this.emit(eg.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===iE.DISCONNECTED?this.handleParticipantDisconnected(i.identity,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=>oI(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
1h(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(eg.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(eg.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=sb.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(ef.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(eg.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.rpcServerManager.handleIncomingRpcRequest(e.participantIdentity,t)}else if("rpcResponse"===e.value.case){let t=e.value.value;switch(t.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(t.requestId,t.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(t.requestId,lv.fromProto(t.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(t.value.case),this.logContext)}}else"rpcAck"===e.value.case&&this.rpcClientManager.handleIncomingRpcAck(e.value.value.requestId)},this.handleUserPacket=(e,t,i,n)=>{this.emit(eg.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(ef.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit(eg.SipDTMFReceived,t,e),null==e||e.emit(ef.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 n=e.id,r=e.text,a=e.language,s=e.startTime,o=e.endTime,c=e.final,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(ek.TranscriptionReceived,a),null==n||n.emit(ef.TranscriptionReceived,a,r),this.emit(eg.TranscriptionReceived,a,n,r)},this.handleChatMessage=(e,t)=>{let i,n,r,a,s=(i=t.id,n=t.timestamp,r=t.message,a=t.editTimestamp,{id:i,timestamp:Number.parseInt(n.toString()),editTimestamp:a?Number.parseInt(a.toString()):void 0,message:r});this.emit(eg.ChatMessage,s,e)},this.handleMetrics=(e,t)=>{this.emit(eg.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>
1{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(eg.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",{error:e}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(eg.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(eg.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(eg.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>rG(this,void 0,void 0,function*(){var e;(null==(e=aK())?void 0:e.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(eg.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(eg.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(eg.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.getRemoteParticipantClientProtocol=e=>{var t,i;return null!=(i=null==(t=this.remoteParticipants.get(e))?void 0:t.clientProtocol)?i:0},this.getRemoteParticipantCapabilities=e=>{var t,i;return null!=(i=null==(t=this.remoteParticipants.get(e))?void 0:t.capabilities)?i:[]},this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.onLocalParticipantMetadataChanged=e=>{this.emit(eg.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(eg.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(eg.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(eg.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(eg.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null==(t=null==e?void 0:e.onPublish)||t.call(e,this)},this.onLocalTrackPublished=e=>rG(this,void 0,void 0,function*(){var t,i,n,r,a,s;null==(t=e.track)||t.on(ek.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.on(ek.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(eg.LocalTrackPublished,e,this.localParticipant),s6(e.track)&&(yield e.track.checkForSilence())&&this.emit(eg.LocalAudioSilenceDetected,e);let o=yield null==(s=e.track)?void 0:s.getDeviceId(!1),c=sp(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit(eg.ActiveDeviceChanged,c,o))}),this.onLocalTrackUnpublished=e=>{var t,i;null==(t=e.track)||t.off(ek.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.off(ek.Restarted,this.onLocalTrackRestarted),this.emit(eg.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>rG(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),i=sp(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active")),this.localParticipant.activeDeviceMap.set(i,t),this.emit(eg.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(eg.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(eg.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(eg.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(eg.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},oX),e),this.log=rV(null!=(i=this.options.loggerName)?i:ec.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},oQ),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},oY),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},oJ),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new cO,this.outgoingDataStreamManager=new cW(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new lo({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
1(eg.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(eg.DataTrackUnpublished,e.sid),null==(t=this.remoteParticipants.get(e.publisherIdentity))||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new lf({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(eg.LocalDataTrackPublished,e.track)}).on("trackUnpublished",e=>{this.emit(eg.LocalDataTrackUnpublished,e.sid)}).on("packetAvailable",e=>{let t=e.handle,i=e.bytes;this.engine.sendDataTrackFrame(i).finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(t))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new lS(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>{var e,t;return null==(t=null==(e=this.engine.latestJoinResponse)?void 0:e.serverInfo)?void 0:t.version}),this.rpcClientManager.on("sendDataPacket",e=>{var t;let i=e.packet;null==(t=this.engine)||t.sendDataPacket(i,ex.RELIABLE)}),this.rpcServerManager=new lC(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",e=>{var t;let i=e.packet;null==(t=this.engine)||t.sendDataPacket(i,ex.RELIABLE)}),this.disconnectLock=new e1,this.localParticipant=new l_("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(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",sX(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",sX(this.options.audioCaptureDefaults.deviceId)),(null==(a=this.options.audioOutput)?void 0:a.deviceId)&&this.switchActiveDevice("audiooutput",sX(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message))),sA()){let e;const t=new AbortController;if(lN.cleanupRegistry){const i=new WeakRef(this);e=()=>{let e=i.deref();e&&e.handleDeviceChange()},lN.cleanupRegistry.register(this,()=>{t.abort()})}else e=this.handleDeviceChange;null==(o=null==(s=navigator.mediaDevices)?void 0:s.addEventListener)||o.call(s,"devicechange",e,{signal:t.signal})}}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)}
1registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return rG(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 og(n,i),this.e2eeManager.on(eE.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(eg.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(eE.EncryptionError,(e,t)=>{let i=t?this.getParticipantByIdentity(t):void 0;this.emit(eg.EncryptionError,e,i)}),null==(e=this.e2eeManager)||e.setup(this),null==(t=this.e2eeManager)||t.setupEngine(this.engine))}setupFrameMetadata(){var e;let t=null!=(e=this.options.frameMetadata)?e:this.options.packetTrailer;this.frameMetadataManager=new ov(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,i;return{room:this.name,roomID:null==(e=this.roomInfo)?void 0:e.sid,participant:null==(t=this.localParticipant)?void 0:t.identity,participantID:null==(i=this.localParticipant)?void 0:i.sid}}get isRecording(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.activeRecording)&&t}getSid(){return this.state===eY.Disconnected?az.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?az.resolve(this.roomInfo.sid):new az((e,t)=>{let i=t=>{""!==t.sid&&(this.engine.off(ev.RoomUpdate,i),e(t.sid))};this.engine.on(ev.RoomUpdate,i),this.once(eg.Disconnected,()=>{this.engine.off(ev.RoomUpdate,i),t(new a3("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 cT(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(ev.ParticipantUpdate,this.handleParticipantUpdates).on(ev.RoomUpdate,this.handleRoomUpdate).on(ev.SpeakersChanged,this.handleSpeakersChanged).on(ev.StreamStateChanged,this.handleStreamStateUpdate).on(ev.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ev.SubscriptionError,this.handleSubscriptionError).on(ev.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ev.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(ev.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ev.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ev.DataPacketReceived,this.handleDataPacket).on(ev.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(eY.SignalReconnecting)&&this.emit(eg.SignalReconnecting)}).on(ev.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.setAndEmitConnectionState(eY.Connected)&&this.emit(eg.Reconnected),this.emitBufferedEvents()}).on(ev.SignalResumed,()=>{this.bufferedEvents=[],(this.state===eY.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ev.Restarting,this.handleRestarting).on(ev.Restarted,this.handleRestarted).on(ev.SignalRestarted,this.handleSignalRestarted).on(ev.Offline,()=>{this.setAndEmitConnectionState(eY.Reconnecting)&&this.emit(eg.Reconnecting)}).on(ev.DCBufferStatusChanged,(e,t)=>{this.emit(eg.DCBufferStatusChanged,e,t)}).on(ev.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(ev.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEac
1h((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(eg.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(ev.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!==iP.NONE}}):this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))}).on(ev.UnPublishDataTrackResponse,e=>{e.info?this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle):this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))}).on(ev.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let t=tf(e,2),i=t[0],n=t[1];return[parseInt(i,10),n.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(ev.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(ev.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>oI(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(ev.TokenRefreshed,e=>{var t;null==(t=this.regionUrlProvider)||t.updateToken(e)}).on(ev.ServerRegionsReported,e=>{var t;null==(t=this.regionUrlProvider)||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:5e3})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>rG(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return null==(e=this.regionUrlProvider)?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return oy.getInstance().getDevices(e,t)}prepareConnection(e,t){return rG(this,void 0,void 0,function*(){if(this.state===eY.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(sL(new URL(e))&&t){this.regionUrlProvider=new cE(e,t);let i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===eY.Disconnected&&(this.regionUrl=i,yield fetch(sZ(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(sZ(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",{error:e})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return rG(this,void 0,void 0,function*(){let i,n=()=>rG(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":i=new rE({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new rE({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new rE({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new rE({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=()=>rG(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new rE({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>rG(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new rE({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 rE({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>rG(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new ri({reason:im.CLIENT_INITIATED,action:rn.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw Error("subscriber-bandwidth requires a number as argument");i=new rE({scenario:{case:"subscriberBandwidth",value:s1(t)}});break;case"leave-full-reconnect":i=new rE({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 rG(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===sb.Source.Microphone);try{d=(yield Promise.all(n.map(e=>{var t;return null==(t=e.audioTrack)?void 0:t.setDeviceId(h)}
1))).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===sb.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,!sP()&&!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 oy.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(eg.ActiveDeviceChanged,e,t)),d}()})}setupLocalParticipantEvents(){this.localParticipant.on(ef.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ef.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ef.AttributesChanged,this.onLocalAttributesChanged).on(ef.TrackMuted,this.onLocalTrackMuted).on(ef.TrackUnmuted,this.onLocalTrackUnmuted).on(ef.LocalTrackPublished,this.onLocalTrackPublished).on(ef.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ef.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ef.MediaDevicesError,this.onMediaDevicesError).on(ef.AudioStreamAcquired,this.startAudio).on(ef.ChatMessage,this.onLocalChatMessageSent).on(ef.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===eY.Connecting||this.state===eY.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(eg.Reconnected,n),this.off(eg.Connected,n),this.off(eg.Disconnected,r)};this.once(eg.Reconnected,n),this.once(eg.Connected,n),this.once(eg.Disconnected,r);return}if(this.state===eY.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected");if("ended"===e.readyState)return void this.log.debug("skipping incoming track as it already ended");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");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));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));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),{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);
1(null==u?void 0:u.isEncrypted)&&!this.e2eeManager&&this.emit(eg.EncryptionError,Error("Encrypted ".concat(u.source," track received from participant ").concat(d.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){let t,i=()=>this.localParticipant.getTrackPublications().find(t=>t.trackSid===e),n=i();if(n)return void this.emitLocalTrackSubscribed(n);this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});let r=t=>{t.trackSid===e&&(a(),this.emitLocalTrackSubscribed(t))},a=()=>{clearTimeout(t),this.localParticipant.off(ef.LocalTrackPublished,r),this.off(eg.Disconnected,a)};this.localParticipant.on(ef.LocalTrackPublished,r),this.once(eg.Disconnected,a),t=setTimeout(()=>{a();let t=i();t?this.emitLocalTrackSubscribed(t):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},1e4)}emitLocalTrackSubscribed(e){this.localParticipant.emit(ef.LocalTrackSubscribed,e),this.emitWhenConnected(eg.LocalTrackSubscribed,e,this.localParticipant)}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.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==eY.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();
1try{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(ef.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ef.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ef.AttributesChanged,this.onLocalAttributesChanged).off(ef.TrackMuted,this.onLocalTrackMuted).off(ef.TrackUnmuted,this.onLocalTrackUnmuted).off(ef.LocalTrackPublished,this.onLocalTrackPublished).off(ef.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ef.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ef.MediaDevicesError,this.onMediaDevicesError).off(ef.AudioStreamAcquired,this.startAudio).off(ef.ChatMessage,this.onLocalChatMessageSent).off(ef.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),sA()&&(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(eY.Disconnected),this.emit(eg.Disconnected,n)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(eg.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return rG(this,void 0,void 0,function*(){var e,t,i;let n=oy.getInstance().previousDevices,r=yield oy.getInstance().getDevices(void 0,!1),a=aK();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(eg.ActiveDeviceChanged,e.kind,e.deviceId)}for(let a of["audiooutput","audioinput","videoinput"]){let s="audioinput"===a?sb.Source.Microphone:"videoinput"===a?sb.Source.Camera:sb.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||sD())&&"videoinput"!==a&&(!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(a))||"audiooutput"===a&&sD()||(yield this.switchActiveDevice(a,c[0].deviceId)))}})}acquireAudioContext(){return rG(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=sh())?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEac
1h(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),sC(200)])}catch(e){this.log.warn("Could not resume audio context",{error:e})}let i=(null==(t=this.audioContext)?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(eg.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?lA.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new lA(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))),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(eg.ParticipantConnected,i),i.on(ef.TrackPublished,e=>{this.emitWhenConnected(eg.TrackPublished,e,i)}).on(ef.TrackSubscribed,(e,t)=>{e.kind===sb.Kind.Audio?(e.on(ek.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(ek.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===sb.Kind.Video&&(e.on(ek.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(ek.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(eg.TrackSubscribed,e,t,i)}).on(ef.TrackUnpublished,e=>{this.emit(eg.TrackUnpublished,e,i)}).on(ef.TrackUnsubscribed,(e,t)=>{this.emit(eg.TrackUnsubscribed,e,t,i)}).on(ef.TrackMuted,e=>{this.emitWhenConnected(eg.TrackMuted,e,i)}).on(ef.TrackUnmuted,e=>{this.emitWhenConnected(eg.TrackUnmuted,e,i)}).on(ef.ParticipantMetadataChanged,e=>{this.emitWhenConnected(eg.ParticipantMetadataChanged,e,i)}).on(ef.ParticipantNameChanged,e=>{this.emitWhenConnected(eg.ParticipantNameChanged,e,i)}).on(ef.AttributesChanged,e=>{this.emitWhenConnected(eg.ParticipantAttributesChanged,e,i)}).on(ef.ConnectionQualityChanged,e=>{this.emitWhenConnected(eg.ConnectionQualityChanged,e,i)}).on(ef.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(eg.ParticipantPermissionsChanged,e,i)}).on(ef.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(eg.TrackSubscriptionStatusChanged,e,t,i)}).on(ef.TrackSubscriptionFailed,(e,t)=>{this.emit(eg.TrackSubscriptionFailed,e,i,t)}).on(ef.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(eg.TrackSubscriptionPermissionChanged,e,t,i)}).on(ef.Active,()=>{this.emitWhenConnected(eg.ParticipantActive,i),i.kind===iw.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)}getClientInfoCapabilities(e){var t;let i=[];return(os(null!=(t=e.frameMetadata)?t:e.packetTrailer)||this.e2eeManager)&&i.push(i5.CAP_PACKET_TRAILER),oe()&&i.push(i5.CAP_COMPRESSION_DEFLATE_RAW),i}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(lk,(e,t)=>rG(this,[e,t],void 0,function(e,t){var i=this;let n=t.identity;return function*(){var t;let r=null!=(t=e.info.attributes)?t:{};yield i.rpcServerManager.handleIncomingDataStream(e,n,r)}()})),this.incomingDataStreamManager.registerTextStreamHandler(lb,(e,t)=>rG(this,[e,t],void 0,function(e,t){var i=this;let n=t.identity;return function*(){var t;let r=null!=(t=e.info.attributes)?t:{};yield i.rpcClientManager.handleIncomingDataStream(e,n,r)}()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=se.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,im.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&se.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===eY.Connected),this.emit
1(eg.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=tf(e,2),i=t[0],n=t[1];this.emit(i,...n)}),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===eY.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===eY.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return rG(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 iy({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:td.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new iC({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(eg.SignalConnected),this.emit(eg.Connected),this.setAndEmitConnectionState(eY.Connected),a.video){let e=new lR(sb.Kind.Video,new i_({source:id.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:il.AUDIO,name:"video-dummy"}),new cf(a.useRealTracks&&(null==(t=window.navigator.mediaDevices)?void 0:t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:sK(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(ef.LocalTrackPublished,e)}if(a.audio){let e=new lR(sb.Kind.Audio,new i_({source:id.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:il.AUDIO}),new cn(a.useRealTracks&&(null==(n=navigator.mediaDevices)?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:sJ(),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(ef.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new iC({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:iE.ACTIVE,tracks:[],joinedAt:td.parse(Date.now())}),i=this.getOrCreateParticipant(t.identity,t);if(s.video){let n=sK(160*(null!=(r=s.aspectRatios[e%s.aspectRatios.length])?r:1),160,!1,!0),a=new i_({source:id.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:il.AUDIO});i.addSubscribedMediaTrack(n,a.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(s.audio){let e=sJ(),n=new i_({source:id.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:il.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!==eg.ActiveSpeakersChanged&&e!==eg.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===eg.TrackSubscribed||e===eg.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:t}),this.log.debug("room event ".concat(e),{event:e,args:t})}return super.emit(e,...i)}}lN.cleanupRegistry="u">typeof FinalizationRegistry&&"u">typeof WeakRef&&new FinalizationRegistry(e=>{e()}),(ei=eX||(eX={}))[ei.IDLE=0]="IDLE",ei[ei.RUNNING=1]="RUNNING",ei[ei.SKIPPED=2]="SKIPPED",ei[ei.SUCCESS=3]="SUCCESS",ei[ei.FAILED=4]="FAILED";class lL extends rX.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=eX.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new lN(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return rG(this,void 0,void 0,function*(){if(this.status!==eX.IDLE)throw Error("check is running already");this.setStatus(eX.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!==eX.SKIPPED&&this.setStatus(this.isSuccess()?eX.SUCCESS:eX.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>"error"===e.level)}connect(e){return rG(this,void 0,void 0,function*(){return this.room.state===eY.Connected||(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions)),this.room})}disconnect(){return rG(this,void 0,void 0,function*(){this.room&&this.room.state!==eY.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(eX.SKIPPED)}switchProtocol(e){return rG(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(eg.Reconnecting,()=>{t=!0}),this.room.once(eg.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 sC(100)}throw Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}
1),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}}}rX.EventEmitter,new TextEncoder,new TextDecoder;class lx extends Error{constructor(e,t){var i;super(e,t),tg(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null==(i=Error.captureStackTrace)||i.call(Error,this,this.constructor)}}tg(lx,"code","ERR_JOSE_GENERIC");class lU extends lx{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}}),tg(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),tg(this,"claim",void 0),tg(this,"reason",void 0),tg(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}tg(lU,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class lF extends lx{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}}),tg(this,"code","ERR_JWT_EXPIRED"),tg(this,"claim",void 0),tg(this,"reason",void 0),tg(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}tg(lF,"code","ERR_JWT_EXPIRED");class lB extends lx{constructor(){super(...arguments),tg(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}tg(lB,"code","ERR_JOSE_ALG_NOT_ALLOWED");class lj extends lx{constructor(){super(...arguments),tg(this,"code","ERR_JOSE_NOT_SUPPORTED")}}tg(lj,"code","ERR_JOSE_NOT_SUPPORTED");class lq extends lx{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),tg(this,"code","ERR_JWE_DECRYPTION_FAILED")}}tg(lq,"code","ERR_JWE_DECRYPTION_FAILED");class lV extends lx{constructor(){super(...arguments),tg(this,"code","ERR_JWE_INVALID")}}tg(lV,"code","ERR_JWE_INVALID");class lH extends lx{constructor(){super(...arguments),tg(this,"code","ERR_JWS_INVALID")}}tg(lH,"code","ERR_JWS_INVALID");class lW extends lx{constructor(){super(...arguments),tg(this,"code","ERR_JWT_INVALID")}}tg(lW,"code","ERR_JWT_INVALID");class lz extends lx{constructor(){super(...arguments),tg(this,"code","ERR_JWK_INVALID")}}tg(lz,"code","ERR_JWK_INVALID");class lG extends lx{constructor(){super(...arguments),tg(this,"code","ERR_JWKS_INVALID")}}tg(lG,"code","ERR_JWKS_INVALID");class lK extends lx{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),tg(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}tg(lK,"code","ERR_JWKS_NO_MATCHING_KEY");class lJ extends lx{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),tg(this,Symbol.asyncIterator,void 0),tg(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}tg(lJ,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class lQ extends lx{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),tg(this,"code","ERR_JWKS_TIMEOUT")}}tg(lQ,"code","ERR_JWKS_TIMEOUT");class lY extends lx{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),tg(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}tg(lY,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");Symbol.for("lk.serializer")}}]);
2//# sourceMappingURL=e3ef6e5f.10ff35039bb69d25.js.map

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.