vendor: 4,775 bytes, line 1
1import{t as fd}from"./vendor-recharts-BYQpxUtL.js";import"./vendor-react-Bxgxa9T6.js";var Es={};function gd(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var vd=Object.defineProperty,bd=(n,e,t)=>e in n?vd(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,_s=(n,e,t)=>bd(n,typeof e!="symbol"?e+"":e,t);class fe{constructor(){_s(this,"_locking"),_s(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function re(n,e){if(!n)throw new Error(e)}const yd=34028234663852886e22,kd=-34028234663852886e22,Td=4294967295,Sd=2147483647,Cd=-2147483648;function ji(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>Sd||n<Cd)throw new Error("invalid int 32: "+n)}function ur(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>Td||n<0)throw new Error("invalid uint 32: "+n)}function Ya(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>yd||n<kd))throw new Error("invalid float 32: "+n)}const $a=Symbol("@bufbuild/protobuf/enum-type");function Ed(n){const e=n[$a];return re(e,"missing enum type on enum object"),e}function Xa(n,e,t,i){n[$a]=Za(e,t.map(r=>({no:r.no,name:r.name,localName:n[r.no]})))}function Za(n,e,t){const i=Object.create(null),r=Object.create(null),s=[];for(const a of e){const o=eo(a);s.push(o),i[a.name]=o,r[a.no]=o}return{typeName:n,values:s,findName(a){return i[a]},findNumber(a){return r[a]}}}function _d(n,e,t){const i={};for(const r of e){const s=eo(r);i[s.localName]=s.no,i[s.no]=s.localName}return Xa(i,n,e),i}function eo(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class qr{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(t);return r.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function wd(n,e,t,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new qr),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,d){return new a().fromBinary(o,d)},fromJson(o,d){return new a().fromJson(o,d)},fromJsonString(o,d){return new a().fromJsonString(o,d)},equals(o,d){return n.util.equals(a,o,d)}}),a}function Pd(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Bn(n,e,t){for(let s=0;s<28;s=s+7){const a=n>>>s,o=!(!(a>>>7)&&e==0),d=(o?a|128:a)&255;if(t.push(d),!o)return}const i=n>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const a=e>>>s,o=!!(a>>>7),d=(o?a|128:a)&255;if(t.push(d),!o)return}t.push(e>>>31&1)}}const Wi=4294967296;function ws(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,r=0;function s(a,o){const d=Number(n.slice(a,o));r*=t,i=i*t+d,i>=Wi&&(r=r+(i/Wi|0),i=i%Wi)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?io(i,r):Vr(i,r)}function Rd(n,e){let t=Vr(n,e);const i=t.hi&2147483648;i&&(t=io(t.lo,t.hi));const r=to(t.lo,t.hi);return i?"-"+r:r}function to(n,e){var t=Id(n,e);
1if(n=t.lo,e=t.hi,e<=2097151)return String(Wi*e+n);const i=n&16777215,r=(n>>>24|e<<8)&16777215,s=e>>16&65535;let a=i+r*6777216+s*6710656,o=r+s*8147497,d=s*2;const c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(d+=Math.floor(o/c),o%=c),d.toString()+Ps(o)+Ps(a)}function Id(n,e){return{lo:n>>>0,hi:e>>>0}}function Vr(n,e){return{lo:n|0,hi:e|0}}function io(n,e){return e=~e,n?n=~n+1:e+=1,Vr(n,e)}const Ps=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Rs(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function Md(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Dd(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof Es!="object"||Es.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(d){const c=typeof d=="bigint"?d:BigInt(d);if(c>s||c<r)throw new Error("int64 invalid: ".concat(d));return c},uParse(d){const c=typeof d=="bigint"?d:BigInt(d);if(c>o||c<a)throw new Error("uint64 invalid: ".concat(d));return c},enc(d){return n.setBigInt64(0,this.parse(d),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(d){return n.setBigInt64(0,this.uParse(d),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(d,c){return n.setInt32(0,d,!0),n.setInt32(4,c,!0),n.getBigInt64(0,!0)},uDec(d,c){return n.setInt32(0,d,!0),n.setInt32(4,c,!0),n.getBigUint64(0,!0)}}}const t=r=>re(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>re(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),ws(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),ws(r)},dec(r,s){return Rd(r,s)},uDec(r,s){return to(r,s)}}}const te=Dd();var _;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(_||(_={}));var _t;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(_t||(_t={}));function ft(n,e,t){if(e===t)return!0;if(n==_.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case _.UINT64:case _.FIXED64:case _.INT64:case _.SFIXED64:case _.SINT64:return e==t}return!1}function ni(n,e){switch(n){case _.BOOL:return!1;case _.UINT64:case _.FIXED64:case _.INT64:case _.SFIXED64:case _.SINT64:return e==0?te.zero:"0";case _.DOUBLE:case _.FLOAT:return 0;case _.BYTES:return new Uint8Array(0);case _.STRING:return"";default:return 0}}function no(n,e){switch(n){case _.BOOL:return e===!1;case _.STRING:return e==="";case _.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}function Is(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,i=Array(e);t<e;t++)i[t]=n[t];return i}function Ad(n){if(Array.isArray(n))return n}function j(n,e,t){return(e=xd(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Od(n,e){var t=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(t!=null){var i,r,s,a,o=[],d=!0,c=!1;try{if(s=(t=t.call(n)).next,e===0){if(Object(t)!==t)return;d=!1}else for(;!(d=(i=s.call(t)).done)&&(o.push(i.value),o.length!==e);d=!0);}catch(l){c=!0,r=l}
1finally{try{if(!d&&t.return!=null&&(a=t.return(),Object(a)!==a))return}finally{if(c)throw r}}return o}}function Nd(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 2In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function N(n,e){return Ad(n)||Od(n,e)||Ud(n,e)||Nd()}function Ld(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function xd(n){var e=Ld(n,"string");return typeof e=="symbol"?e:e+""}function Ud(n,e){if(n){if(typeof n=="string")return Is(n,e);var t={}.toString.call(n).slice(8,-1);return t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set"?Array.from(n):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Is(n,e):void 0}}var ae;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ae||(ae={}));class Fd{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ur(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return ji(e),Rs(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Ya(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){ur(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ji(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ji(e),e=(e<<1^e>>31)>>>0,Rs(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=te.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=te.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=te.enc(e);return Bn(t.lo,t.hi,this.buf),this}sint64(e){let t=te.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return Bn(r,s,this.buf),this}uint64(e){let t=te.uEnc(e);return Bn(t.lo,t.hi,this.buf),this}}class Bd{constructor(e,t){this.varint64=Pd,this.uint32=Md,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ae.Varint:for(;this.buf[this.pos++]&128;);break;case ae.Bit64:this.pos+=4;case ae.Bit32:this.pos+=4;break;case ae.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ae.StartGroup:for(;;){const s=this.tag(),a=N(s,2),o=a[0],d=a[1];if(d===ae.EndGroup){if(t!==void 0&&o!==t)throw new Error("invalid end group tag");break}this.skip(d,o)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return te.dec(...this.varint64())}uint64(){return te.uDec(...this.varint64())}sint64(){let e=this.varint64(),t=N(e,2),i=t[0],r=t[1],s=-(i&1);return i=(i>>>1|(r&1)<<31)^s,r=r>>>1^s,te.dec(i,r)}bool(){let e=this.varint64(),t=N(e,2),i=t[0],r=t[1];return i!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return te.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return te.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 qd(n,e,t,i){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=n.util.newFieldList([s]).list()[0]}return r},runtime:n}}function ro(n){const e=n.field.localName,t=Object.create(null);return t[e]=Vd(n),[t,()=>t[e]]}function Vd(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;
vendor: 10,047 bytes, lines 2-3
2case"scalar":return ni(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function jd(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),fn=[];for(let n=0;n<ot.length;n++)fn[ot[n].charCodeAt(0)]=n;fn[45]=ot.indexOf("+");fn[95]=ot.indexOf("/");const so={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,r=0,s,a=0;for(let o=0;o<n.length;o++){if(s=fn[n.charCodeAt(o)],s===void 0)switch(n[o]){case"=":r=0;case` 3`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=s,r=1;break;case 1:t[i++]=a<<2|(s&48)>>4,a=s,r=2;break;case 2:t[i++]=(a&15)<<4|(s&60)>>2,a=s,r=3;break;case 3:t[i++]=(a&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,r=0;for(let s=0;s<n.length;s++)switch(i=n[s],t){case 0:e+=ot[i>>2],r=(i&3)<<4,t=1;break;case 1:e+=ot[r|i>>4],r=(i&15)<<2,t=2;break;case 2:e+=ot[r|i>>6],e+=ot[i&63],t=0;break}return t&&(e+=ot[r],e+="=",t==1&&(e+="=")),e}};function Wd(n,e,t){oo(e,n);const i=e.runtime.bin.makeReadOptions(t),r=jd(n.getType().runtime.bin.listUnknownFields(n),e.field),s=ro(e),a=N(s,2),o=a[0],d=a[1];for(const c of r)e.runtime.bin.readField(o,i.readerFactory(c.data),e.field,c.wireType,i);return d()}function Hd(n,e,t,i){oo(e,n);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if(ao(n,e)){const c=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of c)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const a=s.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,s);const d=r.readerFactory(a.finish());for(;d.pos<d.len;){const c=d.tag(),l=N(c,2),u=l[0],h=l[1],p=d.skip(h,u);n.getType().runtime.bin.onUnknownField(n,u,h,p)}}function ao(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function oo(n,e){re(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function co(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!no(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Ms(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?ni(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function ct(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(qr.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function lo(n,e){return ct(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}_.DOUBLE,_.FLOAT,_.INT64,_.UINT64,_.INT32,_.UINT32,_.BOOL,_.STRING,_.BYTES;const Ds={ignoreUnknownFields:!1},As={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Kd(n){return n?Object.assign(Object.assign({},Ds),n):Ds}function Gd(n){return n?Object.assign(Object.assign({},As),n):As}const tn=Symbol(),Hi=Symbol();function zd(){return{makeReadOptions:Kd,makeWriteOptions:Gd,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat($e(e)));i=i??new n;const r=new Map,s=t.typeRegistry;for(const o of Object.entries(e)){var a=N(o,2);const d=a[0],c=a[1],l=n.fields.findJsonName(d);if(l){if(l.oneof){if(c===null&&l.kind=="scalar")continue;const u=r.get(l.oneof);if(u!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(l.oneof.name,'" present: "').concat(u,'", "').concat(d,'"'));r.set(l.oneof,d)}Os(i,c,l,t,n)}else{let u=!1;if(s!=null&&s.findExtension&&d.startsWith("[")&&d.endsWith("]")){const h=s.findExtension(d.substring(1,d.length-1));if(h&&h.extendee.typeName==n.typeName){u=!0;const p=ro(h),f=N(p,2),g=f[0],k=f[1];Os(g,c,h.field,t,h),Hd(i,h,k(),t)}}if(!u&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(d,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let r;try{for(r of t.fields.byNumber()){if(!co(r,n)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!Qd(r))continue}const a=r.oneof?n[r.oneof.localName].value:n[r.localName],o=Ns(r,a,e);o!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=o)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(n)){const o=s.findExtensionFor(t.typeName,a.no);if(o&&ao(n,o)){const d=Wd(n,o,e),c=Ns(o.field,d,e);c!==void 0&&(i[o.field.jsonName]=c)}}}catch(s){const a=r?"cannot encode field ".concat(t.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=s instanceof Error?s.message:String(s);throw new Error(a+(o.length>0?": ".concat(o):""))}return i},readScalar(n,e,t){return gi(n,e,t??_t.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||no(n,e)))return Ki(n,e)},debug:$e}}function $e(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function Os(n,e,t,i,r){let s=t.localName;if(t.repeated){if(re(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat($e(e)));const o=n[s];for(const d of e){if(d===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat($e(d)));switch(t.kind){case"message":o.push(t.T.fromJson(d,i));break;case"enum":const c=qn(t.T,d,i.ignoreUnknownFields,!0);c!==Hi&&o.push(c);break;case"scalar":try{o.push(gi(t.T,d,t.L,!0))}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat($e(d));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat($e(e)));const o=n[s];for(const d of Object.entries(e)){var a=N(d,2);const c=a[0],l=a[1];if(l===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: map value null"));let u;try{u=Jd(t.K,c)}catch(h){let p="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat($e(e));throw h instanceof Error&&h.message.length>0&&(p+=": ".concat(h.message)),new Error(p)}switch(t.V.kind){case"message":o[u]=t.V.T.fromJson(l,i);break;case"enum":const h=qn(t.V.T,l,i.ignoreUnknownFields,!0);h!==Hi&&(o[u]=h);break;case"scalar":try{o[u]=gi(t.V.T,l,_t.BIGINT,!0)}catch(p){let f="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat($e(e));throw p instanceof Error&&p.message.length>0&&(f+=": ".concat(p.message)),new Error(f)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:s},s="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let d=n[s];ct(d)?d.fromJson(e,i):(n[s]=d=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[s]=o.fieldWrapper.unwrapField(d)));break;case"enum":const c=qn(t.T,e,i.ignoreUnknownFields,!1);switch(c){case tn:Ms(t,n);break;case Hi:break;default:n[s]=c;break}break;case"scalar":try{const l=gi(t.T,e,t.L,!1);switch(l){case tn:Ms(t,n);break;default:n[s]=l;break}}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat($e(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function Jd(n,e){if(n===_.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return gi(n,e,_t.BIGINT,!0).toString()}function gi(n,e,t,i){if(e===null)return i?ni(n,t):tn;switch(n){case _.DOUBLE:case _.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return n==_.FLOAT&&Ya(r),r;case _.INT32:case _.FIXED32:case _.SFIXED32:case _.SINT32:case _.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return n==_.UINT32||n==_.FIXED32?ur(s):ji(s),s;case _.INT64:case _.SFIXED64:case _.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=te.parse(e);return t?a.toString():a;case _.FIXED64:case _.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=te.uParse(e);return t?o.toString():o;case _.BOOL:if(typeof e!="boolean")break;return e;case _.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case _.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return so.dec(e)}throw new Error}function qn(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:tn;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=n.findName(e);
3if(r!==void 0)return r.no;if(t)return Hi;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat($e(e)))}function Qd(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function Ns(n,e,t){if(n.kind=="map"){re(typeof e=="object"&&e!=null);const a={},o=Object.entries(e);switch(n.V.kind){case"scalar":for(const c of o){var i=N(c,2);const l=i[0],u=i[1];a[l.toString()]=Ki(n.V.T,u)}break;case"message":for(const c of o){var r=N(c,2);const l=r[0],u=r[1];a[l.toString()]=u.toJson(t)}break;case"enum":const d=n.V.T;for(const c of o){var s=N(c,2);const l=s[0],u=s[1];a[l.toString()]=Vn(d,u,t.enumAsInteger)}break}return t.emitDefaultValues||o.length>0?a:void 0}if(n.repeated){re(Array.isArray(e));const a=[];switch(n.kind){case"scalar":for(let o=0;o<e.length;o++)a.push(Ki(n.T,e[o]));break;case"enum":for(let o=0;o<e.length;o++)a.push(Vn(n.T,e[o],t.enumAsInteger));break;case"message":for(let o=0;o<e.length;o++)a.push(e[o].toJson(t));break}return t.emitDefaultValues||a.length>0?a:void 0}switch(n.kind){case"scalar":return Ki(n.T,e);case"enum":return Vn(n.T,e,t.enumAsInteger);case"message":return lo(n.T,e).toJson(t)}}function Vn(n,e,t){var i;if(re(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const r=n.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function Ki(n,e){switch(n){case _.INT32:case _.SFIXED32:case _.SINT32:case _.FIXED32:case _.UINT32:return re(typeof e=="number"),e;case _.FLOAT:case _.DOUBLE:return re(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case _.STRING:return re(typeof e=="string"),e;case _.BOOL:return re(typeof e=="boolean"),e;case _.UINT64:case _.FIXED64:case _.INT64:case _.SFIXED64:case _.SINT64:return re(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case _.BYTES:return re(e instanceof Uint8Array),so.enc(e)}}const jt=Symbol("@bufbuild/protobuf/unknown-fields"),Ls={readUnknownFields:!0,readerFactory:n=>new Bd(n)},xs={writeUnknownFields:!0,writerFactory:()=>new Fd};function Yd(n){return n?Object.assign(Object.assign({},Ls),n):Ls}function $d(n){return n?Object.assign(Object.assign({},xs),n):xs}function Xd(){return{makeReadOptions:Yd,makeWriteOptions:$d,listUnknownFields(n){var e;return(e=n[jt])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[jt]},writeUnknownFields(n,e){const i=n[jt];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(n,e,t,i){const r=n;Array.isArray(r[jt])||(r[jt]=[]),r[jt].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,r){const s=n.getType(),a=r?e.len:e.pos+t;let o,d;for(;e.pos<a;){var c=e.tag(),l=N(c,2);if(o=l[0],d=l[1],r===!0&&d==ae.EndGroup)break;const u=s.fields.find(o);if(!u){const h=e.skip(d,o);i.readUnknownFields&&this.onUnknownField(n,o,d,h);continue}Us(n,e,u,d,i)}if(r&&(d!=ae.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:Us,writeMessage(n,e,t){const i=n.getType();for(const r of i.fields.byNumber()){if(!co(r,n)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?n[r.oneof.localName].value:n[r.localName];Fs(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&Fs(n,e,t,i)}}}function Us(n,e,t,i,r){let s=t.repeated,a=t.localName;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?_.INT32:t.T;let d=nn;if(t.kind=="scalar"&&t.L>0&&(d=el),s){let f=n[a];if(i==ae.LengthDelimited&&o!=_.STRING&&o!=_.BYTES){let k=e.uint32()+e.pos;for(;e.pos<k;)f.push(d(e,o))}else f.push(d(e,o))}else n[a]=d(e,o);break;case"message":const c=t.T;s?n[a].push(Gi(e,new c,r,t)):ct(n[a])?Gi(e,n[a],r,t):(n[a]=Gi(e,new c,r,t),c.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=c.fieldWrapper.unwrapField(n[a])));break;case"map":let l=Zd(t,e,r),u=N(l,2),h=u[0],p=u[1];n[a][h]=p;break}}function Gi(n,e,t,i){const r=e.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(e,n,s?i.no:n.uint32(),t,s),e}function Zd(n,e,t){const i=e.uint32(),r=e.pos+i;let s,a;for(;e.pos<r;){const o=e.tag();switch(N(o,1)[0]){case 1:s=nn(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=nn(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=Gi(e,new n.V.T,t,void 0);break}break}}
vendor: 24,689 bytes, line 3
3if(s===void 0&&(s=ni(n.K,_t.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),a===void 0)switch(n.V.kind){case"scalar":a=ni(n.V.T,_t.BIGINT);break;case"enum":a=n.V.T.values[0].no;break;case"message":a=new n.V.T;break}return[s,a]}function el(n,e){const t=nn(n,e);return typeof t=="bigint"?t.toString():t}function nn(n,e){switch(e){case _.STRING:return n.string();case _.BOOL:return n.bool();case _.DOUBLE:return n.double();case _.FLOAT:return n.float();case _.INT32:return n.int32();case _.INT64:return n.int64();case _.UINT64:return n.uint64();case _.FIXED64:return n.fixed64();case _.BYTES:return n.bytes();case _.FIXED32:return n.fixed32();case _.SFIXED32:return n.sfixed32();case _.SFIXED64:return n.sfixed64();case _.SINT64:return n.sint64();case _.UINT32:return n.uint32();case _.SINT32:return n.sint32()}}function Fs(n,e,t,i){re(e!==void 0);const r=n.repeated;switch(n.kind){case"scalar":case"enum":let a=n.kind=="enum"?_.INT32:n.T;if(r)if(re(Array.isArray(e)),n.packed)il(t,a,n.no,e);else for(const o of e)vi(t,a,n.no,o);else vi(t,a,n.no,e);break;case"message":if(r){re(Array.isArray(e));for(const o of e)Bs(t,i,n,o)}else Bs(t,i,n,e);break;case"map":re(typeof e=="object"&&e!=null);for(const o of Object.entries(e)){var s=N(o,2);const d=s[0],c=s[1];tl(t,i,n,d,c)}break}}function tl(n,e,t,i,r){n.tag(t.no,ae.LengthDelimited),n.fork();let s=i;switch(t.K){case _.INT32:case _.FIXED32:case _.UINT32:case _.SFIXED32:case _.SINT32:s=Number.parseInt(i);break;case _.BOOL:re(i=="true"||i=="false"),s=i=="true";break}switch(vi(n,t.K,1,s),t.V.kind){case"scalar":vi(n,t.V.T,2,r);break;case"enum":vi(n,_.INT32,2,r);break;case"message":re(r!==void 0),n.tag(2,ae.LengthDelimited).bytes(r.toBinary(e));break}n.join()}function Bs(n,e,t,i){const r=lo(t.T,i);t.delimited?n.tag(t.no,ae.StartGroup).raw(r.toBinary(e)).tag(t.no,ae.EndGroup):n.tag(t.no,ae.LengthDelimited).bytes(r.toBinary(e))}function vi(n,e,t,i){re(i!==void 0);let r=uo(e),s=N(r,2),a=s[0],o=s[1];n.tag(t,a)[o](i)}function il(n,e,t,i){if(!i.length)return;n.tag(t,ae.LengthDelimited).fork();let r=uo(e),s=N(r,2),a=s[1];for(let o=0;o<i.length;o++)n[a](i[o]);n.join()}function uo(n){let e=ae.Varint;switch(n){case _.BYTES:case _.STRING:e=ae.LengthDelimited;break;case _.DOUBLE:case _.FIXED64:case _.SFIXED64:e=ae.Bit64;break;case _.FIXED32:case _.SFIXED32:case _.FLOAT:e=ae.Bit32;break}const t=_[n].toLowerCase();return[e,t]}function nl(){return{setEnumType:Xa,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const r of t.fields.byMember()){const s=r.localName,a=e,o=n;if(o[s]!=null)switch(r.kind){case"oneof":const d=o[s].case;if(d===void 0)continue;const c=r.findField(d);let l=o[s].value;c&&c.kind=="message"&&!ct(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===_.BYTES&&(l=di(l)),a[s]={case:d,value:l};break;case"scalar":case"enum":let u=o[s];r.T===_.BYTES&&(u=r.repeated?u.map(di):di(u)),a[s]=u;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===_.BYTES)for(const f of Object.entries(o[s])){var i=N(f,2);const g=i[0],k=i[1];a[s][g]=di(k)}else Object.assign(a[s],o[s]);break;case"message":const p=r.V.T;for(const f of Object.keys(o[s])){let g=o[s][f];p.fieldWrapper||(g=new p(g)),a[s][f]=g}break}break;case"message":const h=r.T;if(r.repeated)a[s]=o[s].map(p=>ct(p,h)?p:new h(p));else{const p=o[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?a[s]=di(p):a[s]=p:a[s]=ct(p,h)?p:new h(p)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const r=e[i.localName],s=t[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((a,o)=>i.T.equals(a,s[o]));case"scalar":return r.every((a,o)=>ft(i.T,a,s[o]));case"enum":return r.every((a,o)=>ft(_.INT32,a,s[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let a=r,o=s;return i.T.fieldWrapper&&(a!==void 0&&!ct(a)&&(a=i.T.fieldWrapper.wrapField(a)),o!==void 0&&!ct(o)&&(o=i.T.fieldWrapper.wrapField(o))),i.T.equals(a,o);case"enum":return ft(_.INT32,r,s);case"scalar":return ft(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const d=i.findField(r.case);if(d===void 0)return!0;switch(d.kind){case"message":return d.T.equals(r.value,s.value);case"enum":return ft(_.INT32,r.value,s.value);case"scalar":return ft(d.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(d.kind));case"map":const c=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const l=i.V.T;return c.every(h=>l.equals(r[h],s[h]));case"enum":return c.every(h=>ft(_.INT32,r[h],s[h]));case"scalar":const u=i.V.T;return c.every(h=>ft(u,r[h],s[h]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const s of e.fields.byMember()){const a=n[s.localName];let o;if(s.repeated)o=a.map(xi);else if(s.kind=="map"){o=i[s.localName];for(const d of Object.entries(a)){var r=N(d,2);const c=r[0],l=r[1];o[c]=xi(l)}}else s.kind=="oneof"?o=s.findField(a.case)?{case:a.case,value:xi(a.value)}:{case:void 0}:o=xi(a);i[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function xi(n){if(n===void 0)return n;if(ct(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function di(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function rl(n,e,t){return{syntax:n,json:zd(),bin:Xd(),util:Object.assign(Object.assign({},nl()),{newFieldList:e,initFields:t}),makeMessageType(i,r,s){return wd(this,i,r,s)},makeEnum:_d,makeEnumType:Za,getEnumType:Ed,makeExtension(i,r,s){return qd(this,i,r,s)}}}class sl{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function ho(n,e){const t=po(n);return e?t:ul(ll(t))}function al(n){return ho(n,!1)}const ol=po;function po(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let r=n.charAt(i);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),t.push(r);break}}return t.join("")}const cl=new Set(["constructor","toString","toJSON","valueOf"]),dl=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),mo=n=>"".concat(n,"$"),ll=n=>dl.has(n)?mo(n):n,ul=n=>cl.has(n)?mo(n):n;class hl{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=al(e)}addField(e){re(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function pl(n,e){var t,i,r,s,a,o;const d=[];let c;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=ho(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:ol(l.name),u.repeated=(i=l.repeated)!==null&&i!==void 0?i:!1,l.kind=="scalar"&&(u.L=(r=l.L)!==null&&r!==void 0?r:_t.BIGINT),u.delimited=(s=l.delimited)!==null&&s!==void 0?s:!1,u.req=(a=l.req)!==null&&a!==void 0?a:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=_.BYTES&&l.T!=_.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!c||c.name!=h)&&(c=new hl(h)),u.oneof=c,c.addField(u)}d.push(u)}return d}const v=rl("proto3",n=>new sl(n,e=>pl(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=ni(e.T,e.L);break}}});class Re extends qr{constructor(e){super(),this.seconds=te.zero,this.nanos=0,v.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(v.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=te.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Re.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Re({seconds:te.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Re().fromBinary(e,t)}static fromJson(e,t){return new Re().fromJson(e,t)}static fromJsonString(e,t){return new Re().fromJsonString(e,t)}static equals(e,t){return v.util.equals(Re,e,t)}}Re.runtime=v;Re.typeName="google.protobuf.Timestamp";Re.fields=v.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const ml=v.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Re},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:fl,repeated:!0},{no:5,name:"events",kind:"message",T:vl,repeated:!0}]),fl=v.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:gl,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),gl=v.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Re},{no:3,name:"value",kind:"scalar",T:2}]),vl=v.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:Re},{no:7,name:"normalized_end_timestamp",kind:"message",T:Re,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),fo=v.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),qe=v.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),de=v.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"}]),jr=v.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Ht=v.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ei=v.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),He=v.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"}]),nt=v.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"}]),bl=v.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),pe=v.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"}]),ri=v.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),gn=v.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:rn,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:Mo}]),rn=v.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),yl=v.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:v.getEnumType(de),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}]),Ft=v.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:v.getEnumType(zt)},{no:4,name:"tracks",kind:"message",T:Kt,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:yl},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:v.getEnumType(_i)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:v.getEnumType(He)},{no:18,name:"kind_details",kind:"enum",T:v.getEnumType(kl),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:vn,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5},{no:21,name:"capabilities",kind:"enum",T:v.getEnumType(wi),repeated:!0}]),zt=v.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),_i=v.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"}]),kl=v.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"}]),H=v.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Tl=v.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:kt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(bo)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Kt=v.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:v.getEnumType(qe)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:v.getEnumType(de)},{no:10,name:"layers",kind:"message",T:kt,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:Tl,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:v.getEnumType(H)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Mo},{no:19,name:"audio_features",kind:"enum",T:v.getEnumType(pe),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(fo)},{no:21,name:"packet_trailer_features",kind:"enum",T:v.getEnumType(ri),repeated:!0}]),vn=v.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:v.getEnumType(H)},{no:5,name:"frame_encoding",kind:"message",T:go,opt:!0},{no:6,name:"schema",kind:"message",T:Wr,opt:!0}]),go=v.makeMessageType("livekit.DataTrackFrameEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:v.getEnumType(Sl),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),Sl=v.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"}]),Cl=v.makeMessageType("livekit.DataTrackSchemaEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:v.getEnumType(El),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),El=v.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"}]),Wr=v.makeMessageType("livekit.DataTrackSchemaId",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:Cl}]),_l=v.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),Hr=v.makeMessageType("livekit.DataBlobKey",()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:Wr,oneof:"key"}]),vo=v.makeMessageType("livekit.DataBlob",()=>[{no:1,name:"key",kind:"message",T:Hr},{no:2,name:"contents",kind:"scalar",T:12}]),kt=v.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(jr)},{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}]),bo=v.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"}]),Ce=v.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:v.getEnumType(Tt)},{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:Kr,oneof:"value"},{no:3,name:"speaker",kind:"message",T:wl,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:So,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Pl,oneof:"value"},{no:8,name:"metrics",kind:"message",T:ml,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:sn,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Gr,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:bn,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:zr,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:yn,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:lt,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Jr,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:yo,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Tt=v.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),yo=v.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:v.getEnumType(H)},{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}]),ko=v.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Kr,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:sn,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Gr,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:bn,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:zr,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:yn,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:lt,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Jr,oneof:"value"}]),wl=v.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:To,repeated:!0}]),To=v.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}]),Kr=v.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}]),So=v.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Pl=v.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:Rl,repeated:!0}]),Rl=v.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no
vendor: 16,384 bytes, line 3
3: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}]),sn=v.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}]),Gr=v.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}]),bn=v.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),zr=v.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:Co,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),Co=v.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}]),Eo=v.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),_o=v.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:v.getEnumType(wo)},{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}]),wo=v.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Po=v.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:v.getEnumType(Ro)},{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},{no:13,name:"capabilities",kind:"enum",T:v.getEnumType(wi),repeated:!0}]),Ro=v.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"}]),wi=v.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),Io=v.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:qs},{no:2,name:"screen",kind:"message",T:qs},{no:3,name:"resume_connection",kind:"enum",T:v.getEnumType(Ei)},{no:4,name:"disabled_codecs",kind:"message",T:Il},{no:5,name:"force_relay",kind:"enum",T:v.getEnumType(Ei)}]),qs=v.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:v.getEnumType(Ei)}]),Il=v.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:rn,repeated:!0},{no:2,name:"publish",kind:"message",T:rn,repeated:!0}]),Mo=v.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),hr=v.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),ke=v.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),Do=v.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:v.getEnumType(hr)},{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"}),Ao=v.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),yn=v.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:v.getEnumType(H)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Do,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Ao,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:v.getEnumType(ke)}],{localName:"DataStream_Header"}),lt=v.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"}),Jr=v.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"}),Ml=v.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),Ve=v.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),pr=v.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Dl=v.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Al=v.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:wt,oneof:"message"},{no:2,name:"answer",kind:"message",T:wt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:kn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Pi,oneof:"message"},{no:5,name:"mute",kind:"message",T:Tn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Sn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Lo,oneof:"message"},{no:8,name:"leave",kind:"message",T:Cn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Uo,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:qo,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:is,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ye,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:es,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Wo,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Zr,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:xo,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:Qr,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:$r,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Oo,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:ql,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:jl,oneof:"message"}]),Vs=v.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:xl,oneof:"message"},{no:2,name:"answer",kind:"message",T:wt,oneof:"message"},{no:3,name:"offer",kind:"message",T:wt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:kn,oneof:"message"},{no:5,name:"update",kind:"message",T:Bl,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Xr,oneof:"message"},{no:8,name:"leave",kind:"message",T:Cn,oneof:"message"},{no:9,name:"mute",kind:"message",T:Tn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Hl,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Kl,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:zl,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Ql,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:$l,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Zl,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Fl,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Ul,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:tu,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:ru,oneof:"message"},{no:22,name:"request_response",kind:"message",T:su,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:au,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:eu,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:du,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Xl,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:Yr,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Ol,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:Nl,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:Vl,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:Wl,oneof:"message"}]),mr=v.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:kt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(bo)}]),Pi=v.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:v.getEnumType(qe)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:v.getEnumType(de)},{no:9,name:"layers",kind:"message",T:kt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:mr,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:v.getEnumType(H)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(fo)},{no:17,name:"audio_features",kind:"enum",T:v.getEnumType(pe),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:v.getEnumType(ri),repeated:!0}]),Qr=v.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:v.getEnumType(H)},{no:4,name:"frame_encoding",kind:"message",T:go,opt:!0},{no:5,name:"schema",kind:"message",T:Wr,opt:!0}]),Yr=v.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:vn}]),$r=v.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),Ol=v.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:vn}]),Nl=v.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Ll}}]),Ll=v.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"}),kn=v.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:v.getEnumType(Ve)},{no:3,name:"final",kind:"scalar",T:8}]),Tn=v.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),xl=v.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:gn},{no:2,name:"participant",kind:"message",T:Ft},{no:3,name:"other_participants",kind:"message",T:Ft,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Fo,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:Io},{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:_o},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:rn,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Ul=v.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Fo,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Io},{no:3,name:"server_info",kind:"message",T:_o},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Xr=v.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Kt}]),Fl=v.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),wt=v.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}}]),Bl=v.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Ft,repeated:!0}]),Sn=v.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:Eo,repeated:!0}]),Oo=v.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:No,repeated:!0}]),No=v.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:_l}],{localName:"UpdateDataSubscription_Update"}),ql=v.makeMessageType("livekit.StoreDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:vo}]),Vl=v.makeMessageType("livekit.StoreDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:Hr}]),jl=v.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:Hr}]),Wl=v.makeMessageType("livekit.GetDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:vo}]),Lo=v.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:v.getEnumType(jr)},{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}]),Zr=v.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:v.getEnumType(pe),repeated:!0}]),xo=v.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}]),Cn=v.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:v.getEnumType(He)},{no:3,name:"action",kind:"enum",T:v.getEnumType(Jt)},{no:4,name:"regions",kind:"message",T:iu}]),Jt=v.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Uo=v.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:kt,repeated:!0}]),es=v.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no
vendor: 5,951 bytes, line 3
3: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}]),Fo=v.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}]),Hl=v.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:To,repeated:!0}]),Kl=v.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:gn}]),Gl=v.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:v.getEnumType(Ht)},{no:3,name:"score",kind:"scalar",T:2}]),zl=v.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Gl,repeated:!0}]),Jl=v.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:v.getEnumType(pr)}]),Ql=v.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Jl,repeated:!0}]),ts=v.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(jr)},{no:2,name:"enabled",kind:"scalar",T:8}]),Yl=v.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ts,repeated:!0}]),$l=v.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ts,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Yl,repeated:!0}]),Xl=v.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Ml,repeated:!0}]),Bo=v.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}]),qo=v.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Bo,repeated:!0}]),Zl=v.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}]),eu=v.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:gn},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Ft},{no:4,name:"other_participants",kind:"message",T:Ft,repeated:!0}]),is=v.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:wt},{no:2,name:"subscription",kind:"message",T:Sn},{no:3,name:"publish_tracks",kind:"message",T:Xr,repeated:!0},{no:4,name:"data_channels",kind:"message",T:jo,repeated:!0},{no:5,name:"offer",kind:"message",T:wt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Vo,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:Yr,repeated:!0}]),Vo=v.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),jo=v.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:v.getEnumType(Ve)}]),Ye=v.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:v.getEnumType(Dl),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"}]),Wo=v.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),tu=v.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),iu=v.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:nu,repeated:!0}]),nu=v.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}]),ru=v.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:v.getEnumType(bl)}]),su=v.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:v.getEnumType(Mt)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:kn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Pi,oneof:"request"},{no:6,name:"mute",kind:"message",T:Tn,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:es,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Zr,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:xo,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:Qr,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:$r,oneof:"request"}]),Mt=v.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"}
vendor: 4,445 bytes, line 3
3,{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),au=v.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Ho=v.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}]),ou=v.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Po},{no:2,name:"connection_settings",kind:"message",T:Ho},{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:Pi,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:wt},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:v.getEnumType(nt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:is}]),cu=v.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:v.getEnumType(fr)},{no:2,name:"join_request",kind:"scalar",T:12}]),fr=v.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),du=v.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function lu(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var zi={exports:{}},uu=zi.exports,js;function hu(){return js||(js=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(uu,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},a=null;function o(g,k){var T=g[k];if(typeof T.bind=="function")return T.bind(g);try{return Function.prototype.bind.call(T,g)}catch{return function(){return Function.prototype.apply.apply(T,[g,arguments])}}}function d(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&i?d:console[g]!==void 0?o(console,g):console.log!==void 0?o(console,"log"):e}function l(){for(var g=this.getLevel(),k=0;k<r.length;k++){var T=r[k];this[T]=k<g?e:this.methodFactory(T,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function u(g){return function(){typeof console!==t&&(l.call(this),this[g].apply(this,arguments))}}function h(g,k,T){return c(g)||u.apply(this,arguments)}function p(g,k){var T=this,S,L,b,y="loglevel";typeof g=="string"?y+=":"+g:typeof g=="symbol"&&(y=void 0);function C(O){var F=(r[O]||"silent").toUpperCase();if(!(typeof window===t||!y)){try{window.localStorage[y]=F;return}catch{}try{window.document.cookie=encodeURIComponent(y)+"="+F+";"}catch{}}}function I(){var O;if(!(typeof window===t||!y)){try{O=window.localStorage[y]}catch{}if(typeof O===t)try{var F=window.document.cookie,X=encodeURIComponent(y),ie=F.indexOf(X+"=");ie!==-1&&(O=/^([^;]+)/.exec(F.slice(ie+X.length+1))[1])}catch{}return T.levels[O]===void 0&&(O=void 0),O}}function A(){if(!(typeof window===t||!y)){try{window.localStorage.removeItem(y)}catch{}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function B(O){var F=O;if(typeof F=="string"&&T.levels[F.toUpperCase()]!==void 0&&(F=T.levels[F.toUpperCase()]),typeof F=="number"&&F>=0&&F<=T.levels.SILENT)return F;throw new TypeError("log.setLevel() called with invalid level: "+O)}T.name=g,T.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},T.methodFactory=k||h,T.getLevel=function(){return b??L??S},T.setLevel=function(O,F){return b=B(O),F!==!1&&C(b),l.call(T)},T.setDefaultLevel=function(O){L=B(O),I()||T.setLevel(O,!1)},T.resetLevel=function(){b=null,A(),l.call(T)},T.enableAll=function(O){T.setLevel(T.levels.TRACE,O)},T.disableAll=function(O){T.setLevel(T.levels.SILENT,O)},T.rebuild=function(){if(a!==T&&(S=B(a.getLevel())),l.call(T),a===T)for(var O in s)s[O].rebuild()},S=B(a?a.getLevel():"WARN");var D=I();D!=null&&(b=B(D)),l.call(T)}
3a=new p,a.getLogger=function(k){if(typeof k!="symbol"&&typeof k!="string"||k==="")throw new TypeError("You must supply a name when creating a logger.");var T=s[k];return T||(T=s[k]=new p(k,a.methodFactory)),T};var f=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=f),a},a.getLoggers=function(){return s},a.default=a,a})})(zi)),zi.exports}var En=hu(),gr;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(gr||(gr={}));var oe;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee",n.DataTracks="livekit-data-tracks",n.Region="livekit-region",n.ICE="livekit-ice"})(oe||(oe={}));let U=En.getLogger(oe.Default);Object.values(oe).map(n=>En.getLogger(n));U.setDefaultLevel(gr.info);function ye(n,e){const t=En.getLogger(n);return t.setDefaultLevel(U.getLevel()),e?pu(t,e):t}function pu(n,e){const t=r=>(s,a)=>{const o=e(),d=o||a?Object.assign(Object.assign({},o),a):void 0;n[r](s,d)},i=Object.create(n);return i.trace=t("trace"),i.debug=t("debug"),i.info=t("info"),i.warn=t("warn"),i.error=t("error"),i}const mu=En.getLogger(oe.E2EE),li=7e3,fu=[0,300,4*300,9*300,16*300,li,li,li,li,li];class gu{constructor(e){this._retryDelays=e!==void 0?[...e]:fu}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function vu(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(n);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(n,i[r])&&(t[i[r]]=n[i[r]]);return t}function m(n,e,t,i){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(l){try{c(i.next(l))}catch(u){a(u)}}function d(l){try{c(i.throw(l))}catch(u){a(u)}}function c(l){l.done?s(l.value):r(l.value).then(o,d)}c((i=i.apply(n,e||[])).next())})}function Ws(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ut(n){return this instanceof ut?(this.v=n,this):new ut(n)}function Ko(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),r[Symbol.asyncIterator]=function(){return this},r;function a(p){return function(f){return Promise.resolve(f).then(p,u)}}function o(p,f){i[p]&&(r[p]=function(g){return new Promise(function(k,T){s.push([p,g,k,T])>1||d(p,g)})},f&&(r[p]=f(r[p])))}function d(p,f){try{c(i[p](f))}catch(g){h(s[0][3],g)}}function c(p){p.value instanceof ut?Promise.resolve(p.value.v).then(l,u):h(s[0][2],p)}function l(p){d("next",p)}function u(p){d("throw",p)}function h(p,f){p(f),s.shift(),s.length&&d(s[0][0],s[0][1])}}function bu(n){var e,t;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,s){e[r]=n[r]?function(a){return(t=!t)?{value:ut(n[r](a)),done:!1}:s?s(a):a}:s}}function Le(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof Ws=="function"?Ws(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(a){return new Promise(function(o,d){a=n[s](a),r(o,d,a.done,a.value)})}}function r(s,a,o,d){Promise.resolve(d).then(function(c){s({value:c,done:o})},a)}}var Ui={exports:{}},Hs;
vendor: 53,147 bytes, lines 3-37
3function yu(){if(Hs)return Ui.exports;Hs=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(y,C,I){return Function.prototype.apply.call(y,C,I)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(y){return Object.getOwnPropertyNames(y).concat(Object.getOwnPropertySymbols(y))}:t=function(y){return Object.getOwnPropertyNames(y)};function i(b){console&&console.warn&&console.warn(b)}var r=Number.isNaN||function(y){return y!==y};function s(){s.init.call(this)}Ui.exports=s,Ui.exports.once=T,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(b){if(typeof b!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof b)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(b){if(typeof b!="number"||b<0||r(b))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+b+".");a=b}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(y){if(typeof y!="number"||y<0||r(y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+y+".");return this._maxListeners=y,this};function d(b){return b._maxListeners===void 0?s.defaultMaxListeners:b._maxListeners}s.prototype.getMaxListeners=function(){return d(this)},s.prototype.emit=function(y){for(var C=[],I=1;I<arguments.length;I++)C.push(arguments[I]);var A=y==="error",B=this._events;if(B!==void 0)A=A&&B.error===void 0;else if(!A)return!1;if(A){var D;if(C.length>0&&(D=C[0]),D instanceof Error)throw D;var O=new Error("Unhandled error."+(D?" ("+D.message+")":""));throw O.context=D,O}var F=B[y];if(F===void 0)return!1;if(typeof F=="function")e(F,this,C);else for(var X=F.length,ie=f(F,X),I=0;I<X;++I)e(ie[I],this,C);return!0};function c(b,y,C,I){var A,B,D;if(o(C),B=b._events,B===void 0?(B=b._events=Object.create(null),b._eventsCount=0):(B.newListener!==void 0&&(b.emit("newListener",y,C.listener?C.listener:C),B=b._events),D=B[y]),D===void 0)D=B[y]=C,++b._eventsCount;else if(typeof D=="function"?D=B[y]=I?[C,D]:[D,C]:I?D.unshift(C):D.push(C),A=d(b),A>0&&D.length>A&&!D.warned){D.warned=!0;var O=new Error("Possible EventEmitter memory leak detected. "+D.length+" "+String(y)+" listeners added. Use emitter.setMaxListeners() to increase limit");O.name="MaxListenersExceededWarning",O.emitter=b,O.type=y,O.count=D.length,i(O)}return b}s.prototype.addListener=function(y,C){return c(this,y,C,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(y,C){return c(this,y,C,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(b,y,C){var I={fired:!1,wrapFn:void 0,target:b,type:y,listener:C},A=l.bind(I);return A.listener=C,I.wrapFn=A,A}s.prototype.once=function(y,C){return o(C),this.on(y,u(this,y,C)),this},s.prototype.prependOnceListener=function(y,C){return o(C),this.prependListener(y,u(this,y,C)),this},s.prototype.removeListener=function(y,C){var I,A,B,D,O;if(o(C),A=this._events,A===void 0)return this;if(I=A[y],I===void 0)return this;if(I===C||I.listener===C)--this._eventsCount===0?this._events=Object.create(null):(delete A[y],A.removeListener&&this.emit("removeListener",y,I.listener||C));else if(typeof I!="function"){for(B=-1,D=I.length-1;D>=0;D--)if(I[D]===C||I[D].listener===C){O=I[D].listener,B=D;break}if(B<0)return this;B===0?I.shift():g(I,B),I.length===1&&(A[y]=I[0]),A.removeListener!==void 0&&this.emit("removeListener",y,O||C)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(y){var C,I,A;if(I=this._events,I===void 0)return this;if(I.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):I[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete I[y]),this;if(arguments.length===0){var B=Object.keys(I),D;for(A=0;A<B.length;++A)D=B[A],D!=="removeListener"&&this.removeAllListeners(D);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(C=I[y],typeof C=="function")this.removeListener(y,C);else if(C!==void 0)for(A=C.length-1;A>=0;A--)this.removeListener(y,C[A]);return this};function h(b,y,C){var I=b._events;if(I===void 0)return[];var A=I[y];return A===void 0?[]:typeof A=="function"?C?[A.listener||A]:[A]:C?k(A):f(A,A.length)}s.prototype.listeners=function(y){return h(this,y,!0)},s.prototype.rawListeners=function(y){return h(this,y,!1)},s.listenerCount=function(b,y){return typeof b.listenerCount=="function"?b.listenerCount(y):p.call(b,y)},s.prototype.listenerCount=p;function p(b){var y=this._events;if(y!==void 0){var C=y[b];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(b,y){for(var C=new Array(y),I=0;I<y;++I)C[I]=b[I];return C}function g(b,y){for(;y+1<b.length;y++)b[y]=b[y+1];b.pop()}function k(b){for(var y=new Array(b.length),C=0;C<y.length;++C)y[C]=b[C].listener||b[C];return y}function T(b,y){return new Promise(function(C,I){function A(D){b.removeListener(y,B),I(D)}function B(){typeof b.removeListener=="function"&&b.removeListener("error",A),C([].slice.call(arguments))}L(b,y,B,{once:!0}),y!=="error"&&S(b,A,{once:!0})})}function S(b,y,C){typeof b.on=="function"&&L(b,"error",y,C)}function L(b,y,C,I){if(typeof b.on=="function")I.once?b.once(y,C):b.on(y,C);else if(typeof b.addEventListener=="function")b.addEventListener(y,function A(B){I.once&&b.removeEventListener(y,A),C(B)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return Ui.exports}var Me=yu();let Go=!0,zo=!0;function fi(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function Vt(n,e,t){if(!n.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){ns("Unable to polyfill events");return}const r=n.RTCPeerConnection.prototype,s=r.addEventListener;r.addEventListener=function(o,d){if(o!==e)return s.apply(this,arguments);const c=l=>{const u=t(l);u&&(d.handleEvent?d.handleEvent(u):d(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(d,c),s.apply(this,[o,c])};const a=r.removeEventListener;r.removeEventListener=function(o,d){if(o!==e||!this._eventMap||!this._eventMap[e])return a.apply(this,arguments);if(!this._eventMap[e].has(d))return a.apply(this,arguments);const c=this._eventMap[e].get(d);return this._eventMap[e].delete(d),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[o,c])},Object.defineProperty(r,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function ku(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Go=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function Tu(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(zo=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function ns(){if(typeof window=="object"){if(Go)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function rs(n,e){zo&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Su(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const t=n.navigator;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(i){const r=parseInt(i.version,10);if(r>=90)return{browser:"chrome",version:r}}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(fi(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(fi(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(fi(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=fi(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function Ks(n){return Object.prototype.toString.call(n)==="[object Object]"}function Jo(n){return Ks(n)?Object.keys(n).reduce(function(e,t){const i=Ks(n[t]),r=i?Jo(n[t]):n[t],s=i&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):n}function vr(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?vr(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(r=>{vr(n,n.get(r),t)})}))}function Gs(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&vr(n,o,r)})}),r}const zs=ns;function Qo(n,e){if(e.version>=64)return;const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const d={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const l=typeof o[c]=="object"?o[c]:{ideal:o[c]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,p){return h?h+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(l.ideal!==void 0){d.optional=d.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",c)]=l.ideal,d.optional.push(h),h={},h[u("max",c)]=l.ideal,d.optional.push(h)):(h[u("",c)]=l.ideal,d.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[u("",c)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[u(h,c)]=l[h])})}),o.advanced&&(d.optional=(d.optional||[]).concat(o.advanced)),d},r=function(o,d){if(e.version>=61)return d(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const l=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(c.exact==="environment"||c.ideal==="environment"?u=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(f=>f.kind==="videoinput");let p=h.find(f=>u.some(g=>f.label.toLowerCase().includes(g)));return!p&&h.length&&u.includes("back")&&(p=h[h.length-1]),p&&(o.video.deviceId=c.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=i(o.video),zs("chrome: "+JSON.stringify(o)),d(o)})}o.video=i(o.video)}return zs("chrome: "+JSON.stringify(o)),d(o)},s=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,d,c){r(o,l=>{t.webkitGetUserMedia(l,d,u=>{c&&c(s(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(d){return r(d,c=>o(c).then(l=>{if(c.audio&&!l.getAudioTracks().length||c.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(s(l))))}}}function Yo(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function $o(n,e){if(!(e.version>102))if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(i){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=i)},enumerable:!0,configurable:!0});const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=r=>{r.stream.addEventListener("addtrack",s=>{let a;n.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===s.track.id):a={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=a,o.transceiver={receiver:a},o.streams=[r.stream],this.dispatchEvent(o)}),r.stream.getTracks().forEach(s=>{let a;n.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===s.id):a={track:s};const o=new Event("track");o.track=s,o.receiver=a,o.transceiver={receiver:a},o.streams=[r.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Vt(n,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function Xo(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,d){let c=r.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(a=>{const o=this._senders.find(d=>d.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Zo(n,e){if(e.version>=67||!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const i=n.RTCPeerConnection.prototype.getSenders;i&&(n.RTCPeerConnection.prototype.getSenders=function(){const a=i.apply(this,[]);return a.forEach(o=>o._pc=this),a});const r=n.RTCPeerConnection.prototype.addTrack;r&&(n.RTCPeerConnection.prototype.addTrack=function(){const a=r.apply(this,arguments);return a._pc=this,a}),n.RTCRtpSender.prototype.getStats=function(){const a=this;return this._pc.getStats().then(o=>Gs(o,a.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const i=n.RTCPeerConnection.prototype.getReceivers;i&&(n.RTCPeerConnection.prototype.getReceivers=function(){const s=i.apply(this,[]);return s.forEach(a=>a._pc=this),s}),Vt(n,"track",r=>(r.receiver._pc=r.srcElement,r)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>Gs(a,s.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const t=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const r=arguments[0];let s,a,o;return this.getSenders().forEach(d=>{d.track===r&&(s?o=!0:s=d)}),this.getReceivers().forEach(d=>(d.track===r&&(a?o=!0:a=d),d.track===r)),o||s&&a?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():a?a.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ec(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const d=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(d)===-1&&this._shimmedLocalStreams[o.id].push(d):this._shimmedLocalStreams[o.id]=[o,d],d};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(u=>u.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const d=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const d=this._shimmedLocalStreams[o].indexOf(a);d!==-1&&this._shimmedLocalStreams[o].splice(d,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),r.apply(this,arguments)}}function tc(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ec(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(p=>p.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const r=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(g=>g===l))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(g=>g.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[u.id];if(f)f.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new n.MediaStream([l]);this._streams[u.id]=g,this._reverseStreams[g.id]=u,this.addStream(g)}return this.getSenders().find(g=>g.track===l)};function s(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const p=c._reverseStreams[h],f=c._streams[p.id];u=u.replace(new RegExp(f.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const p=c._reverseStreams[h],f=c._streams[p.id];u=u.replace(new RegExp(p.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(c){const l=n.RTCPeerConnection.prototype[c],u={[c](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[f=>{const g=s(this,f);h[0].apply(null,[g])},f=>{h[1]&&h[1].apply(null,f)},arguments[2]]):l.apply(this,arguments).then(f=>s(this,f))}};n.RTCPeerConnection.prototype[c]=u[c]});const o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const d=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const c=d.get.apply(this);return c.type===""?c:s(this,c)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(g=>l.track===g)&&(h=this._streams[p])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function br(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=r[t]})}function ic(n,e){e.version>102||Vt(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var Js=Object.freeze({__proto__:null,fixNegotiationNeeded:ic,shimAddTrackRemoveTrack:tc,shimAddTrackRemoveTrackWithNative:ec,shimGetSendersWithDtmf:Xo,shimGetUserMedia:Qo,shimMediaStream:Yo,shimOnTrack:$o,shimPeerConnection:br,shimSenderReceiverGetStats:Zo});function nc(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(r,s,a){rs("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(a,o,d){o in a&&!(d in a)&&(a[d]=a[o],delete a[o])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a.audio,"autoGainControl","mozAutoGainControl"),r(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return r(o,"mozAutoGainControl","autoGainControl"),r(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o,"autoGainControl","mozAutoGainControl"),r(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Cu(n,e){n.navigator.mediaDevices&&(n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)}))}function rc(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function yr(n,e){typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection)||(!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=r[t]}))}function sc(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection)||e.version>=151)return;const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const s=Array.prototype.slice.call(arguments),a=s[0],o=s[1],d=s[2];return this.signalingState==="closed"?Promise.resolve(new Map):i.apply(this,[a||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((u,h)=>{c.set(h,Object.assign({},u,{type:t[u.type]||u.type}))})}return c}).then(o,d)}}function ac(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=t.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function oc(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i}),Vt(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function cc(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){rs("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function dc(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function lc(n,e){if(!(typeof n=="object"&&n.RTCPeerConnection)||e.version>=110)return;const t=n.RTCPeerConnection.prototype.addTransceiver;t&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let r=arguments[1]&&arguments[1].sendEncodings;r===void 0&&(r=[]),r=[...r];const s=r.length>0;s&&r.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const a=t.apply(this,arguments);if(s){const o=a.sender,d=o.getParameters();(!("encodings"in d)||d.encodings.length===1&&Object.keys(d.encodings[0]).length===0)&&(d.encodings=r,o.sendEncodings=r,this.setParametersPromises.push(o.setParameters(d).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return a})}function uc(n,e){if(!(typeof n=="object"&&n.RTCRtpSender)||e.version>=110)return;const t=n.RTCRtpSender.prototype.getParameters;t&&(n.RTCRtpSender.prototype.getParameters=function(){const r=t.apply(this,arguments);return"encodings"in r||(r.encodings=[].concat(this.sendEncodings||[{}])),r})}function hc(n,e){if(!(typeof n=="object"&&n.RTCPeerConnection)||e.version>=110)return;const t=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function pc(n,e){if(!(typeof n=="object"&&n.RTCPeerConnection)||e.version>=110)return;const t=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Qs=Object.freeze({__proto__:null,shimAddTransceiver:lc,shimCreateAnswer:pc,shimCreateOffer:hc,shimGetDisplayMedia:Cu,shimGetParameters:uc,shimGetStats:sc,shimGetUserMedia:nc,shimOnTrack:rc,shimPeerConnection:yr,shimRTCDataChannel:dc,shimReceiverGetStats:oc,shimRemoveStream:cc,shimSenderGetStats:ac});function mc(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>e.call(this,r,i)),i.getVideoTracks().forEach(r=>e.call(this,r,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<r;a++)s[a-1]=arguments[a];return s&&s.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function fc(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function gc(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(c,l),Promise.resolve()):h},e.createAnswer=function(c,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return l?(h.then(c,l),Promise.resolve()):h};let o=function(d,c,l){const u=r.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(d,c,l){const u=s.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(d,c,l){const u=a.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.addIceCandidate=o}function vc(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>i(bc(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,r,s){e.mediaDevices.getUserMedia(i).then(r,s)}).bind(e))}function bc(n){return n&&n.video!==void 0?Object.assign({},n,{video:Jo(n.video)}):n}function yc(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(rs("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(i.iceServers[a])}i.iceServers=s}return new e(i,r)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function kc(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Tc(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Sc(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var Ys=Object.freeze({__proto__:null,shimAudioContext:Sc,shimCallbacksAPI:gc,shimConstraints:bc,shimCreateOfferLegacy:Tc,shimGetUserMedia:vc,shimLocalStreamsAPI:mc,shimRTCIceServerUrls:yc,shimRemoteStreamsAPI:fc,shimTrackEventTransceiver:kc}),jn={exports:{}},$s;function Eu(){return $s||($s=1,(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(` 4`).map(i=>i.trim())},e.splitSections=function(t){return t.split(` 5m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r 6`)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(r=>r.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const r={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let s=8;s<i.length;s+=2)switch(i[s]){case"raddr":r.relatedAddress=i[s+1];break;case"rport":r.relatedPort=parseInt(i[s+1],10);break;case"tcptype":r.tcpType=i[s+1];break;case"ufrag":r.ufrag=i[s+1],r.usernameFragment=i[s+1];break;default:r[i[s]]===void 0&&(r[i[s]]=i[s+1]);break}return r},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const r=t.component;r==="rtp"?i.push(1):r==="rtcp"?i.push(2):i.push(r),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const s=t.type;return i.push("typ"),i.push(s),s!=="host"&&t.relatedAddress&&t.relatedPort!==void 0&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const r={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),r.name=i[0],r.clockRate=parseInt(i[1],10),r.channels=i.length===3?parseInt(i[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const r=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(r!==1?"/"+r:"")+`\r 7`},e.parseExtmap=function(t){const i=t.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r 8`},e.parseFmtp=function(t){const i={};let r;const s=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)r=s[a].trim().split("="),i[r[0].trim()]=r[1];return i},e.writeFmtp=function(t){let i="",r=t.payloadType;if(t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const s=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?s.push(a+"="+t.parameters[a]):s.push(a)}),i+="a=fmtp:"+r+" "+s.join(";")+`\r 9`}return i},e.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(t){let i="",r=t.payloadType;return t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{i+="a=rtcp-fb:"+r+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r 10`}),i},e.parseSsrcMedia=function(t){const i=t.indexOf(" "),r={ssrc:parseInt(t.substring(7,i),10)},s=t.indexOf(":",i);return s>-1?(r.attribute=t.substring(i+1,s),r.value=t.substring(s+1)):r.attribute=t.substring(i+1),r},e.parseSsrcGroup=function(t){const i=t.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(r=>parseInt(r,10))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const i=t.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,i){let r="a=setup:"+i+`\r 11`;return t.fingerprints.forEach(s=>{r+="a=fingerprint:"+s.algorithm+" "+s.value+`\r 12`}),r},e.parseCryptoLine=function(t){const i=t.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r 13`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const r=e.matchPrefix(t+i,"a=ice-ufrag:")[0],s=e.matchPrefix(t+i,"a=ice-pwd:")[0];return r&&s?{usernameFragment:r.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r 14a=ice-pwd:`+t.password+`\r 15`;return t.iceLite&&(i+=`a=ice-lite\r 16`),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");i.profile=s[2];for(let o=3;o<s.length;o++){const d=s[o],c=e.matchPrefix(t,"a=rtpmap:"+d+" ")[0];if(c){const l=e.parseRtpMap(c),u=e.matchPrefix(t,"a=fmtp:"+d+" ");switch(l.parameters=u.length?e.parseFmtp(u[0]):{},l.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+d+" ").map(e.parseRtcpFb),i.codecs.push(l),l.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(l.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{i.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(o=>{a.forEach(d=>{o.rtcpFeedback.find(l=>l.type===d.type&&l.parameter===d.parameter)||o.rtcpFeedback.push(d)})}),i},e.writeRtpDescription=function(t,i){let r="";r+="m="+t+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r 17`,r+=`c=IN IP4 0.0.0.0\r 18`,r+=`a=rtcp:9 IN IP4 0.0.0.0\r 19`,i.codecs.forEach(a=>{r+=e.writeRtpMap(a),r+=e.writeFmtp(a),r+=e.writeRtcpFb(a)});let s=0;return i.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(r+="a=maxptime:"+s+`\r 20`),i.headerExtensions&&i.headerExtensions.forEach(a=>{r+=e.writeExtmap(a)}),r},e.parseRtpEncodingParameters=function(t){const i=[],r=e.parseRtpParameters(t),s=r.fecMechanisms.indexOf("RED")!==-1,a=r.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),d=o.length>0&&o[0].ssrc;let c;const l=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(f=>parseInt(f,10)));l.length>0&&l[0].length>1&&l[0][0]===d&&(c=l[0][1]),r.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let p={ssrc:d,codecPayloadType:parseInt(h.parameters.apt,10)};d&&c&&(p.rtx={ssrc:c}),i.push(p),s&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:d,mechanism:a?"red+ulpfec":"red"},i.push(p))}}),i.length===0&&d&&i.push({ssrc:d});let u=e.matchPrefix(t,"b=");return u.length&&(u[0].indexOf("b=TIAS:")===0?u=parseInt(u[0].substring(7),10):u[0].indexOf("b=AS:")===0?u=parseInt(u[0].substring(5),10)*1e3*.95-2e3*8:u=void 0,i.forEach(h=>{h.maxBitrate=u})),i},e.parseRtcpParameters=function(t){const i={},r=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=s.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return i.mux=a.length>0,i},e.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r 21`),t.mux&&(i+=`a=rtcp-mux\r 22`),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r 23`),i},e.parseMsid=function(t){let i;const r=e.matchPrefix(t,"a=msid:");if(r.length===1)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return i=s[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:");let s;r.length>0&&(s=parseInt(r[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const d=o[0].substring(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,i){let r=[];return t.protocol!=="DTLS/SCTP"?r=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r 24`,`c=IN IP4 0.0.0.0\r 25`,"a=sctp-port:"+i.port+`\r 26`]:r=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\r 27`,`c=IN IP4 0.0.0.0\r 28`,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r 29`],i.maxMessageSize!==void 0&&r.push("a=max-message-size:"+i.maxMessageSize+`\r 30`),r.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,r){let s;const a=i!==void 0?i:2;return t?s=t:s=e.generateSessionId(),`v=0\r 31o=`+(r||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r 32s=-\r 33t=0 0\r 34`},e.getDirection=function(t,i){const r=e.splitLines(t);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const r=e.splitLines(t)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(t){const r=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let r=0;r<i.length;r++)if(i[r].length<2||i[r].charAt(1)!=="=")return!1;return!0},n.exports=e})(jn)),jn.exports}var Cc=Eu(),Qt=lu(Cc),_u=gd({__proto__:null,default:Qt},[Cc]);function Ji(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const r=new e(i),s=Qt.parseCandidate(i.candidate);for(const a in s)a in r||Object.defineProperty(r,a,{value:s[a]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new e(i)},n.RTCIceCandidate.prototype=e.prototype,Vt(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function kr(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||Vt(n,"icecandidate",e=>{if(e.candidate){const t=Qt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Qi(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>102||e.browser==="firefox"&&e.version>=113)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const d=Qt.splitSections(o.sdp);return d.shift(),d.some(c=>{const l=Qt.parseMLine(c);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},i=function(o){const d=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;const c=parseInt(d[1],10);return c!==c?-1:c},r=function(o){let d=65536;return e.browser==="firefox"&&(e.version<57?o===-1?d=16384:d=2147483637:e.version<60?d=e.version===57?65535:65536:d=2147483637),d},s=function(o,d){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const l=Qt.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?c=parseInt(l[0].substring(19),10):e.browser==="firefox"&&d!==-1&&(c=2147483637),c},a=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76&&this.getConfiguration().sdpSemantics==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0}),t(arguments[0])){const d=i(arguments[0]),c=r(d),l=s(arguments[0],d);let u;c===0&&l===0?u=Number.POSITIVE_INFINITY:c===0||l===0?u=Math.max(c,l):u=Math.min(c,l);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return a.apply(this,arguments)}}function Yi(n,e){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype)||e.browser==="chrome"&&e.version>=149||e.browser==="firefox"&&e.version>60)return;function t(r,s){const a=r.send;r.send=function(){const d=arguments[0],c=d.length||d.size||d.byteLength;if(r.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return a.apply(r,arguments)}}const i=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const s=i.apply(this,arguments);return t(s,this),s},Vt(n,"datachannel",r=>(t(r.channel,r.target),r))}function Tr(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",r);s.dispatchEvent(a)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Sr(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(` 35a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(` 36`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(` 37`);n.RTCSessionDescription&&r instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:r.type,sdp:s}
37):r.sdp=s}return t.apply(this,arguments)}}function $i(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Xi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var wu=Object.freeze({__proto__:null,removeExtmapAllowMixed:Sr,shimAddIceCandidateNullOrEmpty:$i,shimConnectionState:Tr,shimMaxMessageSize:Qi,shimParameterlessSetLocalDescription:Xi,shimRTCIceCandidate:Ji,shimRTCIceCandidateRelayProtocol:kr,shimSendThrowTypeError:Yi});function Pu(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=n.window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=ns,r=Su(e),s={browserDetails:r,commonShim:wu,extractVersion:fi,disableLog:ku,disableWarnings:Tu,sdp:_u};switch(r.browser){case"chrome":if(!Js||!br||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(r.version===null)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=Js,$i(e,r),Xi(e),Qo(e,r),Yo(e),br(e,r),$o(e,r),tc(e,r),Xo(e),Zo(e,r),ic(e,r),Ji(e),kr(e),Tr(e),Qi(e,r),Yi(e,r),Sr(e,r);break;case"firefox":if(!Qs||!yr||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Qs,$i(e,r),Xi(e),nc(e,r),yr(e,r),sc(e,r),rc(e),cc(e),ac(e),oc(e),dc(e),lc(e,r),uc(e,r),hc(e,r),pc(e,r),Ji(e),Tr(e),Qi(e,r),Yi(e,r);break;case"safari":if(!Ys||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=Ys,$i(e,r),Xi(e),yc(e),Tc(e),gc(e),mc(e),fc(e),kc(e),vc(e),Sc(e),Ji(e),kr(e),Qi(e,r),Yi(e,r),Sr(e,r);break;default:i("Unsupported browser!");break}return s}Pu({window:typeof window>"u"?void 0:window});var Cr,Ec;class Ee extends(Ec=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}Cr=Ee;Ee.resolve=n=>Reflect.get(Ec,"resolve",Cr).call(Cr,n);const Ru=/version\/(\d+(\.?_?\d+)+)/i;let Wn;function _e(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Wn===void 0||e){const i=Iu.find(r=>r.test.test(t));Wn=i==null?void 0:i.describe(t)}return Wn}const Iu=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Zi(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Hn(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Zi(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Hn(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Zi(Ru,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Hn(n)}}}];function Zi(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function Hn(n){return n.includes("mac os")?Zi(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Mu="2.22.0";const Du=Mu,Au=17,_c=0,Er=1,wc=2,Ou=wc;
37class pt extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof(i==null?void 0:i.cause)<"u"&&(this.cause=i==null?void 0:i.cause)}}class xe extends pt{}var Q;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})(Q||(Q={}));class x extends xe{constructor(e,t,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=r,this.reasonName=Q[t]}static notAllowed(e,t,i){return new x(e,Q.NotAllowed,t,i)}static timeout(e){return new x(e,Q.Timeout)}static leaveRequest(e,t){return new x(e,Q.LeaveRequest,void 0,t)}static internal(e,t){return new x(e,Q.InternalError,void 0,t)}static cancelled(e){return new x(e,Q.Cancelled)}static serverUnreachable(e,t){return new x(e,Q.ServerUnreachable,t)}static websocket(e,t,i){return new x(e,Q.WebSocket,t,i)}static serviceNotFound(e,t){return new x(e,Q.ServiceNotFound,void 0,t)}}class ss extends pt{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class dt extends pt{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Nu extends pt{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}}class Z extends pt{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}}class St extends pt{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}}class Lu extends pt{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}}class Xs extends pt{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Zs extends xe{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Mt[t]}}var ne;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",n[n.HeaderTooLarge=9]="HeaderTooLarge",n[n.PayloadTooLarge=10]="PayloadTooLarge"})(ne||(ne={}));class le extends xe{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ne[t]}}class Wt extends pt{constructor(e){super(18,e),this.name="SignalReconnectError"}}var an;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(an||(an={}));(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(an||(an={}));class Y{}Y.setTimeout=function(){return setTimeout(...arguments)};Y.setInterval=function(){return setInterval(...arguments)};Y.clearTimeout=function(){return clearTimeout(...arguments)};Y.clearInterval=function(){return clearInterval(...arguments)};var w;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived",n.DataTrackPublished="dataTrackPublished",n.DataTrackUnpublished="dataTrackUnpublished",n.LocalDataTrackPublished="localDataTrackPublished",n.LocalDataTrackUnpublished="localDataTrackUnpublished"})(w||(w={}));var M;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",
37n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(M||(M={}));var P;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved",n.PublishDataTrackResponse="publishDataTrackResponse",n.UnPublishDataTrackResponse="unPublishDataTrackResponse",n.DataTrackSubscriberHandles="dataTrackSubscriberHandles",n.DataTrackPacketReceived="dataTrackPacketReceived",n.Joined="joined",n.TokenRefreshed="tokenRefreshed",n.ServerRegionsReported="serverRegionsReported"})(P||(P={}));var R;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(R||(R={}));function xu(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class z{constructor(e,t,i,r,s){if(typeof e=="object")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(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new 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}}}const Uu=["vp8","h264"],Fu=["vp8","h264","vp9","av1","h265"];function Pc(n){return!!Uu.find(e=>e===n)}const Bu=Pc;var ea;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(ea||(ea={}));var _r;
37(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(_r||(_r={}));const Ri={h90:new z(160,90,9e4,20),h180:new z(320,180,16e4,20),h216:new z(384,216,18e4,20),h360:new z(640,360,45e4,20),h540:new z(960,540,8e5,25),h720:new z(1280,720,17e5,30),h1080:new z(1920,1080,3e6,30),h1440:new z(2560,1440,5e6,30),h2160:new z(3840,2160,8e6,30)},wr={h120:new z(160,120,7e4,20),h180:new z(240,180,125e3,20),h240:new z(320,240,14e4,20),h360:new z(480,360,33e4,20),h480:new z(640,480,5e5,20),h540:new z(720,540,6e5,25),h720:new z(960,720,13e5,30),h1080:new z(1440,1080,23e5,30),h1440:new z(1920,1440,38e5,30)},as={h360fps3:new z(640,360,2e5,3,"medium"),h360fps15:new z(640,360,4e5,15,"medium"),h720fps5:new z(1280,720,8e5,5,"medium"),h720fps15:new z(1280,720,15e5,15,"medium"),h720fps30:new z(1280,720,2e6,30,"medium"),h1080fps15:new z(1920,1080,25e5,15,"medium"),h1080fps30:new z(1920,1080,5e6,30,"medium"),original:new z(0,0,7e6,30,"medium")};function Rc(n,e,t){var i,r,s,a;const o=Mc(n??{}),d=o.optionsWithoutProcessor,c=o.audioProcessor,l=o.videoProcessor,u=e==null?void 0:e.processor,h=t==null?void 0:t.processor,p=d??{};return p.audio===!0&&(p.audio={}),p.video===!0&&(p.video={}),p.audio&&(Pr(p.audio,e),(i=(s=p.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(p.audio.processor=c??u)),p.video&&(Pr(p.video,t),(r=(a=p.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=l??h)),p}function Pr(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function os(n){var e,t,i,r;const s={};if(n.video)if(typeof n.video=="object"){const a={},o=a,d=n.video;Object.keys(d).forEach(c=>{switch(c){case"resolution":Pr(o,d.resolution);break;default:o[c]=d[c]}}),s.video=a,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=n.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return n.audio?typeof n.audio=="object"?(s.audio=n.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Ic(n){return m(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=cs();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,a=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield Te(t),r.getByteTimeDomainData(a);const d=a.some(c=>c!==128&&c!==0);return i.close(),!d}return!1})()})}function cs(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>m(this,void 0,void 0,function*(){var r;try{t.state==="suspended"&&(yield t.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}finally{(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var r;t.state==="closed"&&((r=window.document.body)===null||r===void 0||r.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function qu(n){return n==="audioinput"?E.Source.Microphone:n==="videoinput"?E.Source.Camera:E.Source.Unknown}function Rr(n){return n===E.Source.Microphone?"audioinput":n===E.Source.Camera?"videoinput":void 0}function Vu(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,qt()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function bi(n){return n.split("/")[1].toLowerCase()}function ju(n){const e=[];
37return n.forEach(t=>{t.track!==void 0&&e.push(new Xr({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function V(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?V(n.track):{})}}function Wu(){return typeof RTCRtpReceiver<"u"&&typeof RTCRtpReceiver.prototype.getSynchronizationSources=="function"}function Hu(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],r={};for(const s of i)n[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function Mc(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:xu(e)}}function Ku(n){switch(n){case de.CAMERA:return E.Source.Camera;case de.MICROPHONE:return E.Source.Microphone;case de.SCREEN_SHARE:return E.Source.ScreenShare;case de.SCREEN_SHARE_AUDIO:return E.Source.ScreenShareAudio;default:return E.Source.Unknown}}function ta(n,e){return n.width*n.height<e.width*e.height}function Gu(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const zu=5e3,ui=[];var Ae;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Ae||(Ae={}));class E extends Me.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){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=E.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=U,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),zu):this.handleAppVisibilityChanged()},this.loggerContextCb=i.loggerContextCb,this.log=ye((r=i.loggerName)!==null&&r!==void 0?r:oe.Track,()=>this.logContext),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=E.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),V(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===E.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===E.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(ui.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&ui.splice(ui.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Gt(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?R.AudioPlaybackStarted:R.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?R.AudioPlaybackFailed:R.VideoPlaybackFailed,s):s.name==="AbortError"?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:s}),r&&e&&i.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(R.ElementAttached,e),e}detach(e){try{if(e){Yt(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(R.ElementDetached,e)),e}const t=[];
37return this.attachedElements.forEach(i=>{Yt(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(R.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&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!==void 0&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0)}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=ye(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ui.forEach(i=>{i.parentElement||(t=!1)}),t&&ui.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===E.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ie()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ie()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Gt(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(r=>{t.removeTrack(r)}),t.addTrack(n)),(!qt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(qt()||Bt())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Yt(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function r(c){switch(c){case e.Audio:return qe.AUDIO;case e.Video:return qe.VIDEO;default:return qe.DATA}}n.kindToProto=r;function s(c){switch(c){case qe.AUDIO:return e.Audio;case qe.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=s;function a(c){switch(c){case t.Camera:return de.CAMERA;case t.Microphone:return de.MICROPHONE;case t.ScreenShare:return de.SCREEN_SHARE;case t.ScreenShareAudio:return de.SCREEN_SHARE_AUDIO;default:return de.UNKNOWN}}n.sourceToProto=a;function o(c){switch(c){case de.CAMERA:return t.Camera;case de.MICROPHONE:return t.Microphone;case de.SCREEN_SHARE:return t.ScreenShare;case de.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function d(c){switch(c){case pr.ACTIVE:return i.Active;case pr.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=d})(E||(E={}));const Ju="|",$t="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Dc(n){const e=n.split(Ju);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Te(n){return new Ee(e=>Y.setTimeout(e,n))}function Ir(){return"addTransceiver"in RTCPeerConnection.prototype}function Mr(){return"addTrack"in RTCPeerConnection.prototype}function Qu(){if(!("getCapabilities"in RTCRtpSender)||qt()||Bt())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function Yu(){if(!("getCapabilities"in RTCRtpSender)||Bt())return!1;if(qt()){const t=_e();if(t!=null&&t.version&&tt(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&tt(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Xe(n){return n==="av1"||n==="vp9"}function $u(n){var e;const t=(e=n.getHeaderExtensionsToNegotiate)===null||e===void 0?void 0:e.call(n);if(!t||!n.setHeaderExtensionsToNegotiate)return!1;const i=t.find(r=>r.uri===$t);if(!i)return!1;if(i.direction!=="stopped")return!0;
37i.direction="sendrecv";try{return n.setHeaderExtensionsToNegotiate(t),!0}catch{return!1}}function Dr(n){return!document||Ii()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function Xu(){return typeof RTCPeerConnection>"u"?!1:Ir()||Mr()}function Bt(){var n;return((n=_e())===null||n===void 0?void 0:n.name)==="Firefox"}function Zu(){const n=_e();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function Ar(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"&&!Zu()}function qt(){var n;return((n=_e())===null||n===void 0?void 0:n.name)==="Safari"}function Ii(){const n=_e();return(n==null?void 0:n.name)==="Safari"||(n==null?void 0:n.os)==="iOS"}function eh(){const n=_e();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&tt(n.osVersion,"17")>=0}function th(n){return n||(n=_e()),(n==null?void 0:n.name)==="Safari"&&tt(n.version,"18.3")>0||(n==null?void 0:n.os)==="iOS"&&!!(n!=null&&n.osVersion)&&tt(n.osVersion,"18.3")>0}function Ac(){var n,e;return Ie()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function ih(){const n=_e(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&tt(n.osVersion,e)>=0?!0:n.name==="Safari"&&tt(n.version,e)>=0}function Ie(){return typeof document<"u"}function ze(){return navigator.product=="ReactNative"}function si(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Kn(n){return si(n)?n.hostname.split(".")[0]:null}function Oc(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Nc(){if(!ze())return;let n=Oc();if(n)return n.platform}function ia(){if(Ie())return window.devicePixelRatio;if(ze()){let n=Oc();if(n)return n.devicePixelRatio}return 1}function tt(n,e){const t=n.split("."),i=e.split("."),r=Math.min(t.length,i.length);for(let s=0;s<r;++s){const a=parseInt(t[s],10),o=parseInt(i[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function nh(n){for(const e of n)e.target.handleResize(e)}function rh(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Gn=null;const na=()=>(Gn||(Gn=new ResizeObserver(nh)),Gn);let zn=null;const ra=()=>(zn||(zn=new IntersectionObserver(rh,{root:null,rootMargin:"0px"})),zn);function sh(n){var e;const t=new Po({capabilities:n,sdk:Ro.JS,protocol:Au,clientProtocol:Ou,version:Du});return ze()&&(t.os=(e=Nc())!==null&&e!==void 0?e:""),t}function sa(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=n,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(n/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream().getTracks(),d=N(o,1),c=d[0];if(!c)throw Error("Could not get empty media stream video track");return c.enabled=t,c}let hi;function Jn(){if(!hi){const t=new AudioContext,i=t.createOscillator(),r=t.createGain();r.gain.setValueAtTime(0,0);const s=t.createMediaStreamDestination();i.connect(r),r.connect(s),i.start();var n=s.stream.getAudioTracks(),e=N(n,1);if(hi=e[0],!hi)throw Error("Could not get empty media stream audio track");hi.enabled=!1}return hi.clone()}class be{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,r)=>m(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function ah(n,e){const t=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},e),i=cs();if(!i)throw new Error("Audio Context not supported on this browser");const r=t.cloneTrack?n.mediaStreamTrack.clone():n.mediaStreamTrack,s=i.createMediaStreamSource(new MediaStream([r])),a=i.createAnalyser();a.minDecibels=t.minDecibels,a.maxDecibels=t.maxDecibels,a.fftSize=t.fftSize,a.smoothingTimeConstant=t.smoothingTimeConstant,s.connect(a);const o=new Uint8Array(a.frequencyBinCount);return{calculateVolume:()=>{a.getByteFrequencyData(o);let l=0;for(const h of o)l+=Math.pow(h/255,2);return Math.sqrt(l/o.length)},analyser:a,cleanup:()=>m(this,void 0,void 0,function*(){yield i.close(),t.cloneTrack&&r.stop()})}}function Lc(n){return Fu.includes(n)}function Xt(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function oh(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Mi(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function ch(n,e){return n.segments.map(t=>{let i=t.id,r=t.text,s=t.language,a=t.startTime,o=t.endTime,d=t.final;var c;const l=(c=e.get(i))!==null&&c!==void 0?c:Date.now(),u=Date.now();return d?e.delete(i):e.set(i,l),{id:i,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:d,language:s,firstReceivedTime:l,lastReceivedTime:u}})}function dh(n){const e=n.id,t=n.timestamp,i=n.message,r=n.editTimestamp;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function aa(n){switch(n.reason){case Q.LeaveRequest:return n.context;case Q.Cancelled:return He.CLIENT_INITIATED;case Q.NotAllowed:return He.USER_REJECTED;case Q.ServerUnreachable:return He.JOIN_FAILURE;default:return He.UNKNOWN_REASON}}function Dt(n){return n!==void 0?Number(n):void 0}function Ge(n){return n!==void 0?BigInt(n):void 0}function Zt(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function et(n){return!!n&&n.kind==E.Kind.Audio}function ht(n){return!!n&&n.kind==E.Kind.Video}function Qe(n){return Zt(n)&&ht(n)}function rt(n){return Zt(n)&&et(n)}function Or(n){return!!n&&!n.isLocal}function lh(n){return!!n&&!n.isLocal}function Qn(n){return Or(n)&&ht(n)}function uh(n){return n.isLocal}function hh(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&t.push(i),t}function en(n){return new ReadableStream({start(e){e.enqueue(n),e.close()}})}function ph(n,e){return Ko(this,arguments,function*(){const i=n.getReader();let r=new Uint8Array(0);try{for(;;){const s=yield ut(i.read()),a=s.done,o=s.value;if(a)break;if(o.byteLength===0)continue;const d=new Uint8Array(r.byteLength+o.byteLength);for(d.set(r),d.set(o,r.byteLength),r=d;r.byteLength>=e;)yield yield ut(r.slice(0,e)),r=r.slice(e)}r.byteLength>0&&(yield yield ut(r))}finally{i.releaseLock()}})}function mh(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function Ct(){return typeof CompressionStream<"u"}function fh(){return Ct()&&!Bt()}function oa(n,e){const t=Dc(e.id),i=N(t,2),r=i[1];if(r!=null&&r.startsWith("TR"))return r;if(n.id.startsWith("TR"))return n.id}function gh(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=vh(n,e);return t?i:ds(i,"v1")}function vh(n,e){const t=new URL(oh(n));return e.forEach((i,r)=>{t.searchParams.set(r,i)}),ds(t,"rtc")}function bh(n){const e=new URL(Mi(n));return ds(e,"validate")}function xc(n){return n.endsWith("/")?n:"".concat(n,"/")}function ds(n,e){return n.pathname="".concat(xc(n.pathname)).concat(e),n}function ca(n){if(typeof n=="string")return Vs.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return Vs.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function yh(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const kh=10,pi="lk_e2ee",Th="LKFrameEncryptionKey",Sh={sharedKey:!1,ratchetSalt:Th,ratchetWindowSize:8,failureTolerance:kh,keyringSize:16,keySize:128};var Et;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Et||(Et={}));var da;(function(n){n.KeyRatcheted="keyRatcheted"})(da||(da={}));var vt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(vt||(vt={}));var la;(function(n){n.Error="cryptorError"})(la||(la={}));function Ch(){return ls()||Eh()}function Eh(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"}function ls(){return typeof window<"u"&&typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function _h(n){var e,t,i,r,s;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="transcription"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="encryptedPacket")return new ko({value:n.value})}class Wm extends Me.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,i,r)=>{U.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Sh),e),this.on(Et.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const r={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),r),i!==void 0&&(this.latestManuallySetKeyIndex=i),this.emit
37(Et.SetKey,r,i!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(Et.RatchetRequest,e,t)}}var ua;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(ua||(ua={}));function Di(){return Ar()}function Ai(n){return!!(n!=null&&n.worker)&&(ls()||Di())}function on(n){return!!(n!=null&&n.timestamp||n!=null&&n.frameId)}function wh(n){const e=[];return n!=null&&n.timestamp&&e.push(ri.PTF_USER_TIMESTAMP),n!=null&&n.frameId&&e.push(ri.PTF_FRAME_ID),e}function Ph(n){if(!n||n.length===0)return;const e={};return n.includes(ri.PTF_USER_TIMESTAMP)&&(e.timestamp=!0),n.includes(ri.PTF_FRAME_ID)&&(e.frameId=!0),e.timestamp||e.frameId?e:void 0}function us(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i,r;let s;const a=(i=t.isImmediate)!==null&&i!==void 0?i:!1,o=(r=t.callback)!==null&&r!==void 0?r:!1,d=t.maxWait;let c=Date.now(),l=[];function u(){if(d!==void 0){const p=Date.now()-c;if(p+e>=d)return d-p}return e}const h=function(){for(var p=arguments.length,f=new Array(p),g=0;g<p;g++)f[g]=arguments[g];const k=this;return new Promise((T,S)=>{const L=function(){if(s=void 0,c=Date.now(),!a){const y=n.apply(k,f);o&&o(y),l.forEach(C=>{let I=C.resolve;return I(y)}),l=[]}},b=a&&s===void 0;if(s!==void 0&&Y.clearTimeout(s),s=Y.setTimeout(L,u()),b){const y=n.apply(k,f);return o&&o(y),T(y)}l.push({resolve:T,reject:S})})};return h.cancel=function(p){s!==void 0&&Y.clearTimeout(s),l.forEach(f=>{let g=f.reject;return g(p)}),l=[]},h}const hs=2e3;function _n(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}class Uc extends E{constructor(e,t,i,r,s){super(e,i,s),this.timeSyncLoop=()=>{var a;if(this.listenerCount(R.TimeSyncUpdate)===0){this.timeSyncHandle=void 0;return}this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);const o=(a=this.receiver)===null||a===void 0?void 0:a.getSynchronizationSources()[0];if(o){const d=o.timestamp,c=o.rtpTimestamp;c&&this.rtpTimestamp!==c&&(this.emit(R.TimeSyncUpdate,{timestamp:d,rtpTimestamp:c}),this.rtpTimestamp=c)}},this.onTimeSyncListenerAdded=a=>{a===R.TimeSyncUpdate&&this.timeSyncHandle===void 0&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?R.Muted:R.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(R.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),hs)),Wu()&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off("newListener",this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){const e=this;e.off("newListener",this.onTimeSyncListenerAdded),e.on("newListener",this.onTimeSyncListenerAdded),this.timeSyncHandle===void 0&&this.timeSyncLoop()}}const Yn=100;class ps extends Uc{constructor(e,t,i,r,s){super(e,t,E.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=_n(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=us(()=>{this.updateDimensions()},Yn),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;var i;return(i=this.frameMetadataExtractor)===null||i===void 0?void 0:i.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===E.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}
vendor: 4,745 bytes, line 37
37setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Yt(this._mediaStreamTrack,t):Gt(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Rh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);const t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,t={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&i!==""&&r.get(i)&&(t.mimeType=r.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const r=this.elementInfos.reduce((d,c)=>Math.max(d,c.visibilityChangedAt||0),0),s=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(d=>d.pictureInPicture),o=this.elementInfos.some(d=>d.visible)&&!s||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-r<Yn){Y.setTimeout(()=>{this.updateVisibility()},Yn);return}this.lastVisible=o,this.emit(R.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,d=a.height()*s;o+d>i+r&&(i=o,r=d)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:i,height:r},this.emit(R.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?ia():t||(ia()>2?2:1)}}class Rh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var r;const s=i.target,a=i.isIntersecting;s===this.element&&(this.isIntersecting=a,this.isPiP=mi(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var s;this.isPiP=mi(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)})})},this.onLeavePiP=()=>{var i;this.isPiP=mi(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Nr(e),this.isPiP=Ie()&&mi(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Nr(this.element),this.isPiP=mi(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ra().observe(this.element),na().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterP
37iP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,r,s;(e=ra())===null||e===void 0||e.unobserve(this.element),(t=na())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function mi(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Nr(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Nr(n,e){const t=e||window;let i=n.offsetTop,r=n.offsetLeft;const s=n.offsetWidth,a=n.offsetHeight,o=n,d=o.hidden,c=getComputedStyle(n),l=c.display;for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,r+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&r+s>t.pageXOffset&&!d&&l!=="none"}class Ih extends Me.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var r,s;const a=i.data,o=a.kind,d=a.data;switch(o){case"error":if(U.error(d.error.message),d.uuid){const u=this.decryptDataRequests.get(d.uuid);if(u!=null&&u.reject){u.reject(d.error);break}const h=this.encryptDataRequests.get(d.uuid);if(h!=null&&h.reject){h.reject(d.error);break}}this.emit(vt.EncryptionError,d.error,d.participantIdentity);break;case"initAck":d.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u,!1)});break;case"enable":if(d.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u,!1)}),this.encryptionEnabled!==d.enabled&&d.participantIdentity===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(vt.ParticipantEncryptionStatusChanged,d.enabled,this.room.localParticipant),this.encryptionEnabled=d.enabled;else if(d.participantIdentity){const u=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(d.participantIdentity);if(!u)throw TypeError("couldn't set encryption status, participant not found".concat(d.participantIdentity));this.emit(vt.ParticipantEncryptionStatusChanged,d.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(Et.KeyRatcheted,d.ratchetResult,d.participantIdentity,d.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(d.uuid);c!=null&&c.resolve&&c.resolve(d);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(d.uuid);l!=null&&l.resolve&&l.resolve(d);break;case"packetTrailerMetadata":this.handleFrameMetadata(d.trackId,d.rtpTimestamp,d.ssrc,d.metadata);break}},this.onWorkerError=i=>{U.error("e2ee worker encountered an error:",{error:i.error}),this.emit(vt.EncryptionError,i.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}
37setup(e){if(!Ch())throw new ss("tried to setup end-to-end encryption on an unsupported browser");if(U.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:mu.getLevel()}};this.worker&&(U.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){U.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?U.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,i,r){if(this.room){for(const s of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const a of s.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof ps&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,i,r);return}}}setupEngine(e){e.on(P.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(w.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==H.NONE,r.identity)),e.on(w.ConnectionStateChanged,i=>
37{i===K.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==H.NONE,r.identity)})})}).on(w.TrackUnsubscribed,(i,r,s)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(w.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(w.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const i=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(r=>{var s;this.postKey(r,i===((s=r.keyIndex)!==null&&s!==void 0?s:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(M.LocalSenderCreated,(i,r)=>m(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),e.localParticipant.on(M.LocalTrackPublished,i=>{if(!ht(i.track)||!Ii())return;const r={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:bi(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(r)}),t.on(Et.SetKey,(i,r)=>this.postKey(i,r??!0)).on(Et.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}encryptData(e){return m(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new be;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(i),r.promise})}handleEncryptedData(e,t,i,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:i,keyIndex:r}},o=new be;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e,t){let i=e.key,r=e.participantIdentity,s=e.keyIndex;var a;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((a=this.room)===null||a===void 0?void 0:a.localParticipant.identity),key:i,keyIndex:s,updateCurrentKeyIndex:t}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(!e.receiver)return;if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const r=e.kind==="video"&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?bi(i.mimeType):void 0,r)}setupE2EESender(e,t){var i,r,s;if(!Zt(e)||!t){t||U.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,ht(e)?(r=(i=e.publishOptions)===null||i===void 0?void 0:i.frameMetadata)!==null&&r!==void 0?r:(s=e.publishOptions)===null||s===void 0?void 0:s.packetTrailer:void 0)}handleReceiver(e,t,i,r,s){return m(this,void 0,void 0,function*(){if(this.worker){if(Ar()){const a={kind:"decode",participantIdentity:i,trackId:t,codec:r,hasPacketTrailer:s};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(pi in e&&r){const c={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:i,hasPacketTrailer:s}};this.worker.postMessage(c);return}let a=e.writableStream,o=e.readableStream;if(!a||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,a=c.writable,e.readableStream=c.readable,o=c.readable}const d={kind:"decode",data:{readableStream:o,writableStream:a,trackId:t,codec:r,participantIdentity:i,isReuse:pi in e,hasPacketTrailer:s}};this.worker.postMessage(d,[o,a])}e[pi]=!0}})}handleSender(e,t,i,r){var s;if(!(pi in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Ar()){U.info("initialize script transform");const a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:on(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{U.info("initialize encoded streams");const a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:on(r),packetTrailer:r}};this.worker.postMessage(o,[a.readable,a.writable])}e[pi]=!0}}}const Mh=300;class Dh{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,i){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=Mh;){const r=this.metadataMap.keys().next().value;this.metadataMap.delete(r)}this.metadataMap.set(e,i)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class Ah{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{const i=t.data;if(i.kind==="metadata"){const r=this.extractors.get(i.data.trackId);r&&r.storeMetadata(i.data.rtpTimestamp,i.data.ssrc,i.data.metadata)}},this.onWorkerError=t=>{U.error("frame metadata worker encountered an error:",{error:t.error})},this.worker=e==null?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(w.TrackSubscribed,(t,i,r)=>
37{t.kind==="video"&&this.setupReceiver(t,i.trackInfo)}).on(w.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(w.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var i,r,s;const a=e.receiver;if(!a)return;if(!(!!(t!=null&&t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0)){!((i=this.room)===null||i===void 0)&&i.hasE2EESetup||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!Ai(this.worker?{worker:this.worker}:void 0)&&!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)){U.warn("frame metadata transform not supported; skipping extraction");return}const d=new Dh,c=e.mediaStreamID;this.extractors.set(c,d),e.frameMetadataExtractor=d,!(!((s=this.room)===null||s===void 0)&&s.hasE2EESetup)&&this.setupWorkerReceiver(a,c,!0)}setupPassthroughReceiver(e,t){if(Di()){"transform"in e&&(e.transform=null);return}if(this.worker&&Ai({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;const r=this.worker;if(!r)return;if(Di()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}const s=this.workerPipelines.get(e);if(s){const d={kind:"updateTrackId",data:{oldTrackId:s,newTrackId:t,hasPacketTrailer:i}};r.postMessage(d),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){U.warn("createEncodedStreams not supported");return}let a;try{a=e.createEncodedStreams()}catch(d){U.warn("failed to create encoded streams",{error:d});return}const o={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:i}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,i=this.extractors.get(t);i&&(i.dispose(),this.extractors.delete(t)),e instanceof ps&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(const t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)===null||e===void 0||e.terminate()}}const Oh=500,Nh=15e3;class ei{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new ei),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),r=Kn(i);if(!r)return;let s=(t=this.failedConnectionAttempts.get(r))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(r,s+1),this.backOffPromises.set(r,Te(Math.min(Oh*Math.pow(2,s),Nh)))}getBackOffPromise(e){const t=new URL(e),i=t&&Kn(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Kn(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}ei._instance=null;const $n="default";class me{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new me),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=me.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){U.debug("awaiting getUserMedia promise");try{t?yield me.userMediaPromiseMap.get(t):yield Promise.all(me.userMediaPromiseMap.values())}catch{U.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(qt()&&i.hasDeviceInUse(t))&&(a.filter(d=>d.kind===t).length===0||a.some(d=>{const c=d.label==="",l=t?d.kind===t:!0;return c&&l}))){const d={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(d);a=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,i){return m(this,void 0,void 0,function*(){if(t!==$n)return t;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===$n);if(!s){U.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==$n&&o.groupId===(i??s.groupId));if(!a){U.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?me.userMediaPromiseMap.has(e):me.userMediaPromiseMap.size>0}}me.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];me.userMediaPromiseMap=new Map;const ms=65535,Fc=4294967295;
37class Ke{static u16(e){return new Ke(e,ms)}static u32(e){return new Ke(e,Fc)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new 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 Ke(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){const e=this.value;return this.increment(),new Ke(e,this.maxSize)}isBefore(e){const t=this.value>>>0,r=(e.value>>>0)-t>>>0;return r!==0&&r<this.maxSize+1}}class ti{static fromRtpTicks(e){return new ti(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*Fc);return ti.fromRtpTicks(e)}constructor(e,t){this.timestamp=Ke.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new ti(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class At{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new At(t,new Date,e)}static startingAtTime(e,t,i){return new At(i,e,t)}static rtpStartingNow(e){return At.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return At.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=At.durationInMsToTicks(t,this.rateInHz),r=this.base.clone();return r.wrappingAdd(i),r.isBefore(this.previous)&&(r=this.previous),this.previous=r.clone(),r.clone()}static durationInMsToTicks(e,t){let r=(e*1e6*t+5e8)/1e9;return Math.round(r)}}function fs(n){if(n instanceof DataView)return n;if(n instanceof ArrayBuffer)return new DataView(n);if(n instanceof Uint8Array)return new DataView(n.buffer,n.byteOffset,n.byteLength);throw new Error("Error coercing ".concat(n," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var Ut;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(Ut||(Ut={}));class ai extends xe{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=Ut[t]}isReason(e){return this.reason===e}static tooLarge(){return new ai("Value too large to be a valid track handle",Ut.TooLarge)}static reserved(e){return new ai("0x".concat(e.toString(16)," is a reserved value."),Ut.Reserved)}}const Lh={fromNumber(n){if(n===0)throw ai.reserved(n);if(n>ms)throw ai.tooLarge();return n}};class xh{constructor(){this.value=0}get(){return this.value+=1,this.value>ms?null:this.value}reset(){this.value=0}}const cn={from(n){return{sid:n.sid,pubHandle:n.pubHandle,name:n.name,usesE2ee:n.encryption!==H.NONE}},toProtobuf(n){return new vn({sid:n.sid,pubHandle:n.pubHandle,name:n.name,encryption:n.usesE2ee?H.GCM:H.NONE})}};var yi;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(yi||(yi={}));class Uh{constructor(){this.pendingTasks=new Map,this.taskMutex=new fe,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:yi.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=yi.RUNNING,yield e()}finally{t.status=yi.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return m(this,void 0,void 0,function*(){return this.run(()=>m(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class Fh{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const s=new WebSocket(e,(r=t.protocols)!==null&&r!==void 0?r:[]);s.binaryType="arraybuffer",this.ws=s;const a=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},d=o.closeCode,c=o.reason;return s.close(d,c)};this.opened=new Ee((o,d)=>{const c=()=>{d(x.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{o({readable:new ReadableStream({start(l){s.onmessage=u=>{let h=u.data;return l.enqueue(h)},s.onerror=u=>l.error(u)},cancel:a}),writable:new WritableStream({write(l){s.send(l)},abort(){s.close()},close:a}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",c)},s.addEventListener("error",c)}),this.closed=new Ee((o,d)=>{const c=()=>m(this,void 0,void 0,function*(){const l=new Ee(h=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",p=>{h(p)},{once:!0})}),u=yield Ee.race([Te(250),l]);u?o(u):d(x.websocket("Encountered unspecified websocket error without a timely close event"))});
37s.onclose=l=>{let u=l.code,h=l.reason;o({closeCode:u,reason:h}),s.removeEventListener("error",c)},s.addEventListener("error",c)}),t.signal&&(t.signal.onabort=()=>s.close()),this.close=a}}const Bh=["syncState","trickle","offer","answer","simulate","leave"];function qh(n){const e=Bh.indexOf(n.case)>=0;return U.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var J;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(J||(J={}));const Vh=250,jh=5e3;class gs{get currentState(){return this.state}get isDisconnected(){return this.state===J.DISCONNECTING||this.state===J.DISCONNECTED}get isEstablishingConnection(){return this.state===J.CONNECTING||this.state===J.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=J.DISCONNECTED,this.log=U,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=t.loggerContextCb,this.log=ye((i=t.loggerName)!==null&&i!==void 0?i:oe.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new Uh,this.queuedRequests=[],this.closingLock=new fe,this.connectionLock=new fe,this.state=J.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,r){return m(this,arguments,void 0,function(s,a,o,d){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,u=arguments.length>5?arguments[5]:void 0;return(function*(){return c.state=J.CONNECTING,c.options=o,yield c.connect(s,a,o,d,l,u)})()})}reconnect(e,t,i,r){return m(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring");return}return this.state=J.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,i,r){return m(this,arguments,void 0,function(s,a,o,d){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,u=arguments.length>5?arguments[5]:void 0;return(function*(){const h=yield c.connectionLock.lock();c.connectOptions=o,c.useV0SignalPath=l;const p=sh(o.clientInfoCapabilities),f=l?Wh(a,p,o):yield Hh(a,p,o,u),g=gh(s,f,l).toString(),k=bh(g).toString();return new Promise((T,S)=>m(c,void 0,void 0,function*(){var L,b;try{let y=!1;const C=O=>m(this,void 0,void 0,function*(){if(y)return;y=!0;const F=O instanceof Event?O.currentTarget:O,X=yh(F,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(X)).catch(ie=>{this.log.error(ie),this.close()}):this.close(),I(),S(x.cancelled(X))});d==null||d.addEventListener("abort",C);const I=()=>{clearTimeout(A),d==null||d.removeEventListener("abort",C)},A=setTimeout(()=>{C(x.timeout("room connection has timed out (signal)"))},o.websocketTimeout),B=(O,F)=>{this.handleSignalConnected(O,A,F)},D=new URL(g);if(D.searchParams.has("access_token")&&D.searchParams.set("access_token","<redacted>"),this.ws){const O=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-O,"ms"))}this.log.info("signal connecting to ".concat(D),{reconnect:o.reconnect,reconnectReason:o.reconnectReason}),this.ws=new Fh(g);try{this.ws.closed.then(he=>{this.isEstablishingConnection&&S(x.internal("Websocket got closed during a (re)connection attempt: ".concat(he.reason))),he.closeCode!==1e3&&(this.log.warn("websocket closed",{reason:he.reason,code:he.closeCode,wasClean:he.closeCode===1e3,state:this.state}),this.state===J.CONNECTED&&this.handleOnClose(he.reason||"Unexpected WS error"))}).catch(he=>{this.isEstablishingConnection&&S(x.internal("Websocket error during a (re)connection attempt: ".concat(he)))});
37const O=yield this.ws.opened.catch(he=>m(this,void 0,void 0,function*(){if(this.state!==J.CONNECTED){this.state=J.DISCONNECTED,clearTimeout(A);const Rt=yield this.handleConnectionError(he,k);S(Rt);return}this.handleWSError(he),S(he)}));if(clearTimeout(A),!O)return;const F=O.readable.getReader();this.streamWriter=O.writable.getWriter();let X,ie;try{X=yield Promise.race([F.read(),new Promise((he,Rt)=>{ie=setTimeout(()=>{Rt(x.timeout("signal connection timed out while waiting for the first message"))},jh)})])}catch(he){F.releaseLock(),S(he),this.close();return}finally{clearTimeout(ie)}if(F.releaseLock(),!X.value)throw x.internal("no message received as first message");const ge=ca(X.value),Je=this.validateFirstMessage(ge,(L=o.reconnect)!==null&&L!==void 0?L:!1);if(!Je.isValid){S(Je.error);return}((b=ge.message)===null||b===void 0?void 0:b.case)==="join"&&(this.pingTimeoutDuration=ge.message.value.pingTimeout,this.pingIntervalDuration=ge.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(ge.message.value));const mt=Je.shouldProcessFirstMessage?ge:void 0;B(O,mt),T(Je.response)}catch(O){S(O)}finally{I()}}finally{h()}}))})()})}startReadingLoop(e,t){return m(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Te(this.signalLatency));const i=yield e.read(),r=i.done,s=i.value;if(r)break;const a=ca(s);
37this.handleSignalResponse(a)}})}close(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([J.DISCONNECTING||J.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=J.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const s=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([s,Te(Vh)])}}catch(s){e.log.debug("websocket error while closing",{error:s})}finally{t&&(e.state=J.DISCONNECTED),r()}})()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Ot(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Ot(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new kn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Tn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return m(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new es({requestId:o,metadata:i,name:r,attributes:a})}),o})()})}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 Uo({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new qo({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:te.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Wo({timestamp:te.parse(Date.now()),rtt:te.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Zr({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Cn({reason:He.CLIENT_INITIATED,action:Jt.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new Qr({pubHandle:e,name:t,encryption:i?H.GCM:H.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new $r({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Oo({updates:[new No({trackSid:e,subscribe:t})]})})}sendRequest(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!r&&!qh(t)&&i.state===J.RECONNECTING){i.queuedRequests.push(()=>m(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield Te(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case));return}const a=new Al({message:t});try{i.useJSON?yield i.streamWriter.write(a.toJsonString()):yield i.streamWriter.write(a.toBinary().buffer)}catch(o){i.log.error("error sending signal message",{error:o})}})()})}handleSignalResponse(e){var t,i;const r=e.message;if(r==null){this.log.debug("received unsupported message");return}let s=!1;if(r.case==="answer"){const a=ha(r.value);this.onAnswer&&this.onAnswer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){const a=ha(r.value);this.onOffer&&this.onOffer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){const a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):r.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement
37(r.value):r.case==="publishDataTrackResponse"?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(r.value):r.case==="unpublishDataTrackResponse"?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(r.value):r.case==="dataTrackSubscriberHandles"?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(r.value):this.log.debug("unsupported message",{msgCase:r.case}));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return m(this,void 0,void 0,function*(){if(this.state===J.DISCONNECTED)return;const 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(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=Y.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Y.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set");return}this.log.debug("start ping interval"),this.pingInterval=Y.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&Y.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=J.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,r,s,a,o;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===J.RECONNECTING&&((r=e.message)===null||r===void 0?void 0:r.case)!=="leave"?((s=e.message)===null||s===void 0?void 0:s.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:x.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:x.internal("Unexpected first message")}:{isValid:!1,error:x.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return m(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:const r=yield i.text();return r.includes("requested room does not exist")?x.notAllowed(r,i.status):x.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return x.notAllowed(s,i.status);default:break}return e instanceof x?e:x.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof x?i:x.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function ha(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function Ot(n,e){return new wt({sdp:n.sdp,type:n.type,id:e})}function Wh(n,e,t){var i;const r=new URLSearchParams;return r.set("access_token",n),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",ze()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),r.set("client_protocol",e.clientProtocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),t.adaptiveStream&&r.set("adaptive_stream","1"),t.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}function Hh(n,e,t,i){return m(this,void 0,void 0,function*(){const r=new
37URLSearchParams;r.set("access_token",n);const s=new ou({clientInfo:e,connectionSettings:new Ho({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0,publisherOffer:i});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const a=s.toBinary();let o,d;if(Ct()){const h=new CompressionStream("gzip"),p=h.writable.getWriter();p.write(new Uint8Array(a)),p.close();const f=[],g=h.readable.getReader();for(;;){const L=yield g.read(),b=L.done,y=L.value;if(b)break;f.push(y)}const k=f.reduce((L,b)=>L+b.length,0),T=new Uint8Array(k);let S=0;for(const L of f)T.set(L,S),S+=L.length;o=T,d=fr.GZIP}else o=a,d=fr.NONE;const l=new cu({joinRequest:o,compression:d}).toBinary(),u=h=>{const p=Array.from(h,f=>String.fromCodePoint(f)).join("");return btoa(p)};return r.set("join_request",u(l).replace(/\+/g,"-").replace(/\//g,"_")),r})}class Kh{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const i of this._map.entries()){var t=N(i,2);const r=t[0];t[1].expiresAt<e&&this._map.delete(r)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const i of this._map.entries()){var t=N(i,2);const r=t[0],s=t[1];s.expiresAt>=Date.now()&&e(s.value,r,this.asValueMap())}}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const s of i.entries()){var r=N(s,2);const a=r[0],o=r[1];t.push(e(o,a,i))}return t}asValueMap(){const e=new Map;for(const i of this._map.entries()){var t=N(i,2);const r=t[0],s=t[1];s.expiresAt>=Date.now()&&e.set(r,s.value)}return e}}var Ue={},Xn={},Zn={exports:{}},pa;function vs(){if(pa)return Zn.exports;pa=1;var n=Zn.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 e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(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 e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{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 e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","max
37MessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%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+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{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(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Zn.exports}var ma;function Gh(){return ma||(ma=1,(function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,d,c,l){if(l&&!c)d[l]=e(o[1]);else for(var u=0;u<c.length;u+=1)o[u+1]!=null&&(d[c[u]]=e(o[u+1]))},i=function(o,d,c){var l=o.name&&o.names;o.push&&!d[o.push]?d[o.push]=[]:l&&!d[o.name]&&(d[o.name]={});var u=o.push?{}:l?d[o.name]:d;t(c.match(o.reg),u,o.names,o.name),o.push&&d[o.push].push(u)},r=vs(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var d={},c=[],l=d;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var h=u[0],p=u.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var f=0;f<(r[h]||[]).length;f+=1){var g=r[h][f];if(g.reg.test(p))return i(g,l,p)}}),d.media=c,d};var a=function(o,d){var c=d.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&d.length>1&&(o[c[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var d=[],c=o.split(" ").map(e),l=0;l<c.length;l+=3)d.push({component:c[l],ip:c[l+1],port:c[l+2]});return d},n.parseImageAttributes=function(o){return o.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(d){return d.split(",").map(function(c){var l,u=!1;return c[0]!=="~"?l=e(c):(l=e(c.substring(1,c.length)),u=!0),{scid:l,paused:u}})})}})(Xn)),Xn}var er,fa;function zh(){if(fa)return er;fa=1;var n=vs(),e=/%[sdv%]/g,t=function(a){var o=1,d=arguments,c=d.length;return a.replace(e,function(l){if(o>=c)return l;var u=d[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})}
37,i=function(a,o,d){var c=o.format instanceof Function?o.format(o.push?d:d[o.name]):o.format,l=[a+"="+c];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(d[o.name][h]):l.push(d[o.names[u]])}else l.push(d[o.name]);return t.apply(null,l)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return er=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var d=o.outerOrder||r,c=o.innerOrder||s,l=[];return d.forEach(function(u){n[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(i(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(p){l.push(i(u,h,p))})})}),a.media.forEach(function(u){l.push(i("m",n.m[0],u)),c.forEach(function(h){n[h].forEach(function(p){p.name in u&&u[p.name]!=null?l.push(i(h,p,u)):p.push in u&&u[p.push]!=null&&u[p.push].forEach(function(f){l.push(i(h,p,f))})})})}),l.join(`\r 38`)+`\r 39`},er}var ga;function Jh(){if(ga)return Ue;ga=1;var n=Gh(),e=zh(),t=vs();return Ue.grammar=t,Ue.write=e,Ue.parse=n.parse,Ue.parseParams=n.parseParams,Ue.parseFmtpConfig=n.parseFmtpConfig,Ue.parsePayloads=n.parsePayloads,Ue.parseRemoteCandidates=n.parseRemoteCandidates,Ue.parseImageAttributes=n.parseImageAttributes,Ue.parseSimulcastStreamList=n.parseSimulcastStreamList,Ue}var Ne=Jh();const Qh=.9,Yh=1e3,$h=20;function Xh(n,e,t,i){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;var s,a,o;if(!(!((s=n.msid)===null||s===void 0)&&s.includes(e)))return;const d=(o=(a=n.rtp.find(h=>h.codec.toUpperCase()===t.toUpperCase()))===null||a===void 0?void 0:a.payload)!==null&&o!==void 0?o:0;if(d===0)return 0;const c=Math.round(i*Qh),l=r?c:Math.min(c,Yh),u=n.fmtp.find(h=>h.payload===d);return u?u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l)):n.fmtp.push({payload:d,config:"x-google-start-bitrate=".concat(l)}),d}const bt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class va extends Me.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=U,this.iceLog=U,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=us(r=>m(this,void 0,void 0,function*(){this.emit(bt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),$h),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=t,this.log=ye((i=t.loggerName)!==null&&i!==void 0?i:oe.PCTransport,()=>this.logContext),this.iceLog=ye(oe.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new fe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:t.candidate.candidate}),(i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;this.iceLog.debug("ICE candidate error",{event:t}),(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;this.log.debug("data channel opened by peer",{label:t.channel.label,id:t.channel.i
39d}),(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return m(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 m(this,void 0,void 0,function*(){var i,r;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;let s;if(e.type==="offer"){let a=rp(e),o=a.stereoMids,d=a.nackMids;this.remoteStereoMids=o,this.remoteNackMids=d}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){const d=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const c=Ne.parse((i=d.sdp)!==null&&i!==void 0?i:"");c.media.forEach(l=>{Fi(l)}),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(d,Ne.write(c))}const a=Ne.parse((r=e.sdp)!==null&&r!==void 0?r:"");a.media.forEach(d=>{const c=ki(d.mid);d.type==="audio"&&this.trackBitrates.some(l=>{if(!l.transceiver||c!=l.transceiver.mid)return!1;let u=0;if(d.rtp.some(p=>p.codec.toUpperCase()===l.codec.toUpperCase()?(u=p.payload,!0):!1),u===0)return!0;let h=!1;for(const p of d.fmtp)if(p.payload===u){p.config=p.config.split(";").filter(f=>!f.includes("maxaveragebitrate")).join(";"),l.maxbr>0&&(p.config+=";maxaveragebitrate=".concat(l.maxbr*1e3)),h=!0;break}return h||l.maxbr>0&&d.fmtp.push({payload:u,config:"maxaveragebitrate=".concat(l.maxbr*1e3)}),!0})});const o=this.getPlaceholderMids();o.size>0&&ka(a.media,d=>o.has(ki(d.mid))),s=Ne.write(a)}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(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(bt.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit
39(bt.NegotiationComplete),e.sdp&&Ne.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(bt.RTPVideoPayloadTypes,o.rtp)})),!0})}createInitialOffer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer");return}const i=this.latestOfferId+1;this.latestOfferId=i;const r=yield this.pc.createOffer();this.pendingInitialOffer={sdp:r.sdp,type:r.type};const s=Ne.parse((e=r.sdp)!==null&&e!==void 0?e:"");return s.media.forEach(a=>{Fi(a)}),r.sdp=Ne.write(s),{offer:r,offerId:i}}finally{t()}})}createAndSendOffer(e){return m(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){const d=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&d)yield this._pc.setRemoteDescription(d);else{if(e!=null&&e.iceRestart)throw new St("ICE restart requested without a remote description, peer connection must be recreated");this.renegotiate=!0,this.log.debug("requesting renegotiation");return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection");return}this.log.debug("starting to negotiate");const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:s.sdp});const a=Ne.parse((t=s.sdp)!==null&&t!==void 0?t:"");a.media.forEach(d=>{Fi(d),d.type==="audio"?ya(d,["all"],[]):d.type==="video"&&this.trackBitrates.some(c=>{if(!c.cid)return!1;const l=Xh(d,c.cid,c.codec,c.maxbr,c.isScreenShare);return l===void 0?!1:(l>0&&Xe(c.codec)&&!qt()&&(this.ddExtID=Zh(d,a,this.ddExtID)),!0)})});const o=this.getPlaceholderMids();if(o.size>0&&ka(a.media,d=>o.has(ki(d.mid))),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:r});return}yield this.setMungedSDP(s,Ne.write(a)),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Ne.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Fi(r),r.type==="audio"&&ya(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Ne.write(i)),t})}getPlaceholderMids(){var e,t;return np((t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[])}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Z("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 Z("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getMaxMessageSize(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.sctp)===null||t===void 0?void 0:t.maxMessageSize}getConnectedAddress(){return m(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,r=new Map;
39if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,i){return m(this,void 0,void 0,function*(){var r,s;const 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(o){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:o,mungedSdp:t,originalSdp:a}),e.sdp=a}}try{i?yield(r=this._pc)===null||r===void 0?void 0:r.setRemoteDescription(e):yield(s=this._pc)===null||s===void 0?void 0:s.setLocalDescription(e)}catch(o){let d="unknown error";o instanceof Error?d=o.message:typeof o=="string"&&(d=o);const c={error:d,sdp:e.sdp};throw t&&t!==a&&(c.mungedSdp=t),!i&&this.pc.remoteDescription&&(c.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:c}),new St(d)}})}}function Zh(n,e,t){var i,r;const s=ep(e,t);return s===void 0?t:(!((i=n.ext)===null||i===void 0)&&i.some(a=>a.uri===$t)||((r=n.ext)!==null&&r!==void 0||(n.ext=[]),n.ext.push({value:s,uri:$t})),s)}function ep(n,e){const t=tp(n,$t);return t!==void 0?ba(n,t,$t)?void 0:t:e!==0&&!ba(n,e,$t)?e:ip(n)}function tp(n,e){var t;for(const i of n.media){const r=(t=i.ext)===null||t===void 0?void 0:t.find(s=>s.uri===e);if(r)return r.value}}function ba(n,e,t){return n.media.some(i=>{var r;return(r=i.ext)===null||r===void 0?void 0:r.some(s=>s.value===e&&s.uri!==t)})}function ip(n){let e=0;return n.media.forEach(t=>{var i;(i=t.ext)===null||i===void 0||i.forEach(r=>{r.value>e&&(e=r.value)})}),e+1===15?16:e+1}function Bc(n,e){return n.split(";").some(t=>t.trim()===e)}function ya(n,e,t){const i=ki(n.mid);let r=0;n.rtp.some(s=>s.codec.toLowerCase()==="opus"?(r=s.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(s=>s.payload===r&&s.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(s=>s.payload===r?(Bc(s.config,"stereo=1")||(s.config+=";stereo=1"),!0):!1))}function np(n){const e=new Set;for(const t of n)t.mid&&!t.sender.track&&e.add(t.mid);return e}function ka(n,e){var t,i;const r=new Map,s=new Set;for(const a of n){const o=e(a);for(const d of(t=a.fmtp)!==null&&t!==void 0?t:[])o?r.has(d.payload)||r.set(d.payload,d.config):(r.set(d.payload,d.config),s.add(d.payload))}if(r.size!==0){for(const a of n)if(e(a))for(const o of(i=a.fmtp)!==null&&i!==void 0?i:[]){const d=r.get(o.payload);d!==void 0&&o.config!==d&&(o.config=d)}}}function rp(n){var e;const t=[],i=[],r=Ne.parse((e=n.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;const d=ki(a.mid);a.type==="audio"&&(a.rtp.some(c=>c.codec.toLowerCase()==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&i.push(d),a.fmtp.some(c=>c.payload===s?(Bc(c.config,"sprop-stereo=1")&&t.push(d),!0):!1))}),{stereoMids:t,nackMids:i}}function Fi(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function ki(n){return typeof n=="number"?n.toFixed(0):n}const Lr="vp8",sp={audioPreset:_r.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:as.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Lr,backupCodec:!0,preConnectBuffer:!1},qc={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Vc={deviceId:{ideal:"default"},resolution:Ri.h720.resolution},ap={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new gu,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},bs={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var $;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})($||($={}));class Ta{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 r;this.peerConnectionTimeout=bs.peerConnectionTimeout,this.log=U,this.iceLog=U,this.updateState=()=>{var s,a;const o=this.state,d=this.requiredTransports.map(c=>c.getConnectionState());d.every(c=>c==="connected")?this.state=$.CONNECTED:d.some(c=>c==="failed")?this.state=$.FAILED:d.some(c=>c==="connecting")?this.state=$.CONNECTING:d.every(c=>c==="closed")?this.state=$.CLOSED:d.some(c=>c==="closed")?this.state=$.CLOSING:d.every(c=>c==="new")&&(this.state=$.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat($[o]," to ").concat($[this.state])),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.loggerOptions=t,this.log=ye((r=t.loggerName)!==null&&r!==void 0?r:oe.PCManager,()=>this.logContext),this.iceLog=ye(oe.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new va(i,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new va(i,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Ve.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Ve.PUBLISHER)},this.publisher.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=(s,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,s,a)},this.state=$.NEW,this.connectionLock=new fe,this.remoteOfferLock=new fe}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!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 m(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(r){this.log.warn("could not removeTrack",{error:r})}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return m(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 m(this,void 0,void 0,function*(){var i;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===Ve.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return m(this,void 0,void 0,function*(){var i,r,s;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()});const a=yield this.remoteOfferLock.lock();try{return(yield(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,t))?yield(s=this.subscriber)===null||s===void 0?void 0:s.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;
39this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return m(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating"),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new Ee((t,i)=>{const r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let s=!1;const a=()=>{s||(s=!0,clearTimeout(c),this.publisher.off(bt.OfferAnswered,o),e.signal.removeEventListener("abort",d))},o=l=>{l>r&&(a(),t())},d=()=>{a(),i(new St("negotiation aborted"))},c=setTimeout(()=>{a(),i(new St("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",d),this.publisher.on(bt.OfferAnswered,o),this.publisher.negotiate(l=>{a(),l instanceof Error?i(l):i(new Error(String(l)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(r=>r.receiver===e);return i==null?void 0:i.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Ve.PUBLISHER?this.publisher.getConnectedAddress():e===Ve.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return m(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((d,c)=>m(s,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection"),Y.clearTimeout(u),c(x.cancelled("room connection has been cancelled"))};r!=null&&r.signal.aborted&&l(),r==null||r.signal.addEventListener("abort",l);const u=Y.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",l),c(x.internal("could not establish pc connection"))},a);for(;this.state!==$.CONNECTED;)if(yield Te(50),r!=null&&r.signal.aborted){c(x.cancelled("room connection has been cancelled"));return}Y.clearTimeout(u),r==null||r.signal.removeEventListener("abort",l),d()}))})()})}}class jc{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new fe,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&&arguments[0]!==void 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 m(this,void 0,void 0,function*(){const e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}})}waitForHeadroomWithoutLock(){return m(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new Z("engine closed");const e=this.getChannel();if(!e)throw new Z("DataChannel not found, kind: ".concat(this.kind));if(this.isBelowHighWaterMark(e))return;const t=this.waiterAbortController.signal;yield new Ee((i,r)=>{const s=()=>{d(),i()},a=()=>{d(),r(new Z("DataChannel ".concat(this.kind," closed while draining the buffer")))},o=()=>{d(),r(new Z("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},d=()=>{e.removeEventListener("bufferedamountlow",s),e.removeEventListener("close",a),t.removeEventListener("abort",o)};if(t.aborted){o();return}e.addEventListener("bufferedamountlow",s),e.addEventListener("close",a),t.addEventListener("abort",o)})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;const t=this.getChannel();if(!t)return;const i=this.isBelowLowWaterMark(t);i!==this.bufferStatusLow&&(this.bufferStatusLow=i,(e=this.onBufferStatusChanged)===null||e===void 0||e.call(this,i))}}class Sa extends jc{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return m(this,void 0,void 0,function*(){const 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&&U.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(i){if(i instanceof TypeError)U.error(i);else throw i}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=Y.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;const e=this.getChannel();if(e){const t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(Y.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}}class Ca{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(){const 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(const e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class op extends jc{constructor(e){super(e),this.messageBuffer=new Ca,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){const e=this.sequence;return this.sequence+=1,e}send(e,t){return m(this,void 0,void 0,function*(){if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}const i=this.getChannel();if(i){try{yield this.waitForHeadroomWithLock()}catch(r){if(this.isEngineClosed())throw r;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}this.messageBuffer.push({data:e,sequence:t,sent:!0}),i.send(e),this.refreshBufferStatus()}})}replay(e){return m(this,void 0,void 0,function*(){const t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);const i=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let r=this.messageBuffer.getUnsent();r.length>0;r=this.messageBuffer.getUnsent())for(const s of r)yield this.waitForHeadroomWithoutLock(),t.send(s.data),this.messageBuffer.markSent(s)}finally{i()}this.refreshBufferStatus()})}refreshBufferStatus(){const e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new Ca,this.sequence=1}}var q;(function(n){n[n.RELIABLE=0]="RELIABLE",n[n.LOSSY=1]="LOSSY",n[n.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(q||(q={}));const cp=64*1024,dp=1024*1024,lp=8*1024,up=256*1024;function hp(n){return n===q.RELIABLE?cp:lp}function pp(n){return n===q.RELIABLE?dp:up}const Ea="_lossy",_a="_reliable",wa="_data_track";class mp{constructor(e){this.opts=e;const t=i=>({kind:i,lowWaterMark:hp(i),highWaterMark:pp(i),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:r=>e.onBufferStatusChanged(i,r)});this.reliable=new op(Object.assign(Object.assign({},t(q.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new Sa(Object.assign(Object.assign({},t(q.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new Sa(Object.assign(Object.assign({},t(q.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case q.RELIABLE:return this.reliable;case q.LOSSY:return this.lossy;case q.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1))return this.channelFor(e).channelHandle;switch(e){case q.RELIABLE:return this.reliableSub;case q.LOSSY:return this.lossySub;case q.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(const i of[this.lossy,this.reliable,this.dataTrack]){const r=i.channelHandle;r&&(r.onmessage=null,r.onerror=null,r.onclose=null)}const t=(i,r,s)=>{r.onmessage=s,r.onerror=this.opts.onDataError,r.onclose=()=>this.opts.onChannelClose(i.kind),r.bufferedAmountLowThreshold=i.lowWaterMark,r.onbufferedamountlow=()=>i.refreshBufferStatus(),i.attach(r)};
39t(this.lossy,e.createPublisherDataChannel(Ea,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(_a,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(wa,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===_a)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===Ea)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===wa)this.dataTrackSub=e,t=this.opts.onDataTrackMessage;else return!1;return e.onmessage=t,!0}teardown(){const e=t=>{t&&(t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null,t.close())};for(const t of[this.lossy,this.reliable,this.dataTrack]){const 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()}}const ys=typeof MediaRecorder<"u";class fp{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const gp=ys?MediaRecorder:fp;class vp extends gp{constructor(e,t){if(!ys)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,r;const s=()=>r===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r==null||r.close(),r=void 0},o=d=>{r==null||r.error(d),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r=void 0};this.byteStream=new ReadableStream({start:d=>{r=d,i=c=>m(this,void 0,void 0,function*(){let l;if(c.data.arrayBuffer){const u=yield c.data.arrayBuffer();l=new Uint8Array(u)}else if(c.data.byteArray)l=c.data.byteArray;else throw new Error("no data available!");s()||d.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function bp(){return ys}const yp=1e3,kp=1e4;class Wc extends E{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 r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),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=us(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(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(R.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new fe,this.pauseUpstreamLock=new fe,this.trackChangeLock=new fe,this.trackChangeLock.lock().then(a=>m(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==E.Kind.Video)return;const 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(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,i){return m(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;
39this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{Yt(this._mediaStreamTrack,a)}),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());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Gt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),s=this.processor.processedTrack}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=i?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{Gt(s??e,a)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:yp;return(function*(){var i;if(e.kind===E.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=_e())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Te(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield Te(50)}throw new dt("unable to get track dimensions after timeout")})()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Xt(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Xt(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===E.Source.ScreenShare)return;const i=e._mediaStreamTrack.getSettings(),r=i.deviceId,s=i.groupId,a=e.kind===E.Kind.Audio?"audioinput":"videoinput";return t?me.getInstance().normalizeDeviceId(a,r,s):r})()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new dt("unable to replace an unpublished track");let r,s;typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor())}finally{i()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return m(this,void 0,void 0,function*(){})}restart(e,t){return m(this,void 0,void 0,function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const r=e,s=r.deviceId,a=r.facingMode,o=vu(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const d={audio:!1,video:!1};this.kind===E.Kind.Video?d.video=s||a?{deviceId:s,facingMode:a}:!0:d.audio=s?Object.assign({deviceId:s},o):!0,this.attachedElements.forEach(u=>{Yt(this.mediaStreamTrack,u)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(d)).getTracks()[0];return this.kind===E.Kind.Video&&(yield l.applyConstraints(o)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit
39(R.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?R.Muted:R.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Ac()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(R.UpstreamPaused,this);const i=_e();if((i==null?void 0:i.name)==="Safari"&&tt(i.version,"12.0")<0)throw new ss("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(R.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),d={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext,localTrack:i};if(yield t.init(d),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Gt(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>{c instanceof DOMException&&c.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:c})),setTimeout(()=>{o.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:c}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const c of i.attachedElements)c!==i.processorElement&&r&&(Yt(i._mediaStreamTrack,c),Gt(i.processor.processedTrack,c));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(R.TrackProcessorUpdate,i.processor)}finally{a()}yield i.onSenderTrackSwapped()})()})}getProcessor(){return this.processor}stopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}yield e.onSenderTrackSwapped()})()})}internalStopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(R.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!bp()){this.log.warn("MediaRecorder is not available, cannot start prec
39onnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new vp(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},kp)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class dn extends Wc{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,E.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=_n(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(R.AudioTrackFeatureUpdate,this,pe.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(R.AudioTrackFeatureUpdate,this,pe.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===E.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===E.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const i=os({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}applyConstraints(e){return m(this,void 0,void 0,function*(){const t=yield this.trackChangeLock.lock();try{const i=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),i}finally{t()}})}restart(e,t){const i=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const r=yield i.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){Ie()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},hs)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!ze()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={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(r),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?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
vendor: 4,055 bytes, line 39
39(R.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield Ic(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(R.AudioSilenceDetected)),e})}}function Tp(n,e,t){switch(n.kind){case"audio":return new dn(n,e,!1,void 0,t);case"video":return new un(n,e,!1,t);default:throw new dt("unsupported track type: ".concat(n.kind))}}const Sp=Object.values(Ri),Cp=Object.values(wr),Ep=Object.values(as),_p=[Ri.h180,Ri.h360],wp=[wr.h180,wr.h360],Pp=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new z(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,n.encoding.priority)}),xr=["q","h","f"];function ln(n,e,t,i){var r,s;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,d=i==null?void 0:i.scalabilityMode,c=i==null?void 0:i.videoCodec;if(!a&&!o&&!d||!e||!t)return[{}];a||(a=Rp(n,e,t,c),U.debug("using video encoding",a));const l=a.maxFramerate,u=new z(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(d&&Xe(c)){const k=new Kc(d),T=[];if(k.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));const S=_e();if(Ii()||ze()||(S==null?void 0:S.name)==="Chrome"&&tt(S==null?void 0:S.version,"113")<0){const L=k.suffix=="h"?2:3,b=th(S);for(let y=0;y<k.spatial;y+=1)T.push({rid:xr[2-y],maxBitrate:a.maxBitrate/Math.pow(L,y),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:b?Math.pow(2,y):void 0});T[0].scalabilityMode=d}else T.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:d});return u.encoding.priority&&(T[0].priority=u.encoding.priority,T[0].networkPriority=u.encoding.priority),U.debug("using svc encoding",{encodings:T}),T}if(!o)return[a];let h;n?h=(r=Ra(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Pa(n,u):h=(s=Ra(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Pa(n,u);let p;if(h.length>0){const k=h[0];if(h.length>1){var f=h,g=N(f,2);p=g[1]}const T=Math.max(e,t);if(T>=960&&p)return tr(e,t,[k,p,u],l);if(T>=480)return tr(e,t,[k,u],l)}return tr(e,t,[u])}function Hc(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&U.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),d=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,c=(s=o.height)!==null&&s!==void 0?s:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===E.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),ln(n.source===E.Source.ScreenShare,d,c,t)}function Rp(n,e,t,i){const r=Ip(n,e,t);let s=r[0].encoding;const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const d=r[o];if(s=d.encoding,d.width>=a)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function Ip(n,e,t){if(n)return Ep;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Sp:Cp}function Pa(n,e){if(n)return Pp(e);const t=e.width,i=e.height,r=t>i?t/i:i/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?_p:wp}function tr(n,e,t,i){const r=[];if(t.forEach((s,a)=>
39{if(a>=xr.length)return;const o=Math.min(n,e),c={rid:xr[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},l=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;l&&(c.maxFramerate=l);const u=_e(),h=(u==null?void 0:u.name)==="Firefox"&&u.os!=="iOS"||a===0;s.encoding.priority&&h&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),r.push(c)}),ze()&&Nc()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var d;o.maxFramerate!=s&&(a&&(a=!1,U.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),U.info('Setting framerate of encoding "'.concat((d=o.rid)!==null&&d!==void 0?d:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Ra(n){if(n)return n.slice().sort((e,t)=>{const i=e.encoding,r=t.encoding;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class Kc{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Mp(n){switch(n.source){case E.Source.Camera:return"maintain-framerate";case E.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}const Dp=5e3;class un extends Wc{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&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,E.Kind.Video,t,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(d){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:d}));return}const a=new Map(s.map(d=>[d.rid,d])),o=s.some(d=>d.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(R.CpuConstrained)),this.prevStats){let d=0;a.forEach((c,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);d+=_n(c,h)}),this._currentBitrate=d}this.prevStats=a}),this.senderLock=new fe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ie())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},hs))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,d=Le(this.simulcastCodecs.values()),c;c=yield d.next(),t=c.done,!t;o=!0)s=c.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return m(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,d=Le(this.simulcastCodecs.values()),c;c=yield d.next(),t=c.done,!t;o=!0){s=c.value,o=!1;const l=s;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===E.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===E.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();
vendor: 1,811 bytes, line 39
39return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Ae.LOW;i<=Ae.HIGH;i+=1)t.push(new ts({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Xe(this.codec),t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,i,r,s,a;let o;if(e){const u=os({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var d=!0,c=Le(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;d=!0){s=l.value,d=!1;const u=s;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!d&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return m(this,void 0,void 0,function*(){yield this.refreshSen
39derEncodings()})}refreshSenderEncodings(){return m(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let r;try{r=yield this.waitForDimensions()}catch(o){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:o}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===r.width&&this.lastEncodedDimensions.height===r.height)return;const s=this.source===E.Source.ScreenShare,a=ln(s,r.width,r.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=r;for(const o of this.simulcastCodecs){var i=N(o,2);const d=i[0],c=i[1];if(!c.sender||((e=c.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!Pc(d))continue;const l=Object.assign({},this.publishOptions),u=Hc(this,d,l);u&&(yield this.applyEncodingsToSender(c.sender,u),c.encodings=u)}}catch(r){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:r}))}finally{t()}})}applyEncodingsToSender(e,t){return m(this,void 0,void 0,function*(){const i=e.getParameters();!i.encodings||i.encodings.length!==t.length||(i.encodings.forEac
39h((r,s)=>{if(r.active===!1)return;const a=t[s];a.scaleResolutionDownBy!==void 0&&(r.scaleResolutionDownBy=a.scaleResolutionDownBy),a.maxBitrate!==void 0&&(r.maxBitrate=a.maxBitrate),a.maxFramerate!==void 0&&(r.maxFramerate=a.maxFramerate),a.priority!==void 0&&(r.priority=a.priority,r.networkPriority=a.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){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return m(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,d,c,l,u;if(yield t.setProcessor.call(r,i,s),!((l=r.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,p=Le(r.simulcastCodecs.values()),f;f=yield p.next(),a=f.done,!a;h=!0)c=f.value,h=!1,yield(u=c.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(g){o={error:g}}finally{try{!h&&!a&&(d=p.return)&&(yield d.call(p))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return m(this,void 0,void 0,function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(const t of this.simulcastCodecs.values())yield this.applyDegradationPreference(t.sender)})}applyDegradationPreference(e){return m(this,void 0,void 0,function*(){if(e)try{this.log.debug("setting degradationPreference to ".concat(this.degradationPreference),this.logContext);const t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){return m(this,void 0,void 0,function*(){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,yield this.applyDegradationPreference(t),setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Dp))})}setPublishingCodecs(e){return m(this,void 0,void 0,function*(){var t,i,r,s,a,o,d;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(Xe(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Le(e);r=yield i.next(),s=r.done,!s;t=!0){d=r.value,t=!1;const l=d;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Xe(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){c.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield Ia(u.sender,u.encodings,l.qualities,this.senderLock,Xe(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return m(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield Ia(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return m(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((i,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&Xe(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Ac()&&this.isInBackgroun
39d&&this.source===E.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Ia(n,e,t,i,r,s,a){return m(this,void 0,void 0,function*(){const o=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const d=n.getParameters(),c=d.encodings;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:c,senderEncodings:e}));return}let l=!1;!1&&c[0].scalabilityMode||(r&&t.some(p=>p.enabled)&&t.forEach(p=>p.enabled=!0),c.forEach((h,p)=>{var f;let g=(f=h.rid)!==null&&f!==void 0?f:"";g===""&&(g="q");const k=Gc(g),T=t.find(S=>S.quality===k);T&&h.active!==T.enabled&&(l=!0,h.active=T.enabled,s.debug("setting layer ".concat(T.quality," to ").concat(h.active?"enabled":"disabled"),a),Bt()&&(T.enabled?(h.scaleResolutionDownBy=e[p].scaleResolutionDownBy,h.maxBitrate=e[p].maxBitrate,h.maxFrameRate=e[p].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(d.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:d.encodings})),yield n.setParameters(d))}finally{o()}})}function Gc(n){switch(n){case"f":return Ae.HIGH;case"h":return Ae.MEDIUM;case"q":return Ae.LOW;default:return Ae.HIGH}}function Ma(n,e,t,i){if(!t)return[new kt({quality:Ae.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new Kc(r),a=[],o=s.suffix=="h"?1.5:2,d=s.suffix=="h"?2:3;for(let c=0;c<s.spatial;c+=1)a.push(new kt({quality:Math.min(Ae.HIGH,s.spatial-1)-c,width:Math.ceil(n/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(d,c)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const d=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let c=Gc((a=r.rid)!==null&&a!==void 0?a:"");return new kt({quality:c,width:Math.ceil(n/d),height:Math.ceil(e/d),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Ap=2*1e3,ir="leave-reconnect",Op=10*1e3,Np=3e4,Lp=3,xp=3;var De;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(De||(De={}));const Da=64e3;class Up extends Me.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=bs.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=De.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=U,this.reliableReceivedState=new Kh(Np),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>m(this,[i],void 0,function(r){var s=this;let a=r.channel;return(function*(){a&&s.dataChannels.adoptSubscriberChannel(a)&&s.log.debug("on data channel ".concat(a.id,", ").concat(a.label))})()}),this.handleDataMessage=i=>m(this,void 0,void 0,function*(){var r,s,a,o,d;const c=yield this.dataProcessLock.lock();try{const l=yield this.decodeDataMessage(i);if(!l)return;const u=Ce.fromBinary(l);if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((r=u.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(P.ActiveSpeakersUpdate,u.value.value.speakers);else if(((s=u.value)===null||s===void 0?void 0:s.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),p=ko.fromBinary(h.payload),f=new Ce({value:p.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=f.value)===null||o===void 0?void 0:o.case)==="user"&&Aa(f,f.value.value),this.emit
39(P.DataPacketReceived,f,u.value.value.encryptionType)}else((d=u.value)===null||d===void 0?void 0:d.case)==="user"&&Aa(u,u.value.value),this.emit(P.DataPacketReceived,u,H.NONE)}finally{c()}}),this.handleDataTrackMessage=i=>m(this,void 0,void 0,function*(){const r=yield this.decodeDataMessage(i);r&&this.emit("dataTrackPacketReceived",r)}),this.handleDataError=i=>{if(this._isClosed)return;const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&i instanceof RTCErrorEvent&&i.error){const a=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(a.message),{error:a,errorDetail:a.errorDetail,sctpCauseCode:a.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(s),{event:i})},this.handleDataChannelClose=i=>()=>{var r;!this._isClosed&&((r=this.pcManager)===null||r===void 0?void 0:r.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(q[i],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=d=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(d,"ms. giving up")),this.emit(P.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===ir&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(P.TokenRefreshed,this.token),this.reconnectTimeout=Y.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===De.Connected&&i();const s=()=>{this.off(P.Disconnected,a),i()},a=()=>{this.off(P.Restarted,s),r()};this.once(P.Restarted,s),this.once(P.Disconnected,a)}),this.onRtpMapAvailable=i=>{const r=new Map;i.forEach(s=>{const a=s.codec.toLowerCase();Lc(a)&&r.set(s.payload,a)}),this.emit(P.RTPVideoMapUpdate,r)},this.handleBrowserOnLine=()=>m(this,void 0,void 0,function*(){!this.url||!(yield fetch(Mi(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===J.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===J.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(nt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>m(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Mi(this.url),{method:"HEAD"}),Te(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=ye((t=e.loggerName)!==null&&t!==void 0?t:oe.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new gs(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new fe,this.dataProcessLock=new fe,this.dataChannels=new mp({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:i=>this.handleDataMessage(i),onDataTrackMessage:i=>this.handleDataTrackMessage(i),onDataError:i=>this.handleDataError(i),onChannelClose:i=>this.handleDataChannelClose(i)(),onBufferStatusChanged:(i,r)=>this.emit(P.DCBufferStatusChanged,r,i)}),this.client.onParticipantUpdate=i=>this.emit(P.ParticipantUpdate,i),this.client.onConnectionQuality=i=>{this.handleLocalConnectionQuality(i),this.emit(P.ConnectionQualityUpdate,i)},this.client.onRoomUpdate=i=>this.emit(P.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(P.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(P.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(P.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(P.StreamStateChanged,i),this.client.onRequestResponse=i=>
39this.emit(P.SignalRequestResponse,i),this.client.onParticipantUpdate=i=>this.emit(P.ParticipantUpdate,i),this.client.onJoined=i=>this.emit(P.Joined,i)}get logContext(){var e,t,i,r,s,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,participantID:this.participantSid}}join(e,t,i,r){return m(this,arguments,void 0,function(s,a,o,d){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){var u,h,p;c._isNewlyCreated=!1,c.url=s,c.token=a,c.signalOpts=o,c.maxJoinAttempts=o.maxRetries;try{c.joinAttempts+=1,c.setupSignalClientCallbacks();const f=!l&&fh();let g;if(f){c.pcManager||(yield c.configure(),c.applyInitialPublisherLayout());const S=yield(u=c.pcManager)===null||u===void 0?void 0:u.publisher.createInitialOffer();S&&(g=Ot(S.offer,S.offerId))}if(d!=null&&d.aborted)throw x.cancelled("Connection aborted");if(!l&&c.shouldFailOnV1Path)throw c.shouldFailOnV1Path=!1,x.serviceNotFound("Simulated v1 path failure","v0-rtc");const k=yield c.client.join(s,a,o,d,l,g);c._isClosed=!1,c.latestJoinResponse=k,c.participantSid=(h=k.participant)===null||h===void 0?void 0:h.sid,c.subscriberPrimary=k.subscriberPrimary,f?(p=c.pcManager)===null||p===void 0||p.updateConfiguration(c.makeRTCConfiguration(k)):(c.pcManager||(yield c.configure(k,!l),l||c.applyInitialPublisherLayout()),(!c.subscriberPrimary||k.fastPublish)&&c.negotiate().catch(S=>{c.log.error(S)})),c.registerOnLineListener(),c.clientConfiguration=k.clientConfiguration,c.emit(P.SignalConnected,k);let T=k.serverInfo;return T||(T={version:k.serverVersion,region:k.serverRegion}),c.log.info("connected to Livekit Server ".concat(Object.entries(T).map(S=>{let L=N(S,2),b=L[0],y=L[1];return"".concat(b,": ").concat(y)}).join(", "))),{joinResponse:k,serverInfo:T}}catch(f){if(f instanceof x){if(f.reason===Q.ServerUnreachable){if(c.log.warn("Couldn't connect to server, attempt ".concat(c.joinAttempts," of ").concat(c.maxJoinAttempts)),c.joinAttempts<c.maxJoinAttempts)return c.join(s,a,o,d,l)}else if(f.reason===Q.ServiceNotFound)return c.log.warn("Initial connection failed: ".concat(f.message," – Retrying")),c.pcManager&&(c.pcManager.onStateChange=void 0,yield c.cleanupPeerConnections()),c.join(s,a,o,d,!0)}throw f}})()})}close(){return m(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(P.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return m(this,void 0,void 0,function*(){var e;this.dataChannels.teardown(),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(){return m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new dt("a track with the same ID has already been published");return new Promise((t,i)=>{const r=Y.setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(x.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{Y.clearTimeout(r),t(s)},reject:()=>{Y.clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",{error:t})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.dataChannelForKind(q.RELIABLE,!0))===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return m(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return m(this,void 0,void 0,function*(){var i;if(!(this.pcManager&&this.pcManager.currentState!==$.NEW)){if(e){this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new Ta(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,r)}else{const r=this.makeRTCConfiguration();this.pcManager=new Ta("publisher-only",this.loggerOptions,r)}
39this.emit(P.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=(r,s)=>{this.client.sendOffer(r,s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,a)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r)),r===$.CONNECTING?this.transportConnectingSince=Date.now():this.transportConnectingSince=void 0,["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===$.CONNECTED){const c=this.pcState===De.New;this.pcState=De.Connected,c&&this.emit(P.Connected,this.latestJoinResponse)}else r===$.FAILED&&(this.pcState===De.Connected||this.pcState===De.Reconnecting)&&(this.pcState=De.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?nt.RR_SUBSCRIBER_FAILED:nt.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===J.RECONNECTING,d=[$.FAILED,$.CLOSING,$.CLOSED].includes(r);o&&d&&!this._isClosed&&this.emit(P.Offline)}),this.pcManager.onTrack=r=>{r.streams.length!==0&&this.emit(P.MediaTrackAdded,r.track,r.streams[0],r.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>m(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)=>m(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),{cid:e.cid});return}const i=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(P.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(P.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(P.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(P.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(P.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(P.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(P.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(P.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(P.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",nt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(e==null?void 0:e.action,")"),{reason:e==null?void 0:e.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(P.ServerRegionsReported,e.regions)),e.action){case Jt.DISCONNECT:this.emit(P.Disconnected,e==null?void 0:e.reason),this.close();break;case Jt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ir);break;case Jt.RESUME:this.handleDisconnect(ir)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((((t=this.signalOpts)===null||t===void 0?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!Di())&&ls()&&(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){const s=[];
39e.iceServers.forEach(a=>{const o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),s.push(o)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ei.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(){this.createDataChannels(),ze()||this.addMediaSections(Lp,xp)}addMediaSections(e,t){var i,r,s;const a={direction:"recvonly"};for(let d=0;d<e;d++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("audio",a);const o=((r=this.pcManager)===null||r===void 0?void 0:r.mode)==="publisher-only";for(let d=0;d<t;d++){const c=(s=this.pcManager)===null||s===void 0?void 0:s.addPublisherTransceiverOfKind("video",a);if(o&&c){const l=$u(c);this.log.debug("dependency descriptor negotiated for received video",{negotiated:l})}}}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return m(this,void 0,void 0,function*(){if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Blob)return new Uint8Array(yield e.data.arrayBuffer());this.log.error("unsupported data type",{data:e.data})})}createSender(e,t,i){return m(this,void 0,void 0,function*(){let r;if(Ir())r=yield this.createTransceiverRTCRtpSender(e,t,i);else if(Mr())this.log.warn("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new Z("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,i,r){return m(this,void 0,void 0,function*(){let s;if(Ir())s=yield this.createSimulcastTransceiverSender(e,t,i,r);else if(Mr())this.log.debug("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new Z("Cannot stream on this device");return s&&this.setupFrameMetadataSender(s,i),s})}get frameMetadataWorker(){var e,t;return(t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer)===null||t===void 0?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r,s;const a=this.frameMetadataWorker;if(!a||!((i=this.signalOpts)===null||i===void 0)&&i.e2eeEnabled)return;const o=(r=t.frameMetadata)!==null&&r!==void 0?r:t.packetTrailer,d=on(o);if(Di()){d&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:o}));return}if(!Ai((s=this.options.frameMetadata)!==null&&s!==void 0?s:this.options.packetTrailer)||!("createEncodedStreams"in e)){d&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}const c=e.createEncodedStreams(),l=c.readable,u=c.writable;d?a.postMessage({kind:"encode",data:{readableStream:l,writableStream:u,packetTrailer:o}},[l,u]):l.pipeTo(u)}createTransceiverRTCRtpSender(e,t,i){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Z("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),ht(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,r){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Z("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return yield e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Z("publisher is closed");return this.pcManager.addPublisherTrack(e)})}handleLocalConnectionQuality(e){if(!this.participantSid)return;const t=e.updates.find(i=>i.participantSid===this.participantSid);t&&(t.quality===Ht.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||(this.lostQualityTimeout=Y.setTimeout(()=>{this.lostQualityTimeout=void 0,!(this._isClosed||this.pcState!==De.Connected||this.attemptingReconnect)&&this.hasActivePublisherSenders()&&(this.log.warn("local connection quality lost while publishing, triggering full reconnect",this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect("connection quality lost",nt.RR_PUBLISHER_FAILED))},Op))}clearLostQualityTimeout(){this.lostQualityTimeout&&(Y.clearTimeout(this.lostQualityTimeout),this.lostQualityTimeout=void 0)}hasActivePublisherSenders(){var e,t;return(t=(e=this.pcManager)===null||e===void 0?void 0:e.publisher.getSenders().some(i=>!!i.track&&i.track.readyState==="live"))!==null&&t!==void 0?t:!1}reconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:nt.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect("reconcile",e)}attemptReconnect(e){return m(this,void 0,void 0,function*(){var t,i,r;if(this._isClosed)return;if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}this.clearLostQualityTimeout(),(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ei.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:$.NEW)===$.NEW)&&(this.fullReconnectOnNext=!0);const s=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let a=!1;try{this.attemptingReconnect=!0,s?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),a=!0}catch(o){this.reconnectAttempts+=1;let d=!0;o instanceof Z?(this.log.debug("received unrecoverable error",{error:o}),d=!1):(s||!(o instanceof Wt))&&(this.fullReconnectOnNext=!0),d?this.handleDisconnect("reconnect",nt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit
39(P.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1,a&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug("full reconnect requested during in-progress attempt, dispatching"),this.handleDisconnect("reconnect"))}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",{error:t})}return null}restartConnection(e){return m(this,void 0,void 0,function*(){var t,i,r;try{if(!this.url||!this.token)throw new Z("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(P.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new Wt;s=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(a){throw a instanceof x&&a.reason===Q.NotAllowed?new Z("could not reconnect, token might be expired"):new Wt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(P.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==J.CONNECTED)throw new Wt("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(P.Restarted)}catch(s){const a=yield(i=this.regionStrategy)===null||i===void 0?void 0:i.getNextUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionStrategy)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return m(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new Z("could not reconnect, url or token not saved");if(!this.pcManager)throw new Z("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(P.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,{error:r})),r instanceof x&&r.reason===Q.NotAllowed?new Z("could not reconnect, token might be expired"):r instanceof x&&r.reason===Q.LeaveRequest?r:new Wt(s)}
39if(this.emit(P.SignalResumed),t){const r=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==J.CONNECTED)throw new Wt("Signal connection got severed during reconnect");this.client.setReconnected();const i=this.dataChannelForKind(q.RELIABLE);(i==null?void 0:i.readyState)==="open"&&i.id===null&&this.createDataChannels(),t!=null&&t.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(r=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:r}))}),this.emit(P.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Z("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=De.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Te(Ap),!this.pcManager)throw new Z("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=De.Connected}catch(e){throw this.pcState=De.Disconnected,x.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const i=new Ce({destinationIdentities:[e],kind:Tt.RELIABLE,value:{case:"rpcAck",value:new bn({requestId:t})}});yield this.sendDataPacket(i,q.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){var i,r;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const o=_h(e);if(o){const d=yield this.e2eeManager.encryptData(o.toBinary());e.value={case:"encryptedPacket",value:new yo({encryptedValue:d.payload,iv:d.iv,keyIndex:d.keyIndex})}}}t===q.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());const s=e.toBinary(),a=Math.min((r=(i=this.pcManager)===null||i===void 0?void 0:i.getMaxPublisherMessageSize())!==null&&r!==void 0?r:Da,Da);if(typeof a<"u"&&a!==0&&s.byteLength>a)throw new Lu("cannot publish data packet larger than ".concat(a," bytes (got ").concat(s.byteLength,")"));t===q.RELIABLE?yield this.reliableChannel.send(s,e.sequence):yield this.lossyChannel.send(s)})}sendDataTrackFrame(e){return m(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(q.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return m(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(q.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return m(this,void 0,void 0,function*(){return this.flowControlFor(e).waitForHeadroomWithLock()})}ensureDataTransportConnected(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!i.pcManager)throw new Z("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw x.internal("".concat(o," connection not set"));let d=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),d=!0),!d&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(d=!0),d&&i.negotiate().catch(u=>{i.log.error(u)});const c=i.dataChannelForKind(t,r);if((c==null?void 0:c.readyState)==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((s=i.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield Te(50)}throw x.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){if(!this.pcManager)return!1;const e=this.pcManager.currentState;return![$.CONNECTING,$.CONNECTED].includes(e)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED?!1:e===$.CONNECTING&&this.transportConnectingSince!==void 0&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout?(this.log.warn("transport stuck in connecting state",this.logContext),!1):!0}negotiate(){return m(this,void 0,void 0,function*(){return new Ee((e,t)=>
39m(this,void 0,void 0,function*(){if(!this.pcManager){t(new St("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.dataChannels.hasPublisherChannels&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new St("cannot negotiate on closed engine")),this.on(P.Closing,r),this.on(P.Restarting,r),this.pcManager.publisher.off(bt.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(bt.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),e()}catch(s){if(i.signal.aborted){e();return}s instanceof St&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",nt.RR_UNKNOWN),s instanceof Error?t(s):t(new Error(String(s)))}finally{this.off(P.Closing,r),this.off(P.Restarting,r)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,i){var r,s,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}const d=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getRemoteDescription(),u=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),h=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,p=new Array,f=new Array;e.forEach(g=>{g.isDesired!==h&&p.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new is({answer:this.pcManager.mode==="publisher-only"?c?Ot({sdp:c.sdp,type:c.type}):void 0:u?Ot({sdp:u.sdp,type:u.type}):void 0,offer:this.pcManager.mode==="publisher-only"?d?Ot({sdp:d.sdp,type:d.type}):void 0:l?Ot({sdp:l.sdp,type:l.type}):void 0,subscription:new Sn({trackSids:p,subscribe:!h,participantTracks:[]}),publishTracks:ju(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,k)=>new Vo({publisherSid:k,lastSeq:g})),publishDataTracks:i.map(g=>new Yr({info:cn.toProtobuf(g)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new jo({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(q.LOSSY),Ve.PUBLISHER),t(this.dataChannelForKind(q.RELIABLE),Ve.PUBLISHER),t(this.dataChannelForKind(q.LOSSY,!0),Ve.SUBSCRIBER),t(this.dataChannelForKind(q.RELIABLE,!0),Ve.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Y.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ie()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Ie()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const r=Object.entries(this.midToTrackId).find(s=>N(s,1)[0]===i);if(r)return r[1]}}}function Aa(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}const Bi=ye(oe.Region),Ur=5e3,Fp=3e4;class W{static fetchRegionSettings(e,t,i){return m(this,void 0,void 0,function*(){const r=yield W.fetchLock.lock();try{const s=yield fetch("".concat(Bp(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(s.ok){const a=mh(s.headers),o=a?a*1e3:Ur;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw s.status===401?x.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):x.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof x?s:i!=null&&i.aborted?x.cancelled("Region fetching was aborted"):x.serverUnreachable("C
39ould not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,t,i){return m(this,void 0,void 0,function*(){const r=W.settingsTimeouts.get(e.hostname);clearTimeout(r),W.settingsTimeouts.set(e.hostname,setTimeout(()=>m(this,void 0,void 0,function*(){try{const s=yield W.fetchRegionSettings(e,t);W.updateCachedRegionSettings(e,t,s)}catch(s){if(s instanceof x&&s.reason===Q.NotAllowed){Bi.debug("token is not valid, cancelling auto region refresh");return}Bi.debug("auto refetching of region settings failed",{error:s}),W.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){W.cache.set(e.hostname,i),W.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=W.settingsTimeouts.get(e);t&&(clearTimeout(t),W.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=W.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=W.connectionTrackers.get(e);i&&i.connectionCount===0&&(Bi.debug("stopping region refetch after disconnect delay",{hostname:e}),W.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},Fp))}static cancelCleanup(e){const t=W.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=W.connectionTrackers.get(e);t||(t={connectionCount:0},W.connectionTrackers.set(e,t)),t.connectionCount++,W.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=W.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&W.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const i=this.getServerUrl(),r=W.cache.get(i.hostname);W.scheduleRefetch(this.serverUrl,this.token,(t=r==null?void 0:r.maxAgeInMs)!==null&&t!==void 0?t:Ur)}isCloud(){return si(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){return W.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=W.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),W.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(i.length>0){const r=i[0];return this.attemptedRegions.push(r),Bi.info("switching to region: ".concat(r.region),{region:r.region}),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){W.updateCachedRegionSettings(this.serverUrl,this.token,e)}}W.cache=new Map;W.settingsTimeouts=new Map;W.connectionTrackers=new Map;W.fetchLock=new fe;function Bp(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}function nr(){return new CompressionStream("deflate-raw")}function zc(){return new DecompressionStream("deflate-raw")}function Oa(n,e){return m(this,void 0,void 0,function*(){const t=new DecompressionStream("deflate-raw"),i=t.writable.getWriter();return i.write(n).catch(()=>{}),i.close().catch(()=>{}),Jc(t.readable,e)})}function Jc(n,e){return m(this,void 0,void 0,function*(){const t=n.getReader(),i=[];let r=0;for(;;){const o=yield t.read(),d=o.done,c=o.value;if(d)break;if(i.push(c),r+=c.byteLength,typeof e=="number"&&r>e)throw yield t.cancel(),new le("Decompressed payload exceeds the maximum payload size of ".concat(e," bytes"),ne.PayloadTooLarge)}const s=new Uint8Array(r);let a=0;for(const o of i)s.set(o,a),a+=o.byteLength;return s})}const Nt=15e3,qp=5e9;class Qc{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new le("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ne.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new le("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ne.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class Na extends Qc{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>m(this,void 0,void 0,function*(){var i;try{const r=this.signal;if(r!=null&&r.aborted)throw r.reason;const s=yield new Promise((a,o)=>
39{if(r){const d=()=>o(r.reason);r.addEventListener("abort",d,{once:!0}),e.read().then(a,o).finally(()=>{r.removeEventListener("abort",d)})}else e.read().then(a,o)});return s.done?(this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((i=this.onProgress)===null||i===void 0||i.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(s.value),{done:!1,value:s.value.content})}catch(r){throw t(),r}}),return(){return m(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,a;let o=new Set;const d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Le(d),u;u=yield l.next(),i=u.done,!i;c=!0){a=u.value,c=!1;const h=a;o.add(h)}}catch(h){r={error:h}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return Array.from(o)})()})}}class La extends Qc{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Dt(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=new TextDecoder("utf-8"),i=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>m(this,void 0,void 0,function*(){var s;try{if(i!=null&&i.aborted)throw i.reason;const a=yield new Promise((o,d)=>{if(i){const c=()=>d(i.reason);i.addEventListener("abort",c,{once:!0}),e.read().then(o,d).finally(()=>{i.removeEventListener("abort",c)})}else e.read().then(o,d)});if(a.done)return this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((s=this.onProgress)===null||s===void 0||s.call(this,1)),{done:!0,value:void 0};{this.handleChunkReceived(a.value);let o;try{o=t.decode(a.value.content)}catch(d){throw new le("Cannot decode datastream chunk ".concat(a.value.chunkIndex," as text: ").concat(d),ne.DecodeFailed)}return{done:!1,value:o}}}catch(a){throw r(),a}}),return(){return m(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,a;let o="";const d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Le(d),u;u=yield l.next(),i=u.done,!i;c=!0)a=u.value,c=!1,o+=a}catch(h){r={error:h}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return o})()})}}class Vp{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:qp;this.log=U,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(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const i=t.packet,r=t.encryptionType;this.handleDataStreamPacket(i,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new le('A text stream handler for topic "'.concat(e,'" has already been set.'),ne.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new le('A byte stream handler for topic "'.concat(e,'" has already been set.'),ne.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.entr
39ies()).filter(a=>a[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){const a=new le("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ne.AbnormalEnd);for(const o of i){var r=N(o,2);const d=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(d)}for(const o of t){var s=N(o,2);const d=s[0];s[1].controller.error(a),this.textStreamControllers.delete(d)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}handleStreamHeader(e,t,i){var r;switch(e.contentHeader.case){case"byteHeader":{const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Dt(e.timestamp),attributes:e.attributes,encryptionType:i};let d;switch(e.compression){case ke.DEFLATE_RAW:if(!Ct()){U.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}d=!0;break;case ke.NONE:d=!1;break;default:U.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}const c=e.inlineContent;if(typeof c<"u"){s(new Na(o,xa(e.streamId,d?Oa(c,this.maxPayloadByteLength):c),Dt(e.totalLength)),{identity:t});return}const l=new ReadableStream({start:u=>{if(a=u,this.byteStreamControllers.has(e.streamId))throw new le("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ne.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new Na(o,d?Hp(l,e.streamId,this.maxPayloadByteLength):l,Dt(e.totalLength)),{identity:t});return}case"textHeader":{const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o={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};let d;switch(e.compression){case ke.DEFLATE_RAW:if(!Ct()){U.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}d=!0;break;case ke.NONE:d=!1;break;default:U.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}const c=e.inlineContent;if(typeof c<"u"){const u=d?Oa(c,this.maxPayloadByteLength):c;s(new La(o,xa(e.streamId,u),Dt(e.totalLength)),{identity:t});return}const l=new ReadableStream({start:u=>{if(a=u,this.textStreamControllers.has(e.streamId))throw new le("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ne.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new La(o,d?Kp(l,e.streamId,this.maxPayloadByteLength):l,Dt(e.totalLength)),{identity:t});return}}}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new le("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ne.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?(r.controller.error(new le("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),ne.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new le("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ne.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),e.reason?i.controller.error(new le("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),ne.AbnormalEnd)):i.controller.close()),this.textStreamControllers.delete(e.streamId));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new le("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),ne.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),e.reason?r.controller.error(new le("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),ne.AbnormalEnd)):r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}function xa(n,e){return new ReadableStream({start:t=>m(this,void 0,void 0,function*(){try{const i=yield e;t.enqueue(new lt({streamId:n,chunkIndex:BigInt(0),content:i})),t.close()}catch(i){t.error(i)}})})}function Yc(n){let e=-1;return new TransformStream({transform:(t,i)=>{const r=Dt(t.chunkIndex);if(r<=e){U.warn("ignoring duplicate chunk ".concat(r," for compressed data stream ").concat(n," (last processed: ").concat(e,")"));return}if(r>e+1)throw new le("Missing chunk(s) ".concat(e+1,"..").concat(r-1," for compressed data stream ").concat(n," - cannot continue decompressing"),ne.Incomplete);e=r,i.enqueue(t)}})}function $c(){return new TransformStream({transform:(n,e)=>{e.enqueue(n.content)}})}function jp(n){let e=0;return new TransformStream({transform:(t,i)=>{t.byteLength>0&&(i.enqueue(new lt({streamId:n,chunkIndex:Ge(e),content:t})),e+=1)}})}function Wp(n){const e=new TextDecoder("utf-8"),t=new TextEncoder;let i=0;const r=s=>{try{return s?e.decode(s,{stream:!0}):e.decode()}catch(a){throw new le("Cannot decode compressed data stream ".concat(n," as text: ").concat(a),ne.DecodeFailed)}};return new TransformStream({transform:(s,a)=>{const o=r(s);o.length>0&&(a.enqueue(new lt({streamId:n,chunkIndex:Ge(i),content:t.encode(o)})),i+=1)},flush:s=>{const a=r();a.length>0&&(s.enqueue(new lt({streamId:n,chunkIndex:Ge(i),content:t.encode(a)})),i+=1)}})}function Hp(n,e,t){return n.pipeThrough(Yc(e)).pipeThrough($c()).pipeThrough(zc()).pipeThrough(Xc(e,t)).pipeThrough(jp(e))}function Kp(n,e,t){return n.pipeThrough(Yc(e)).pipeThrough($c()).pipeThrough(zc()).pipeThrough(Xc(e,t)).pipeThrough(Wp(e))}function Xc(n,e){let t=0;return new TransformStream({transform:(i,r)=>{if(t+=i.byteLength,t>e)throw new le("Data stream ".concat(n," exceeds the maximum payload size of ").concat(e," bytes"),ne.PayloadTooLarge);r.enqueue(i)}})}class Zc{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 m(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Gp extends Zc{}class zp extends Zc{}function rr(n,e,t){var i;return new yn({streamId:n.id,mimeType:n.mimeType,topic:n.topic,timestamp:Ge(n.timestamp),totalLength:Ge(n.size),attributes:n.attributes,compression:(i=t==null?void 0:t.compression)!==null&&i!==void 0?i:ke.NONE,inlineContent:t==null?void 0:t.inlineContent,contentHeader:{case:"textHeader",value:new Do({version:e==null?void 0:e.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?hr.UPDATE:hr.CREATE})}})}function qi(n,e){var t;return new yn({streamId:n.id,mimeType:n.mimeType,topic:n.topic,timestamp:Ge(n.timestamp),totalLength:Ge(n.size),attributes:n.attributes,compression:(t=e==null?void 0:e.compression)!==null&&t!==void 0?t:ke.NONE,inlineContent:e==null?void 0:e.inlineContent,contentHeader:{case:"byteHeader",value:new Ao({name:n.name})}})}function It(n,e){return new Ce({destinationIdentities:e,value:{case:"streamHeader",value:n}})}const Jp=new TextEncoder;class Qp{constructor(e,t,i,r,s){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=i,this.getRemoteParticipantCapabilities=r,this.getAllRemoteParticipantIdentities=s}setupEngine(e){this.engine=e}sendText(e,t){return m(this,void 0,void 0,function*(){var i,r,s,a,o;const d=crypto.randomUUID(),c=Jp.encode(e),l=c.byteLength,u=(i=t==null?void 0:t.compress)!==null&&i!==void 0?i:!0;let h={id:d,mimeType:"text/plain",timestamp:Date.now(),topic:(r=t==null?void 0:t.topic)!==null&&r!==void 0?r:"",size:l,attributes:t==null?void 0:t.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?H.GCM:H.NONE},f=u&&Ct()&&this.allRecipientsSupportV2(t==null?void 0:t.destinationIdentities)&&this.allRecipientsSupportCompression(t==null?void 0:t.destinationIdentities)?hn.fromStream(en(c).pipeThrough(nr
39())):null;if((!(t!=null&&t.attachments)||t.attachments.length===0)&&this.allRecipientsSupportV2(t==null?void 0:t.destinationIdentities)){let b=c,y=ke.NONE;if(f){const A=yield f.collect();A.byteLength<c.byteLength&&(b=A,y=ke.DEFLATE_RAW)}const C=rr(h,void 0,{compression:y,inlineContent:b}),I=It(C,t==null?void 0:t.destinationIdentities);if(I.toBinary().byteLength<=Nt)return yield this.engine.sendDataPacket(I,q.RELIABLE),(a=t==null?void 0:t.onProgress)===null||a===void 0||a.call(t,1),h}const k=(o=t==null?void 0:t.attachments)===null||o===void 0?void 0:o.map(()=>crypto.randomUUID()),T=k?k.length+1:1,S=new Array(T).fill(0),L=(b,y)=>{var C;S[y]=b,(C=t==null?void 0:t.onProgress)===null||C===void 0||C.call(t,S.reduce((I,A)=>I+A,0)/T)};if(f){h.attachedStreamIds=k;const b=rr(h,void 0,{compression:ke.DEFLATE_RAW}),y=It(b,t==null?void 0:t.destinationIdentities);yield this.sendChunkedByteStream(y,d,t==null?void 0:t.destinationIdentities,f.stream().pipeThrough(sr(c.length,C=>L(C,0)))),c.length===0&&L(1,0)}else{const b=yield this.streamText({streamId:d,totalSize:l,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:k,attributes:t==null?void 0:t.attributes});yield b.write(e),L(1,0),yield b.close(),h=b.info}return t!=null&&t.attachments&&k&&(yield Promise.all(t.attachments.map((b,y)=>m(this,void 0,void 0,function*(){return this._sendFile(k[y],b,{topic:t.to
39pic,mimeType:b.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:C=>{L(C,y+1)}})})))),h})}sendBytes(e,t){return m(this,void 0,void 0,function*(){var i,r,s,a,o,d,c;const l=crypto.randomUUID(),u=t==null?void 0:t.destinationIdentities,h=(i=t==null?void 0:t.compress)!==null&&i!==void 0?i:!0,p={id:l,name:(r=t==null?void 0:t.name)!==null&&r!==void 0?r:"unknown",mimeType:(s=t==null?void 0:t.mimeType)!==null&&s!==void 0?s:"application/octet-stream",timestamp:Date.now(),topic:(a=t==null?void 0:t.topic)!==null&&a!==void 0?a:"",size:e.byteLength,attributes:t==null?void 0:t.attributes,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?H.GCM:H.NONE},f=sr(e.length,t==null?void 0:t.onProgress);let k=h&&Ct()&&this.allRecipientsSupportV2(u)&&this.allRecipientsSupportCompression(u)?hn.fromStream(en(e).pipeThrough(f).pipeThrough(nr())):null;if(this.allRecipientsSupportV2(u)){let b=e,y=ke.NONE;if(k){const A=yield k.collect();A.byteLength<e.byteLength&&(b=A,y=ke.DEFLATE_RAW)}const C=qi(p,{compression:y,inlineContent:b}),I=It(C,u);if(I.toBinary().byteLength<=Nt)return yield this.engine.sendDataPacket(I,q.RELIABLE),(d=t==null?void 0:t.onProgress)===null||d===void 0||d.call(t,1),p}const T=qi(p,{compression:k?ke.DEFLATE_RAW:ke.NONE}),S=It(T,u),L=k?k.stream():en(e).pipeThrough(f);return yield this.sendChunkedByteStream(S,l,u,L),e.length===0&&((c=t==null?void 0:t.onProgress)===null||c===void 0||c.call(t,1)),p})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(i=>this.getRemoteParticipantClientProtocol(i)>=wc)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(i=>this.getRemoteParticipantCapabilities(i).includes(wi.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,i,r){return m(this,void 0,void 0,function*(){var s,a,o,d;const c=this.engine;yield ar(c,e);let l=0;try{for(var u=!0,h=Le(ph(r,Nt)),p;p=yield h.next(),s=p.done,!s;u=!0){d=p.value,u=!1;const f=d,g=new Ce({destinationIdentities:i,value:{case:"streamChunk",value:new lt({content:f,streamId:t,chunkIndex:Ge(l)})}});yield c.sendDataPacket(g,q.RELIABLE),l+=1}}catch(f){a={error:f}}finally{try{!u&&!s&&(o=h.return)&&(yield o.call(h))}finally{if(a)throw a.error}}yield or(t,i,c)})}streamText(e){return m(this,void 0,void 0,function*(){var t,i,r;const s=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e==null?void 0:e.destinationIdentities,o={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?H.GCM:H.NONE,attachedStreamIds:e==null?void 0:e.attachedStreamIds},d=rr(o,e),c=It(d,a);yield ar(this.engine,c);let l=0;const u=this.engine,h=new WritableStream({write(g){return m(this,void 0,void 0,function*(){for(const k of hh(g,Nt)){const T=new lt({content:k,streamId:s,chunkIndex:Ge(l)}),S=new Ce({destinationIdentities:a,value:{case:"streamChunk",value:T}});yield u.sendDataPacket(S,q.RELIABLE),l+=1}})},close(){return m(this,void 0,void 0,function*(){yield or(s,a,u)})},abort(g){console.log("Sink error:",g)}});let p=()=>m(this,void 0,void 0,function*(){yield f.close()});u.once(P.Closing,p);const f=new Gp(h,o,()=>this.engine.off(P.Closing,p));return f})}sendFile(e,t){return m(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return m(this,void 0,void 0,function*(){var r,s,a,o,d;const c=i==null?void 0:i.destinationIdentities,l=((r=i==null?void 0:i.compress)!==null&&r!==void 0?r:!0)&&Ct()&&this.allRecipientsSupportV2(c)&&this.allRecipientsSupportCompression(c),u={id:e,name:t.name,mimeType:(s=i==null?void 0:i.mimeType)!==null&&s!==void 0?s:t.type,topic:(a=i==null?void 0:i.topic)!==null&&a!==void 0?a:"",timestamp:Date.now(),size:t.size,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?H.GCM:H.NONE},h=qi(u,{compression:l?ke.DEFLATE_RAW:ke.NONE}),p=It(h,c),f=t.stream().pipeThrough(sr(t.size,i==null?void 0:i.onProgress)),g=l?f.pipeThrough(nr
39()):f;return yield this.sendChunkedByteStream(p,e,c,g),t.size===0&&((d=i==null?void 0:i.onProgress)===null||d===void 0||d.call(i,1)),u})}streamBytes(e){return m(this,void 0,void 0,function*(){var t,i,r,s,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?H.GCM:H.NONE},l=qi(c),u=It(l,d);yield ar(this.engine,u);let h=0;const p=new fe,f=this.engine,g=this.log,k=new WritableStream({write(S){return m(this,void 0,void 0,function*(){const L=yield p.lock();let b=0;try{for(;b<S.byteLength;){const y=S.slice(b,b+Nt),C=new Ce({destinationIdentities:d,value:{case:"streamChunk",value:new lt({content:y,streamId:o,chunkIndex:Ge(h)})}});yield f.sendDataPacket(C,q.RELIABLE),h+=1,b+=y.byteLength}}finally{L()}})},close(){return m(this,void 0,void 0,function*(){yield or(o,d,f)})},abort(S){g.error("Sink error:",S)}});return new zp(k,c)})}}class hn{constructor(e){this.state=e}static fromStream(e){return new hn({type:"stream",stream:e})}collect(){return m(this,void 0,void 0,function*(){switch(this.state.type){case"stream":const e=yield Jc(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 en(this.state.bytes)}}}function sr(n,e){let t=0;return new TransformStream({transform(i,r){t+=i.byteLength,e&&typeof n=="number"&&n>0&&e(Math.min(t/n,1)),r.enqueue(i)}})}function ar(n,e){return m(this,void 0,void 0,function*(){if(e.toBinary().byteLength>Nt)throw new le("data stream header exceeds the ".concat(Nt,"-byte limit; reduce attribute size"),ne.HeaderTooLarge);yield n.sendDataPacket(e,q.RELIABLE)})}function or(n,e,t){return m(this,void 0,void 0,function*(){const i=new Ce({destinationIdentities:e,value:{case:"streamTrailer",value:new Jr({streamId:n})}});yield t.sendDataPacket(i,q.RELIABLE)})}function ed(n){if(n.length===0)return new AbortController().signal;if(n.length===1)return n[0];for(const r of n)if(r.aborted)return r;const e=new AbortController,t=Array(n.length),i=()=>{for(const r of t)r()};return n.forEach((r,s)=>{const a=()=>{e.abort(r.reason),i()};r.addEventListener("abort",a),t[s]=()=>r.removeEventListener("abort",a)}),e.signal}function td(n){const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(n," ms"),"TimeoutError"))},n),e.signal}const se=1,it=2,Ua=4,Yp=8,Fa=0,Ba=12,qa=5,$p=7,Va=3,Xp=3,ja=2,Wa=1,Ha=0,Ka=3,Vi=2,Ga=2,Zp=1,em=0;var st;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(st||(st={}));class Se extends xe{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=st[t]}static tooShort(){return new Se("Too short to contain a valid header",st.TooShort)}static headerOverrun(){return new Se("Header exceeds total packet length",st.HeaderOverrun)}static missingExtWords(){return new Se("Extension word indicator is missing",st.MissingExtWords)}static unsupportedVersion(e){return new Se("Unsupported version ".concat(e),st.UnsupportedVersion)}static invalidHandle(e){return new Se("invalid track handle: ".concat(e.message),st.InvalidHandle,{cause:e})}static malformedExt(e){return new Se("Extension with tag ".concat(e," is malformed"),st.MalformedExt)}}var Ti;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(Ti||(Ti={}));class Oi extends xe{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=Ti[t]}static tooSmallForHeader(){return new Oi("Buffer cannot fit header",Ti.TooSmallForHeader)}static tooSmallForPayload(){return new Oi("Buffer cannot fit payload",Ti.TooSmallForPayload)}}class wn{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),r=this.toBinaryInto(i);if(e!==r)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(r," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}var oi;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(oi||(oi={}));class id extends wn{}class je extends id{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return se+se+je.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,je.tag),t+=se,e.setUint8(t,je.lengthBytes),t+=se,e.setBigUint64(t,this.timestamp),t+=Yp;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length
39was ").concat(i," bytes"));return t}toJSON(){return{tag:je.tag,lengthBytes:je.lengthBytes,timestamp:this.timestamp}}}je.tag=oi.UserTimestamp;je.lengthBytes=8;class We extends id{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return se+se+We.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,We.tag),t+=se,e.setUint8(t,We.lengthBytes),t+=se,e.setUint8(t,this.keyIndex),t+=se;for(let r=0;r<this.iv.length;r+=1)e.setUint8(t,this.iv[r]),t+=se;const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:We.tag,lengthBytes:We.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}We.tag=oi.E2ee;We.lengthBytes=13;class ii extends wn{constructor(){let e=arguments.length>0&&arguments[0]!==void 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){const r=this.e2ee.toBinaryInto(e);t+=r}if(this.userTimestamp){const r=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=r}const i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){const t=fs(e);let i,r,s=0;for(;t.byteLength-s>=se+se;){const a=t.getUint8(s);s+=se;const o=t.getUint8(s);if(s+=se,a!==em)switch(a){case oi.UserTimestamp:if(t.byteLength-s<je.lengthBytes)throw Se.malformedExt(a);i=new je(t.getBigUint64(s)),s+=o;break;case oi.E2ee:if(t.byteLength-s<We.lengthBytes)throw Se.malformedExt(a);const d=t.getUint8(s),c=new Uint8Array(12);for(let l=0;l<c.length;l+=1){let u=s;u+=se,u+=l*se,c[l]=t.getUint8(u)}r=new We(d,c),s+=o;break;default:if(t.byteLength-s<o)throw Se.malformedExt(a);s+=o;break}}return[new ii({userTimestamp:i,e2ee:r}),t.byteLength]}toJSON(){var e,t,i,r;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(r=(i=this.e2ee)===null||i===void 0?void 0:i.toJSON())!==null&&r!==void 0?r:null}}}const nd={from(n){return{payload:n.payload,extensions:new ii({userTimestamp:n.userTimestamp?new je(n.userTimestamp):void 0})}},lossyIntoFrame(n){var e;return{payload:n.payload,userTimestamp:(e=n.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},rd=Symbol.for("lk.track"),sd=Symbol.for("lk.data-track");class ad{constructor(e,t,i){this.trackSymbol=rd,this.isLocal=!1,this.typeSymbol=sd,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{const t=this.manager.openSubscriptionStream(this.info.sid,e==null?void 0:e.signal,e==null?void 0:e.bufferSize),i=N(t,2),r=i[0];return i[1].catch(()=>{}),r}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class Ni extends wn{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=(t=e.extensions)!==null&&t!==void 0?t:new ii}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((Vi+e)/4),i=t*4-Vi-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:i}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,i=e.paddingLengthBytes;let r=Ba;return t>0&&(r+=Vi+t+i),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Oi.tooSmallForHeader();let t=Fa<<qa,i;switch(this.marker){case ee.Inter:i=Ha;break;case ee.Final:i=Wa;break;case ee.Start:i=ja;break;case ee.Single:i=Ka;break}t|=i<<Va;const r=this.extensionsMetrics(),s=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;s>0&&(t|=1<<Ga);let d=0;if(e.setUint8(d,t),d+=se,e.setUint8(d,0),d+=se,e.setUint16(d,this.trackHandle),d+=it,e.setUint16(d,this.sequence.value),d+=it,e.setUint16(d,this.frameNumber.value),d+=it,e.setUint32(d,this.timestamp.asTicks()),d+=Ua,s>0){const l=a-1;e.setUint16(d,l),d+=it;const u=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+d));d+=u;for(let h=0;h<o;h+=1)e.setUint8(d,0),d+=se}const c=this.toBinaryLengthBytes();if(d!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(d," bytes but expected length
39was ").concat(c," bytes"));return c}static fromBinary(e){const t=fs(e);if(t.byteLength<Ba)throw Se.tooShort();let i=0;const r=t.getUint8(i);i+=se;const s=r>>qa&$p;if(s>Fa)throw Se.unsupportedVersion(s);let a;switch(r>>Va&Xp){case ja:a=ee.Start;break;case Wa:a=ee.Final;break;case Ka:a=ee.Single;break;case Ha:default:a=ee.Inter;break}const o=(r>>Ga&Zp)>0;i+=se;let d;try{d=Lh.fromNumber(t.getUint16(i))}catch(p){throw p instanceof ai&&(p.isReason(Ut.Reserved)||p.isReason(Ut.TooLarge))?Se.invalidHandle(p):p}i+=it;const c=Ke.u16(t.getUint16(i));i+=it;const l=Ke.u16(t.getUint16(i));i+=it;const u=ti.fromRtpTicks(t.getUint32(i));i+=Ua;let h=new ii;if(o){if(t.byteLength-i<it)throw Se.missingExtWords();let p=t.getUint16(i);i+=it;let g=4*(p+1)-Vi;if(i+g>t.byteLength)throw Se.headerOverrun();let k=new DataView(t.buffer,t.byteOffset+i,g);const T=ii.fromBinary(k),S=N(T,2),L=S[0],b=S[1];h=L,i+=b}return[new Ni({marker:a,trackHandle:d,sequence:c,frameNumber:l,timestamp:u,extensions:h}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var ee;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(ee||(ee={}));class Pn extends wn{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;const i=this.header.toBinaryInto(e);if(t+=i,e.byteLength-t<this.payload.byteLength)throw Oi.tooSmallForPayload();for(let s=0;s<this.payload.length;s+=1)e.setUint8(t,this.payload[s]),t+=se;const r=this.toBinaryLengthBytes();if(t!==r)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(r," bytes"));return r}static fromBinary(e){const t=fs(e),i=Ni.fromBinary(t),r=N(i,2),s=r[0],a=r[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new Pn(s,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const cr=ye(oe.DataTracks);class Ze extends xe{constructor(e,t,i,r){super(19,"Frame ".concat(i," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=Lt[t],this.frameNumber=i}static interrupted(e,t){return new Ze("Interrupted by the start of a new frame ".concat(t),Lt.Interrupted,e)}static unknownFrame(e){return new Ze("Initial packet was never received.",Lt.UnknownFrame,e)}static bufferFull(e){return new Ze("Reorder buffer is full.",Lt.BufferFull,e)}static incomplete(e,t,i){return new Ze("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),Lt.Incomplete,e)}}var Lt;(function(n){n[n.Interrupted=0]="Interrupted",n[n.UnknownFrame=1]="UnknownFrame",n[n.BufferFull=2]="BufferFull",n[n.Incomplete=3]="Incomplete"})(Lt||(Lt={}));class Rn{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case ee.Single:return this.frameFromSingle(e,t);case ee.Start:return this.beginPartial(e,t);case ee.Inter:case ee.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==ee.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const r=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;if(this.partials.size>=r){const s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no olde
39st frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t!=null&&t.throwOnInterruption)throw Ze.interrupted(s,e.header.frameNumber.value);cr.warn("Data track frame ".concat(s," 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!==ee.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const r=e.header.sequence,s=e.header.frameNumber.value,a={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},o=(i=t==null?void 0:t.maxPartialFrames)!==null&&i!==void 0?i:1;for(;this.partials.size>=o;){const d=this.peekOldestPartialFrameNumber();if(typeof d!="number")break;if(this.partials.delete(d),t!=null&&t.throwOnInterruption)throw Ze.interrupted(d,s);cr.warn("Data track partials full (max ".concat(o,"), evicted oldest frame ").concat(d," to make room for new frame ").concat(s,"."))}return this.partials.set(s,a),null}pushToPartial(e){if(e.header.marker!==ee.Inter&&e.header.marker!==ee.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),Ze.unknownFrame(t);if(i.payloads.size>=Rn.MAX_BUFFER_PACKETS)throw this.partials.delete(t),Ze.bufferFull(t);return i.payloads.has(e.header.sequence.value)&&cr.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===ee.Final?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){const r=t.payloads.size;let s=0;for(const c of t.payloads.values())s+=c.length;const a=new Uint8Array(s);let o=t.startSequence.clone(),d=0;for(;;){const c=t.payloads.get(o.value);if(!c)break;t.payloads.delete(o.value);const l=a.length-d;if(c.length>l)throw new Error("Depacketizer.finalize: Expected at least ".concat(c.length," more bytes left in the payload buffer, only got ").concat(l," bytes."));if(a.set(c,d),d+=c.length,o.value!=i){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),Ze.incomplete(e,r,i-t.startSequence.value+1)}}Rn.MAX_BUFFER_PACKETS=128;var xt;(function(n){n[n.Unpublished=0]="Unpublished",n[n.Timeout=1]="Timeout",n[n.Disconnected=2]="Disconnected",n[n.Cancelled=4]="Cancelled"})(xt||(xt={}));class Pe extends xe{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=xt[t]}static unpublished(){return new Pe("The track has been unpublished and is no longer available",xt.Unpublished)}static timeout(){return new Pe("Request to subscribe to data track timed-out",xt.Timeout)}static disconnected(){return new Pe("Cannot subscribe to data track when disconnected",xt.Disconnected)}static cancelled(){return new Pe("Subscription to data track cancelled by caller",xt.Cancelled)}}const dr=ye(oe.DataTracks);class tm{constructor(e){var t,i;const r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const s=new Rn;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(i=e.pipelineOptions)!==null&&i!==void 0?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return m(this,void 0,void 0,function*(){const t=this.depacketize(e);if(!t)return null;const 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(i){return dr.warn("Data frame depacketize error: ".concat(i)),null}return t}decryptIfNeeded(e){return m(this,void 0,void 0,function*(){var t,i;const r=this.e2eeManager;if(!r)return e;const s=(i=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&i!==void 0?i:null;if(!s)return dr.error("Missing E2EE meta"),null;let a;try{a=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(o){return dr.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}}const ce=ye(oe.DataTracks),im=1e4,nm=16;class rm extends Me.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const i=this.descriptors.get(e);if(!i){ce.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}i.pipelineOptions=t,i.subscription.type==="active"&&i.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:nm,r=null;const s=new be,a=this.descriptors.get(e),o=()=>{t==null||t.removeEventListener("abort",c)},d=()=>
39{if(o(),!r){ce.warn("ReadableStream subscribed to ".concat(e," was not started."));return}if(!a||this.descriptors.get(a.info.sid)!==a){ce.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(a.subscription.type!=="active"){ce.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}a.subscription.streamControllers.delete(r),a.subscription.streamControllers.size===0&&this.unSubscribeRequest(a.info.sid)},c=()=>{var u;r&&((a==null?void 0:a.subscription.type)==="active"&&a.subscription.streamControllers.delete(r),r.error(Pe.cancelled()),(u=s.reject)===null||u===void 0||u.call(s,Pe.cancelled()),d())};return[new ReadableStream({start:u=>{r=u,this.subscribeRequest(e,t).then(()=>m(this,void 0,void 0,function*(){var h,p,f;if(!a||this.descriptors.get(a.info.sid)!==a){ce.error("Unknown track ".concat(e));const g=Pe.disconnected();u.error(g),(h=s.reject)===null||h===void 0||h.call(s,g);return}if(a.subscription.type!=="active"){ce.error("Subscription for track ".concat(e," is not active"));const g=Pe.disconnected();u.error(g),(p=s.reject)===null||p===void 0||p.call(s,g);return}if(t!=null&&t.aborted){c();return}t==null||t.addEventListener("abort",c),a.subscription.streamControllers.set(u,o),(f=s.resolve)===null||f===void 0||f.call(s)})).catch(h=>{var p;u.error(h),(p=s.reject)===null||p===void 0||p.call(s,h)})},cancel:()=>{d()}},new CountQueuingStrategy({highWaterMark:i})),s.promise]}subscribeRequest(e,t){return m(this,void 0,void 0,function*(){const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");const r=(s,a,o)=>m(this,void 0,void 0,function*(){if(s.subscription.type==="active")return;if(s.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(s.subscription.type));const d=ed([a,o].filter(u=>typeof u<"u")),c=new be;s.subscription.completionFuture.promise.then(()=>{var u;return(u=c.resolve)===null||u===void 0?void 0:u.call(c)}).catch(u=>{var h;return(h=c.reject)===null||h===void 0?void 0:h.call(c,u)});const l=()=>{var u;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,o!=null&&o.aborted){s.subscription.cancel();return}if(s.subscription.pendingRequestCount<=0){s.subscription.cancel();return}(u=c.reject)===null||u===void 0||u.call(c,Pe.cancelled())}};d.aborted&&l(),d.addEventListener("abort",l),yield c.promise,d.removeEventListener("abort",l)});switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new be,pendingRequestCount:1,cancel:()=>{var a,o;const d=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:i.info.sid,subscribe:!1}),d.type==="pending"&&((o=(a=d.completionFuture).reject)===null||o===void 0||o.call(a,s.aborted?Pe.timeout():Pe.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const s=td(im);yield r(i,t,s);return}case"pending":{i.subscription.pendingRequestCount+=1,yield r(i,t);return}case"active":return}})}querySubscribed(){return m(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(t=>t.subscription.type==="active").map(t=>[t.info,t.publisherIdentity])})}unSubscribeRequest(e){var t;const i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");if(i.subscription.type!=="active"){ce.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=i.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(i.subscription.streamControllers,e);const r=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const r of e){var i=N(r,2);const s=i[0],a=i[1];a();try{s.close()}catch(o){ce.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return m(this,void 0,void 0,function*(){if(e.size===0)return;const t=new Map;for(const s of e.entries()){var i=N(s,2);const a=i[0],o=i[1],d=new Set;for(const c of o)d.add(c.sid),!this.descriptors.has(c.sid)&&(this.handleSidReassigned(a,c)||(yield this.handleTrackPublished(a,c)));t.set(a,d)}for(const s of t.entries()){var r=N(s,2);const a=r[0],o=r[1];let c=Array.from(this.descriptors.entries()).filter(l=>{let u=N(l,2);return u[0],u[1].publisherIdentity===a}).map(l=>N(l,1)[0]).filter(l=>!o.has(l));for(const l of c)this.handleTrackUnpublished(l)}})}queryPublications(){return m(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return m(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){ce.error("Existing descriptor for track ".concat(t.sid));return}let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);const r=new ad(i.info,this,{publisherIdentity:e});
39this.emit("trackPublished",{track:r})})}handleSidReassigned(e,t){const i=Array.from(this.descriptors.entries()).find(u=>{let h=N(u,2);h[0];let p=h[1];return p.publisherIdentity===e&&p.info.pubHandle===t.pubHandle});if(!i)return!1;const r=N(i,2),s=r[0],a=r[1],o=a.info,d=o.name,c=o.usesE2ee;if(d!==t.name||c!==t.usesE2ee)return ce.warn("Info mismatch for ".concat(s,", treating as new publication")),!1;const l=t.sid;if(ce.debug("SID reassigned: ".concat(s," -> ").concat(l)),!this.descriptors.delete(s))return!1;switch(a.info.sid=l,a.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:l,subscribe:!0});break}return a.subscription.type==="active"&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,l),this.descriptors.set(l,a),!0}handleTrackUnpublished(e){const t=this.descriptors.get(e);if(!t){ce.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(const i of e.entries()){var t=N(i,2);const r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var i,r;const s=this.descriptors.get(t);if(!s){ce.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{ce.warn("No subscription for ".concat(t));return}case"active":{this.subscriptionHandles.delete(s.subscription.subcriptionHandle),s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{ce.debug("data track subscription activated",{sid:t,handle:e});const a=new tm({info:s.info,publisherIdentity:s.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:s.pipelineOptions}),o=s.subscription;s.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}}}packetReceived(e){return m(this,void 0,void 0,function*(){let t;try{var i=Pn.fromBinary(e),r=N(i,1);t=r[0]}catch(d){ce.error("Failed to deserialize packet: ".concat(d));return}const s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){ce.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}const a=this.descriptors.get(s);if(!a){ce.error("Missing descriptor for track ".concat(s));return}if(a.subscription.type!=="active"){ce.warn("Received packet for track ".concat(s," without active subscription"));return}const o=yield a.subscription.pipeline.processPacket(t);if(o)for(const d of a.subscription.streamControllers.keys()){if(d.desiredSize!==null&&d.desiredSize<=0){ce.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(d.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const c=nd.lossyIntoFrame(o);d.enqueue(c)}})}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=N(t,2);const i=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:i,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,i;for(const r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case"none":break;case"pending":(i=(t=r.subscription.completionFuture).reject)===null||i===void 0||i.call(t,Pe.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;
39for(const i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),i.subscription.type==="pending"&&((t=(e=i.subscription.completionFuture).reject)===null||t===void 0||t.call(e,Pe.disconnected())),i.subscription.type==="active"&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class In extends xe{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=pn[t]}static mtuTooShort(){return new In("MTU is too short to send frame",pn.MtuTooShort)}}var pn;(function(n){n[n.MtuTooShort=0]="MtuTooShort"})(pn||(pn={}));class ks{constructor(e,t){this.sequence=Ke.u16(0),this.frameNumber=Ke.u16(0),this.clock=At.rtpStartingNow(ti.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?ee.Single:e===0?ee.Start:e===t-1?ee.Final:ee.Inter}*packetize(e,t){var i;const r=this.frameNumber.getThenIncrement(),s={marker:ee.Inter,trackHandle:this.handle,sequence:Ke.u16(0),frameNumber:r,timestamp:(i=t==null?void 0:t.now)!==null&&i!==void 0?i:this.clock.now(),extensions:e.extensions},a=new Ni(s).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw In.mtuTooShort();const o=this.mtuSizeBytes-a,d=Math.ceil(e.payload.byteLength/o);for(let l=0,u=0;u<e.payload.byteLength;c=[l+1,u+o],l=c[0],u=c[1],c){var c;const h=this.sequence.getThenIncrement(),p=new Ni(Object.assign(Object.assign({},s),{marker:ks.computeFrameMarker(l,d),sequence:h})),f=Math.min(o,e.payload.byteLength-u),g=new Uint8Array(e.payload.buffer,e.payload.byteOffset+u,f);yield new Pn(p,g)}}}var Fe;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.DuplicateName=1]="DuplicateName",n[n.Timeout=2]="Timeout",n[n.LimitReached=3]="LimitReached",n[n.Disconnected=4]="Disconnected",n[n.Cancelled=5]="Cancelled",n[n.InvalidName=6]="InvalidName",n[n.Unknown=7]="Unknown"})(Fe||(Fe={}));class ue extends xe{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=Fe[t],this.rawMessage=i==null?void 0:i.rawMessage}static notAllowed(e){return new ue("Data track publishing unauthorized",Fe.NotAllowed,{rawMessage:e})}static duplicateName(e){return new ue("Track name already taken",Fe.DuplicateName,{rawMessage:e})}static invalidName(e){return new ue("Track name is invalid",Fe.InvalidName,{rawMessage:e})}static timeout(){return new ue("Publish data track timed-out. Does the LiveKit server support data tracks?",Fe.Timeout)}static limitReached(e){return new ue("Data track publication limit reached",Fe.LimitReached,{rawMessage:e})}static unknown(e,t){return new ue("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),Fe.Unknown)}static disconnected(){return new ue("Room disconnected",Fe.Disconnected)}static cancelled(){return new ue("Publish data track cancelled by caller",Fe.Cancelled)}}var Si;(function(n){n[n.TrackUnpublished=0]="TrackUnpublished",n[n.Dropped=1]="Dropped"})(Si||(Si={}));class yt extends xe{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=Si[t]}static trackUnpublished(){return new yt("Track is no longer published",Si.TrackUnpublished)}static dropped(e){return new yt("Frame was dropped",Si.Dropped,{cause:e})}}var Ci;(function(n){n[n.Packetizer=0]="Packetizer",n[n.Encryption=1]="Encryption"})(Ci||(Ci={}));class Li extends xe{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=Ci[t]}static packetizer(e){return new Li("Error packetizing frame",Ci.Packetizer,{cause:e})}static encryption(e){return new Li("Error encrypting frame",Ci.Encryption,{cause:e})}}class Mn{constructor(e,t){this.trackSymbol=rd,this.isLocal=!0,this.typeSymbol=sd,this.handle=null,this.log=U,this.flushedFuture=new be,this.isFlushed=!0,this.handleManagerReset=()=>{var i,r;(r=(i=this.flushedFuture).resolve)===null||r===void 0||r.call(i),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=i=>{var r,s;this.isFlushed=i.isFlushed,i.isFlushed&&((s=(r=this.flushedFuture).resolve)===null||s===void 0||s.call(r),this.flushedFuture=new be)},this.options=e,this.manager=t,this.log=ye(oe.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){const r=new Mn(e,t);return r.handle=i,r}get info(){const e=this.descriptor;if((e==null?void 0:e.type)==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return m(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}})}isPublished(){var e;return((e=this.descriptor)===null||e===void 0?void 0:e.type)==="active"&&this.descriptor.publishState!=="unpublished"}tryPush(e){if(!this.handle)throw yt.trackUnpublished();const t=nd.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(i){throw i}}flush(){return m(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return m(this,void 0,void 0,function*(){if(!this.handle){U.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}}class Dn{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new ks(e.info.pubHandle,Dn.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return Ko(this,arguments,function*(){const i=yield ut(this.encryptIfNeeded(e));try{yield ut(yield*bu(Le(this.packetizer.packetize(i))))}catch(r){throw r instanceof In?Li.packetizer(r):r}})}encryptIfNeeded(e){return m(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(i){throw Li.encryption(i)}return e.payload=t.payload,e.extensions.e2ee=new We(t.keyIndex,t.iv),e})}}Dn.TRANSPORT_MTU_BYTES=16e3;const Oe=ye(oe.DataTracks),za={pending(){return{type:"pending",completionFuture:new be}},active(n,e){return{type:"active",info:n,publishState:"published",pipeline:new Dn({info:n,e2eeManager:e}),unpublishingFuture:new be}}},sm=1e4;class Ts extends Me.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new xh,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e==null?void 0:e.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){const t=new Ts;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}
39getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return m(this,void 0,void 0,function*(){var i,r,s,a,o;const d=this.getDescriptor(e);if((d==null?void 0:d.type)!=="active"||d.publishState==="unpublished")throw yt.trackUnpublished();if(d.publishState==="republishing")throw yt.dropped("Data track republishing");try{try{for(var c=!0,l=Le(d.pipeline.processFrame(t)),u;u=yield l.next(),i=u.done,!i;c=!0){a=u.value,c=!1;const h=a,p=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,p+1),p===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:h.toBinary()})}}catch(h){r={error:h}}finally{try{!c&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}}catch(h){throw yt.dropped(h)}})}handlePacketSendComplete(e){var t;let r=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;r<0&&(Oe.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),r=0),this.inFlightPacketCounter.set(e,r),r===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return m(this,void 0,void 0,function*(){const i=this.handleAllocator.get();if(!i)throw ue.limitReached();const r=td(sm),s=t?ed([t,r]):r;if(this.descriptors.has(i))throw new Error("Descriptor for handle already exists");const a=za.pending();this.descriptors.set(i,a);const o=()=>{var d,c;const l=this.descriptors.get(i);if(!l){Oe.warn("No descriptor for ".concat(i));return}this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),l.type==="pending"&&((c=(d=l.completionFuture).reject)===null||c===void 0||c.call(d,r.aborted?ue.timeout():ue.cancelled()))};return s.aborted?(o(),a.completionFuture.promise.then(()=>i)):(s.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,s.removeEventListener("abort",o),this.emit("trackPublished",{track:Mn.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return m(this,void 0,void 0,function*(){const t=this.descriptors.get(e);if(!t){Oe.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){Oe.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var i,r,s,a;const o=this.descriptors.get(e);if(!o){Oe.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){const d=t.data;Oe.debug("SFU accepted publish request for handle ".concat(e),{sid:d.sid});const c=d.usesE2ee?this.e2eeManager:null;this.descriptors.set(d.pubHandle,za.active(d,c)),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}else Oe.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),(a=(s=o.completionFuture).reject)===null||a===void 0||a.call(s,t.error);return}case"active":{if(o.publishState!=="republishing"){Oe.warn("Track ".concat(e," already active"));return}if(t.type==="error"){Oe.warn("Republish failed for track ".concat(e));return}Oe.debug("Track ".concat(e," republished")),o.info.sid=t.data.sid,o.publishState="published",this.descriptors.set(o.info.pubHandle,o)}}}receivedSfuUnpublishResponse(e){var t,i;const r=this.descriptors.get(e);if(!r){Oe.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){Oe.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(i=(t=r.unpublishingFuture).resolve)===null||i===void 0||i.call(t)}sfuWillRepublishTracks(){var e,t;for(const r of this.descriptors.entries()){var i=N(r,2);const s=i[0],a=i[1];switch(a.type){case"pending":this.descriptors.delete(s),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,ue.disconnected());break;
39case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return m(this,void 0,void 0,function*(){var e,t,i,r;this.handleAllocator.reset();for(const s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,ue.disconnected());break;case"active":(r=(i=s.unpublishingFuture).resolve)===null||r===void 0||r.call(i),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}}class G extends Error{constructor(e,t,i,r){super(t),this.code=e,this.message=Ja(t,G.MAX_MESSAGE_BYTES),this.data=i?Ja(i,G.MAX_DATA_BYTES):void 0,typeof(r==null?void 0:r.cause)<"u"&&(this.cause=r==null?void 0:r.cause)}static fromProto(e){return new G(e.code,e.message,e.data)}toProto(){return new Co({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new G(G.ErrorCode[e],G.ErrorMessage[e],t,i)}}G.MAX_MESSAGE_BYTES=256;G.MAX_DATA_BYTES=15360;G.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};G.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const od=15360,cd="lk.rpc_request",dd="lk.rpc_response";var ve;(function(n){n.RPC_REQUEST_ID="lk.rpc_request_id",n.RPC_REQUEST_METHOD="lk.rpc_request_method",n.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",n.RPC_REQUEST_VERSION="l
39k.rpc_request_version"})(ve||(ve={}));const am=1,ld=2;function Ss(n){return new TextEncoder().encode(n).length}function Ja(n,e){if(Ss(n)<=e)return n;let t=0,i=n.length;const r=new TextEncoder;for(;t<i;){const s=Math.floor((t+i+1)/2);r.encode(n.slice(0,s)).length<=e?t=s:i=s-1}return n.slice(0,t)}class om extends Me.EventEmitter{constructor(e,t,i,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=r}performRpc(e){return m(this,arguments,void 0,function(t){var i=this;let r=t.destinationIdentity,s=t.method,a=t.payload,o=t.responseTimeout,d=o===void 0?15e3:o;return(function*(){const u=i.getRemoteParticipantClientProtocol(r);if(Ss(a)>od&&u<Er)throw G.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const p=i.getServerVersion();if(p&&tt(p,"1.8.0")<0)throw G.builtIn("UNSUPPORTED_SERVER");const f=Math.max(d,8e3),g=crypto.randomUUID(),k=new be;let T=null;const S=setTimeout(()=>{var b;i.pendingAcks.delete(g),(b=k.reject)===null||b===void 0||b.call(k,G.builtIn("CONNECTION_TIMEOUT")),i.pendingResponses.delete(g),T!==null&&clearTimeout(T)},7e3);i.pendingAcks.set(g,{resolve:()=>{clearTimeout(S)},participantIdentity:r}),i.pendingResponses.set(g,{completionFuture:k,participantIdentity:r}),yield i.publishRpcRequest(r,g,s,a,f,u),T=setTimeout(()=>{var b;i.pendingResponses.delete(g),(b=k.reject)===null||b===void 0||b.call(k,G.builtIn("RESPONSE_TIMEOUT"))},d);const L=k.promise.finally(()=>{clearTimeout(T),i.pendingAcks.has(g)&&(i.log.warn("RPC response received before ack",g),i.pendingAcks.delete(g),clearTimeout(S))});return[g,L]})()})}publishRpcRequest(e,t,i,r,s,a){return m(this,void 0,void 0,function*(){if(a>=Er){yield this.outgoingDataStreamManager.sendText(r,{topic:cd,destinationIdentities:[e],attributes:{[ve.RPC_REQUEST_ID]:t,[ve.RPC_REQUEST_METHOD]:i,[ve.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(s),[ve.RPC_REQUEST_VERSION]:"".concat(ld)}});return}this.emit("sendDataPacket",{packet:new Ce({destinationIdentities:[e],kind:Tt.RELIABLE,value:{case:"rpcRequest",value:new Gr({id:t,method:i,payload:r,responseTimeoutMs:s,version:am})}})})})}handleIncomingDataStream(e,t,i){return m(this,void 0,void 0,function*(){const r=i[ve.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(ve.RPC_REQUEST_ID," not set."));return}const s=this.pendingResponses.get(r);if(s&&s.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(s.participantIdentity,". Ignoring."));return}let a;try{a=yield e.readAll()}catch(o){this.log.warn("Error reading RPC response payload: ".concat(o)),this.handleIncomingRpcResponseFailure(r,G.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:o}));return}this.handleIncomingRpcResponseSuccess(r,a)})}handleIncomingRpcResponseSuccess(e,t){var i,r;const s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).resolve)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,r;const s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).reject)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const 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(const a of this.pendingAcks){var i=N(a,2);const o=i[0];i[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(const a of this.pendingResponses){var r=N(a,2);const o=r[0];var s=r[1];const d=s.participantIdentity,c=s.completionFuture;d===e&&((t=c.reject)===null||t===void 0||t.call(c,G.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(o))}}}class cm extends Me.EventEmitter{constructor(e,t,i){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i}
39registerRpcMethod(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 m(this,void 0,void 0,function*(){var i;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,G.builtIn("UNSUPPORTED_VERSION"));return}const r=this.rpcHandlers.get(t.method);if(!r){this.publishRpcResponsePacket(e,t.id,null,G.builtIn("UNSUPPORTED_METHOD"));return}let s;try{s=yield r({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(a){let o;a instanceof G?o=a:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),a),o=G.builtIn("APPLICATION_ERROR","Uncaught error: ".concat((i=a==null?void 0:a.message)!==null&&i!==void 0?i:a),{cause:a})),this.publishRpcResponsePacket(e,t.id,null,o);return}yield this.publishRpcResponse(e,t.id,s??"")})}handleIncomingDataStream(e,t,i){return m(this,void 0,void 0,function*(){const r=i[ve.RPC_REQUEST_ID],s=i[ve.RPC_REQUEST_METHOD],a=parseInt(i[ve.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(i[ve.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(ve.RPC_REQUEST_ID," / ").concat(ve.RPC_REQUEST_METHOD," / ").concat(ve.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(ve.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,r,null,G.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,r),o!==ld){this.publishRpcResponsePacket(t,r,null,G.builtIn("UNSUPPORTED_VERSION"));return}let d;try{d=yield e.readAll()}catch(u){this.log.warn("Error reading RPC request payload: ".concat(u)),this.publishRpcResponsePacket(t,r,null,G.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:u}));return}const c=this.rpcHandlers.get(s);if(!c){this.publishRpcResponsePacket(t,r,null,G.builtIn("UNSUPPORTED_METHOD"));return}let l;try{l=yield c({requestId:r,callerIdentity:t,payload:d,responseTimeout:a})}catch(u){let h;u instanceof G?h=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),u),h=G.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,r,null,h);return}yield this.publishRpcResponse(t,r,l??"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Ce({destinationIdentities:[e],kind:Tt.RELIABLE,value:{case:"rpcAck",value:new bn({requestId:t})}})})}publishRpcResponsePacket(e,t,i,r){this.emit("sendDataPacket",{packet:new Ce({destinationIdentities:[e],kind:Tt.RELIABLE,value:{case:"rpcResponse",value:new zr({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}})})}publishRpcResponse(e,t,i){return m(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=Er){yield this.outgoingDataStreamManager.sendText(i,{topic:dd,destinationIdentities:[e],attributes:{[ve.RPC_REQUEST_ID]:t}});return}if(Ss(i)>od){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,G.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,i,null)})}}class ud extends Uc{constructor(e,t,i,r,s,a){super(e,t,E.Kind.Audio,i,a),this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=_n(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;ze()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(ze())return 1;let e=0;
vendor: 4,402 bytes, line 39
39return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Dr(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Dr(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,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(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(R.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(R.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}class at extends Me.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=H.NONE,this.log=U,this.handleMuted=()=>{this.emit(R.Muted)},this.handleUnmuted=()=>{this.emit(R.Unmuted)},this.log=ye((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:oe.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=E.Source.Unknown}setTrack(e){this.track&&(this.track.off(R.Muted,this.handleMuted),this.track.off(R.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(R.Muted,this.handleMuted),e.on(R.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),V(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==H.NONE}get audioTrack(){if(et(this.track))return this.track}get videoTrack(){if(ht(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=E.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===E.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(at||(at={}));class Fr extends at{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>
39{this.emit(R.Ended)},this.handleCpuConstrained=()=>{this.track&&ht(this.track)&&this.emit(R.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(R.Ended,this.handleTrackEnded),this.track.off(R.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(R.Ended,this.handleTrackEnded),e.on(R.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 m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(et(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(pe.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(pe.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(pe.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(pe.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(pe.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(pe.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function An(n,e){return m(this,void 0,void 0,function*(){n??(n={});let t=!1;const i=Mc(n),r=i.audioProcessor,s=i.videoProcessor,a=i.optionsWithoutProcessor;let o=a.audio,d=a.video;if(r&&typeof a.audio=="object"&&(a.audio.processor=r),s&&typeof a.video=="object"&&(a.video.processor=s),n.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const h=a.audio.deviceId;a.audio.deviceId={exact:h},t=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:h}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const h=a.video.deviceId;a.video.deviceId={exact:h},t=!0,d=Object.assign(Object.assign({},a.video),{deviceId:{ideal:h}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const c=Rc(a,qc,Vc),l=os(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(me.userMediaPromiseMap.set("audioinput",u),u.catch(()=>me.userMediaPromiseMap.delete("audioinput"))),a.video&&(me.userMediaPromiseMap.set("videoinput",u),u.catch(()=>me.userMediaPromiseMap.delete("videoinput")));try{const h=yield u;return yield Promise.all(h.getTracks().map(p=>m(this,void 0,void 0,function*(){const f=p.kind==="audio";let g;const k=f?l.audio:l.video;typeof k!="boolean"&&(g=k);const T=p.getSettings().deviceId;g!=null&&g.deviceId&&Xt(g.deviceId)!==T?g.deviceId=T:g||(g={deviceId:T});const S=Tp(p,g,e);return S.kind===E.Kind.Video?S.source=E.Source.Camera:S.kind===E.Kind.Audio&&(S.source=E.Source.Microphone),S.mediaStream=h,et(S)&&r?yield S.setProcessor(r):ht(S)&&s&&(yield S.setProcessor(s)),S})))}catch(h){if(!t)throw h;return An(Object.assign(Object.assign({},n),{audio:o,video:d}),e)}})}function dm(n){return m(this,void 0,void 0,function*(){return(yield An({audio:!1,video:!0}))[0]})}function lm(n){return m(this,void 0,void 0,function*(){return(yield An({audio:!0,video:!1}
39))[0]})}var gt;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(gt||(gt={}));function um(n){switch(n){case Ht.EXCELLENT:return gt.Excellent;case Ht.GOOD:return gt.Good;case Ht.POOR:return gt.Poor;case Ht.LOST:return gt.Lost;default:return gt.Unknown}}class hd extends Me.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?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((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===_i.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===zt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:_i.STANDARD;var d;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=gt.Unknown,this.log=U,this.loggerOptions=a,this.log=ye((d=a==null?void 0:a.loggerName)!==null&&d!==void 0?d:oe.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const i of this.trackPublications){var t=N(i,2);const r=t[1];if(r.source===e)return r}}getTrackPublicationByName(e){for(const i of this.trackPublications){var t=N(i,2);const r=t[1];if(r.trackName===e)return r}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new be,this.once(M.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(E.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(E.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(E.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===zt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==zt.ACTIVE&&this.emit(M.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(M.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(M.ParticipantNameChanged,e)}_setAttributes(e){const t=Hu(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(M.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const d=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);
39return this.permissions=e,c&&this.emit(M.ParticipantPermissionsChanged,d),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(M.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=um(e),t!==this._connectionQuality&&this.emit(M.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>et(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){this.log.debug("adding track publication",{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(R.Muted,()=>{this.emit(M.TrackMuted,e)}),e.on(R.Unmuted,()=>{this.emit(M.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case E.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case E.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function hm(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Bo({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class pm extends hd{constructor(e,t,i,r,s,a,o,d){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=H.NONE,this.e2eeStateMutex=new fe,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new be)},this.handleReconnected=()=>{var c,l;(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.resolve)===null||l===void 0||l.call(c),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var c,l,u,h,p,f;this.reconnectFuture&&(this.reconnectFuture.promise.catch(g=>this.log.warn(g.message)),(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.reject)===null||l===void 0||l.call(c,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((h=(u=this.signalConnectedFuture).reject)===null||h===void 0||h.call(u,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(f=(p=this.activeAgentFuture)===null||p===void 0?void 0:p.reject)===null||f===void 0||f.call(p,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=c=>{var l,u;c.participant&&this.updateInfo(c.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new be),(u=(l=this.signalConnectedFuture).resolve)===null||u===void 0||u.call(l)},this.handleSignalRequestResponse=c=>{const l=c.requestId,u=c.reason,h=c.message,p=this.pendingSignalRequests.get(l);switch(p&&(u!==Mt.OK&&p.reject(new Zs(h,u)),this.pendingSignalRequests.delete(l)),c.request.case){case"publishDataTrack":{let f;switch(c.reason){case Mt.NOT_ALLOWED:f=ue.notAllowed(c.message);break;case Mt.DUPLICATE_NAME:f=ue.duplicateName(c.message);break;case Mt.INVALID_NAME:f=ue.invalidName(c.message);break;case Mt.LIMIT_EXCEEDED:f=ue.limitReached(c.message);break;default:f=ue.unknown(c.reason,c.message);break}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(c.request.value.pubHandle,{type:"error",error:f});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(c=>hm(c)))},this.onTrackUnmuted=c=>{this.onTrackMuted(c,c.isUpstreamPaused)},this.onTrackMuted=(c,l)=>{if(l===void 0&&(l=!0),!c.sid){this.log.error("could not update mute status for unpublished track",V(c));return}this.engine.updateMuteStatus(c.sid,l)},this.onTrackUpstreamPaused=c=>{this.log.debug("upstream paused",V(c)),this.onTrackMuted(c,!0)},this.onTrackUpstreamResumed=c=>{this.log.debug("upstream resumed",V(c)),this.onTrackMuted(c,c.isMuted)},this.onTrackFeatureUpdate=c=>{const l=this.audioTrackPublications.get(c.sid);if(!l){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(c.sid));return}this.engine.client.sendUpdateLocalAudioTrack(l.trackSid,l.getTrackFeatures())},this.onTrackCpuConstrained=(c,l)=>
39{this.log.debug("track cpu constrained",V(l)),this.emit(M.LocalTrackCpuConstrained,c,l)},this.handleSubscribedQualityUpdate=c=>m(this,void 0,void 0,function*(){var l,u,h,p,f;if(!(!((f=this.roomOptions)===null||f===void 0)&&f.dynacast))return;const g=this.videoTrackPublications.get(c.trackSid);if(!g){this.log.warn("received subscribed quality update for unknown track",{trackSid:c.trackSid});return}if(!g.videoTrack)return;const k=yield g.videoTrack.setPublishingCodecs(c.subscribedCodecs);try{for(var T=!0,S=Le(k),L;L=yield S.next(),l=L.done,!l;T=!0){p=L.value,T=!1;const b=p;Bu(b)&&(this.log.debug("publish ".concat(b," for ").concat(g.videoTrack.sid),V(g)),yield this.publishAdditionalCodecForTrack(g.videoTrack,b,g.options))}}catch(b){u={error:b}}finally{try{!T&&!l&&(h=S.return)&&(yield h.call(S))}finally{if(u)throw u.error}}}),this.handleLocalTrackUnpublished=c=>{const l=this.trackPublications.get(c.trackSid);if(!l){this.log.warn("received unpublished event for unknown track",{trackSid:c.trackSid});return}this.unpublishTrack(l.track)},this.handleTrackEnded=c=>m(this,void 0,void 0,function*(){if(c.source===E.Source.ScreenShare||c.source===E.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",V(c)),this.unpublishTrack(c);else if(c.isUserProvided)yield c.mute();else if(rt(c)||Qe(c))try{if(Ie())try{const l=yield navigator==null?void 0:navigator.permissions.query({name:c.source===E.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(c.source),V(c)),l.onchange=()=>{l.state!=="denied"&&(c.isMuted||c.restartTrack(),l.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}c.isMuted||(this.log.debug("track ended, attempting to use a different device",V(c)),rt(c)?yield c.restartTrack({deviceId:"default"}):yield c.restartTrack())}catch{this.log.warn("could not restart track, muting instead",V(c)),yield c.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=s,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=d}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==H.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(P.RemoteMute,(i,r)=>{const s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(P.Connected,this.handleReconnected).on(P.SignalConnected,this.handleSignalConnected).on(P.SignalRestarted,this.handleReconnected).on(P.SignalResumed,this.handleReconnected).on(P.Restarting,this.handleReconnecting).on(P.Resuming,this.handleReconnecting).on(P.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(P.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(P.Closing,this.handleClosing).on(P.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var i=this;let r=t.metadata,s=t.name,a=t.attributes;return(function*(){return new Ee((o,d)=>m(i,void 0,void 0,function*(){var c,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((c=r??this.metadata)!==null&&c!==void 0?c:"",(l=s??this.name)!==null&&l!==void 0?l:"",a),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:f=>{d(f),u=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-p<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(f=>{let g=N(f,2),k=g[0],T=g[1];return this.attributes[k]===T||T===""&&!this.attributes[k]}))){this.pendingSignalRequests.delete(h),o();return}yield Te(50)}d(new Zs("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?d(u):d(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(E.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(E.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(E.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?H.GCM:H.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(i=>i.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,i,r){return m(this,void 0,void 0,function*(){var s,a;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let u;if(this.pendingPublishing.has(e)){const h=yield this.waitForPendingPublicationOfSource(e);return h||this.log.info("waiting for pending publication promise timed out",{source:e}),yield h==null?void 0:h.unmute(),h}this.pendingPublishing.add(e);try{switch(e){case E.Source.Camera:u=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case E.Source.Microphone:u=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case E.Source.ScreenShare:u=yield this.createScreenTracks(Object.assign({},i));break;default:throw new dt(e)}}catch(h){throw u==null||u.forEach(p=>{p.stop()}
39),h instanceof Error&&this.emit(M.MediaDevicesError,h,Rr(e)),this.pendingPublishing.delete(e),h}for(const h of u){const p=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===E.Source.Microphone&&et(h)&&p.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),h.startPreConnectBuffer())}try{const h=[];for(const f of u)this.log.info("publishing track",V(f)),h.push(this.publishTrack(f,r));const p=yield Promise.all(h);var d=N(p,1);o=d[0]}catch(h){throw u==null||u.forEach(p=>{p.stop()}),h}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",{source:e})),o&&o.track)if(e===E.Source.ScreenShare){const u=[this.unpublishTrack(o.track)],h=this.getTrackPublication(E.Source.ScreenShareAudio);h&&h.track&&u.push(this.unpublishTrack(h.track));var c=yield Promise.all(u),l=N(c,1);o=l[0]}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(E.Source.Camera)||this.pendingPublishing.has(E.Source.Microphone))){this.pendingPublishing.add(E.Source.Camera),this.pendingPublishing.add(E.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(E.Source.Camera),this.pendingPublishing.delete(E.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,i;e??(e={});const r=Rc(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield An(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(et(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=E.Source.Microphone,this.emit(M.AudioStreamAcquired)),ht(o)&&(this.cameraError=void 0,o.source=E.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new ss("getDisplayMedia not supported");e.resolution===void 0&&!eh()&&(e.resolution=as.h1080fps30.resolution);const t=Vu(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new dt("no video track found");const s=new un(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=E.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(M.AudioStreamAcquired);const o=new dn(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=E.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,i)=>{const r=()=>{clearTimeout(o),this.engine.off(P.Restarted,s),this.engine.off(P.Closing,a)},s=()=>{r(),t()},a=()=>{r(),i(new Error("engine closed before restart completed"))},o=setTimeout(()=>{r(),i(new Error("timed out waiting for engine restart"))},e);this.engine.once(P.Restarted,s),this.engine.once(P.Closing,a)})}publishOrRepublishTrack(e,t){return m(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;return(function*(){var d,c,l,u;rt(i)&&i.setAudioContext(s.audioContext),yield(d=s.reconnectFuture)===null||d===void 0?void 0:d.promise,s.republishPromise&&!a&&(yield s.republishPromise),Zt(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let h;if(i instanceof MediaStreamTrack)h=i.getConstraints();else{h=i.constraints;let S;switch(i.source){case E.Source.Microphone:S="audioinput";break;case E.Source.Camera:S="videoinput"}S&&s.activeDeviceMap.has(S)&&(h=Object.assign(Object.assign({},h),{deviceId:s.activeDeviceMap.get(S)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new dn(i,h,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new un(i,h,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new dt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let p;if(s.trackPublications.forEach(S=>{S.track&&S.track===i&&(p=S)}),p)return s.log.warn("track has already been published, skipping",V(p)),p;const f=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r),g="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,k=(c=f.forceStereo)!==null&&c!==void 0?c:g;k&&(f.dtx===void 0&&s.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",V(i)),f.red===void 0&&s.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=f.dtx)!==null&&l!==void 0||(f.dtx=!1),(u=f.red)!==null&&u!==void 0||(f.red=!1)),!ih()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),f.simulcast=!1),f.source&&(i.source=f.source);const T=new Promise((S,L)=>m(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==J.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:V(i)});let b=!1;const y=setTimeout(()=>{b=!0,i.stop(),L(new Xs("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(y),b)return;const C=yield this.publish(i,f,k);S(C)}else try{const b=yield this.publish(i,f,k);S(b)}catch(b){L(b)}}catch(b){L(b)}}
39));s.pendingPublishPromises.set(i,T);try{return yield T}catch(S){if(!o&&S instanceof St)return s.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:S}),s.pendingPublishPromises.delete(i),yield s.waitForNextEngineRestart(),yield s.publishOrRepublishTrack(i,r,a,!0);throw S}finally{s.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new be),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",V(e)),!1;const t=this.permissions,i=t.canPublish,r=t.canPublishSources;return i&&(r.length===0||r.map(s=>Ku(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",V(e)),!1)}publish(e,t,i){return m(this,void 0,void 0,function*(){var r,s,a,o,d,c,l,u,h,p;if(!this.hasPermissionsToPublish(e))throw new Xs("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(D=>Zt(e)&&D.source===e.source)&&e.source!==E.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),V(e)),t.stopMicTrackOnMute&&et(e)&&(e.stopOnMute=!0),e.source===E.Source.ScreenShare&&Bt()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Qu()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Yu()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Lr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(D=>t.videoCodec===bi(D.mime))||(t.videoCodec=bi(this.enabledPublishVideoCodecs[0].mime)));const g=t.videoCodec;e.on(R.Muted,this.onTrackMuted),e.on(R.Unmuted,this.onTrackUnmuted),e.on(R.Ended,this.handleTrackEnded),e.on(R.UpstreamPaused,this.onTrackUpstreamPaused),e.on(R.UpstreamResumed,this.onTrackUpstreamResumed),e.on(R.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const k=[],T=!(!((r=t.dtx)!==null&&r!==void 0)||r),S=e.getSourceTrackSettings();S.autoGainControl&&k.push(pe.TF_AUTO_GAIN_CONTROL),S.echoCancellation&&k.push(pe.TF_ECHO_CANCELLATION),S.noiseSuppression&&k.push(pe.TF_NOISE_SUPPRESSION),S.channelCount&&S.channelCount>1&&k.push(pe.TF_STEREO),T&&k.push(pe.TF_NO_DTX),rt(e)&&e.hasPreConnectBuffer&&k.push(pe.TF_PRECONNECT_BUFFER);const L=this.normalizeRequestedFrameMetadataOptions(e,t),b=new Pi({cid:e.mediaStreamTrack.id,name:t.name,type:E.kindToProto(e.kind),muted:e.isMuted,source:E.sourceToProto(e.source),disableDtx:T,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:k,packetTrailerFeatures:L});let y;if(e.kind===E.Kind.Video){let D;try{D=yield e.waitForDimensions()}catch{const F=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:Ri.h720.resolution;D={width:F.width,height:F.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},V(e)),{dims:D}))}b.width=D.width,b.height=D.height,Qe(e)&&(Xe(g)&&(e.source===E.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",V(e)))),t.scalabilityMode=(d=t.scalabilityMode)!==null&&d!==void 0?d:"L3T3_KEY"),b.simulcastCodecs=[new mr({codec:g,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Lr}),t.backupCodec&&g!==t.backupCodec.codec&&b.encryption===H.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),b.simulcastCodecs.push(new mr({codec:t.backupCodec.codec,cid:""})))),y=ln(e.source===E.Source.ScreenShare,b.width,b.height,t),b.layers=Ma(b.width,b.height,y,Xe(t.videoCodec))}else e.kind===E.Kind.Audio&&(y=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(p=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new Z("cannot publish track when not connected");const C=()=>m(this,void 0,void 0,function*(){var D,O,F,X;if(!this.engine.pcManager)throw new Z("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),Qe(e)&&(e.publishOptions=t),this.emit
39(M.LocalSenderCreated,e.sender,e),Qe(e)&&((D=t.degradationPreference)!==null&&D!==void 0||(t.degradationPreference=Mp(e)),e.setDegradationPreference(t.degradationPreference)),y){if(Bt()&&e.kind===E.Kind.Audio){let ie;for(const ge of this.engine.pcManager.publisher.getTransceivers())if(ge.sender===e.sender){ie=ge;break}ie&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:ie,codec:"opus",maxbr:!((O=y[0])===null||O===void 0)&&O.maxBitrate?y[0].maxBitrate/1e3:0})}else if(e.codec&&Lc(e.codec)){const ie=Xe(e.codec)?(X=(F=y[0])===null||F===void 0?void 0:F.maxBitrate)!==null&&X!==void 0?X:0:y.reduce((ge,Je)=>{var mt;return ge+((mt=Je.maxBitrate)!==null&&mt!==void 0?mt:0)},0);ie>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:b.cid,codec:e.codec,maxbr:ie/1e3,isScreenShare:e.source===E.Source.ScreenShare})}}yield this.engine.negotiate()});let I;const A=new Promise((D,O)=>m(this,void 0,void 0,function*(){var F;try{I=yield this.engine.addTrack(b),D(I)}catch(X){if(e.sender&&(!((F=this.engine.pcManager)===null||F===void 0)&&F.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(ie){this.log.error(ie)}yield this.engine.negotiate().catch(ie=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},V(e)),{error:ie}))})}O(X)}}));if(this.enabledPublishVideoCodecs.length>0&&L.length===0)I=(yield Promise.all([A,C()]))[0];else{I=yield A;let D;if(I.codecs.forEach(O=>{D===void 0&&(D=O.mimeType)}),D&&e.kind===E.Kind.Video){const O=bi(D);O!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},V(e)),{codec:O})),t.videoCodec=O,y=ln(e.source===E.Source.ScreenShare,b.width,b.height,t))}yield C()}const B=new Fr(e.kind,I,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(B.on(R.CpuConstrained,D=>this.onTrackCpuConstrained(D,B)),B.options=t,e.sid=I.sid,Qe(e)&&(e.publishOptions=t,b.width&&b.height&&(e.lastEncodedDimensions={width:b.width,height:b.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:y,trackInfo:I}),Qe(e)?e.startMonitor(this.engine.client):rt(e)&&e.startMonitor(),this.addTrackPublication(B),this.emit(M.LocalTrackPublished,B),rt(e)&&I.audioFeatures.includes(pe.TF_PRECONNECT_BUFFER)){const D=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(M.LocalTrackSubscribed,F=>{if(F.trackSid===I.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",V(e)),e.stopPreConnectBuffer()}}),D&&new Promise((X,ie)=>m(this,void 0,void 0,function*(){var ge,Je,mt,he,Rt,On;try{this.log.debug("waiting for agent",V(e));const Un=setTimeout(()=>{ie(new Error("agent not active within 10 seconds"))},1e4),md=yield this.waitUntilActiveAgentPresent();clearTimeout(Un),this.log.debug("sending preconnect buffer",V(e));const Cs=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[md.identity],attributes:{trackId:B.trackSid,sampleRate:String((Rt=S.sampleRate)!==null&&Rt!==void 0?Rt:"48000"),channels:String((On=S.channelCount)!==null&&On!==void 0?On:"1")}});try{for(var Nn=!0,Ln=Le(D),xn;xn=yield Ln.next(),ge=xn.done,!ge;Nn=!0){he=xn.value,Nn=!1;const Fn=he;yield Cs.write(Fn)}}catch(Fn){Je={error:Fn}}finally{try{!Nn&&!ge&&(mt=Ln.return)&&(yield mt.call(Ln))}finally{if(Je)throw Je.error}}yield Cs.close(),X()}catch(Un){ie(Un)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",V(e))}).catch(X=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},V(e)),{error:X}))})}return B})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||Ai((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var i;const r=(i=t.frameMetadata)!==null&&i!==void 0?i:t.packetTrailer;if(e.kind!==E.Kind.Video||!on(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),V(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const s=wh(r),a=Ph(s);return t.frameMetadata=a,t.packetTrailer=a,s}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return m(this,void 0,void 0,function*(){var r;if(this.encryptionType!==H.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new dt("track is not published");if(!Qe(e))throw new dt("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),o=Hc(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",V(e));return}const d=e.addSimulcastTrack(t,o);if(!d)return;const c=this.normalizeRequestedFrameMetadataOptions(e,a),l=new Pi({cid:d.mediaStreamTrack.id,type:E.kindToProto(e.kind),muted:e.isMuted,source:E.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:d.mediaStreamTrack.id}]});if(l.layers=Ma(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Z("cannot publish track when not connected");const u=()=>m(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,d,a,o),yield this.engine.negotiate()}),p=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:p})})}unpublishTrack(e,t){return m(this,void 0,void 0,function*(){var i,r;if(Zt(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.debug("awaiting publish promise before attempting to unpublish",V(e)),yield l)}const s=this.getPublicationForTrack(e),a=s?V(s):void 0;if(this.log.info("unpublishing track",a),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",a);return}e=s.track,e.off(R.Muted,this.onTrackMuted),e.off(R.Unmuted,this.onTrackUnmuted),e.off(R.Ended,this.handleTrackEnded),e.off(R.UpstreamPaused,this.onTrackUpstreamPaused),e.off(R.UpstreamResumed,this.onTrackUpstreamResumed),e.off(R.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const d=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<$.FAILED&&d)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===d&&(l.direction="inactive",o=!0);try{o=this.engine.removeTrack(d)}catch(l){this.log.warn(l),o=!0}
39if(Qe(e)){for(const l of e.simulcastCodecs){var c=N(l,2);const u=c[1];if(u.sender){try{o=this.engine.removeTrack(u.sender)}catch(h){this.log.warn(h),o=!0}u.sender=void 0}}e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case E.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case E.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(M.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Ee((s,a)=>m(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(d=>{d.track&&(t&&(d.options=Object.assign(Object.assign({},d.options),t)),o.push(d))}),yield Promise.all(o.map(d=>m(this,void 0,void 0,function*(){const c=d.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==E.Source.ScreenShare&&c.source!==E.Source.ScreenShareAudio&&(rt(c)||Qe(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",{track:d.trackSid}),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,d.options,!0)}))),s()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return m(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const s=r.reliable?q.RELIABLE:q.LOSSY,a=r.reliable?Tt.RELIABLE:Tt.LOSSY,o=r.destinationIdentities,d=r.topic;let c=new Kr({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:d});const l=new Ce({kind:a,value:{case:"user",value:c}});yield i.engine.sendDataPacket(l,s)})()})}publishDtmf(e,t){return m(this,void 0,void 0,function*(){const i=new Ce({kind:Tt.RELIABLE,value:{case:"sipDtmf",value:new So({code:e,digit:t})}});yield this.engine.sendDataPacket(i,q.RELIABLE)})}sendChatMessage(e,t){return m(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},r=new Ce({value:{case:"chatMessage",value:new sn(Object.assign(Object.assign({},i),{timestamp:te.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,q.RELIABLE),this.emit(M.ChatMessage,i),i})}editChatMessage(e,t){return m(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Ce({value:{case:"chatMessage",value:new sn(Object.assign(Object.assign({},i),{timestamp:te.parse(i.timestamp),editTimestamp:te.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,q.RELIABLE),this.emit(M.ChatMessage,i),i})}sendText(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}sendBytes(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)})}streamBytes(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let i=N(t,2);return i[0],i[1]})}
39registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},V(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new be),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(rt(r)||Qe(r))&&r.mediaStreamTrack===e&&(t=i):e===r&&(t=i))}),t}waitForPendingPublicationOfSource(e){return m(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>N(s,1)[0].source===e);if(r)return r[1];yield Te(20)}})}publishDataTrack(e){return m(this,void 0,void 0,function*(){const t=new Mn(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class Qa extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class mm extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,r;super.set(e,t);const s=(i=this.pending)===null||i===void 0?void 0:i.get(e);if(s){for(const a of s)a.isResolved||(r=a.resolve)===null||r===void 0||r.call(a,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return m(this,void 0,void 0,function*(){const i=this.get(e);if(typeof i<"u")return i;if(t!=null&&t.aborted)throw new Qa("The operation was aborted.",t.reason);const r=new be(void 0,()=>{const a=this.pending.get(e);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.pending.delete(e)}),s=this.pending.get(e);if(s?s.push(r):this.pending.set(e,[r]),t){const a=()=>{var o;r.isResolved||(o=r.reject)===null||o===void 0||o.call(r,new Qa("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0}),r.promise.finally(()=>{t.removeEventListener("abort",a)})}return r.promise})}}class fm extends at{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(R.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Sn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Eo({participantSid:"",trackSids:[this.trackSid]})]});this.emit(R.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?at.SubscriptionStatus.Unsubscribed:super.isSubscribed?at.SubscriptionStatus.Subscribed:at.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?at.PermissionStatus.Allowed:at.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Qn(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Qn(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Ae.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(R.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(R.VisibilityChanged,this.handleVisibilityChange),r.off(R.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit
39(R.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(R.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(R.VisibilityChanged,this.handleVisibilityChange),e.on(R.Ended,this.handleEnded),this.emit(R.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(R.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?R.Muted:R.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(R.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(R.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Qn(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Lo({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===E.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)ta(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Gu(this.trackInfo,this.requestedMaxQuality);i&&ta(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(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:Ae.HIGH})),e.quality=Ae.HIGH)}this.emit(R.UpdateSettings,e)}}class mn extends hd{static fromParticipantInfo(e,t,i,r){return new mn(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,t.dataTracks.map(s=>{const a=cn.from(s);return new ad(a,r,{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,r,s,a,o){let d=arguments.length>7&&arguments[7]!==void 0?arguments[7]:_i.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:_c,u=arguments.length>10&&arguments[10]!==void 0?arguments[10]:[];super(t,i||"",r,s,a,o,d),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new mm(c.map(h=>[h.info.name,h])),this.volumeMap=new Map,this.clientProtocol=l,this.capabilities=u}addTrackPublication(e){super.addTrackPublication(e),e.on(R.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(R.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(R.SubscriptionPermissionChanged,t=>{this.emit(M.TrackSubscriptionPermissionChanged,e,t)}),e.on(R.SubscriptionStatusChanged,t=>{this.emit(M.TrackSubscriptionStatusChanged,e,t)}),e.on(R.Subscribed,t=>
vendor: 2,840 bytes, line 39
39{this.emit(M.TrackSubscribed,t,e)}),e.on(R.Unsubscribed,t=>{this.emit(M.TrackUnsubscribed,t,e)}),e.on(R.SubscriptionFailed,t=>{this.emit(M.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:E.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(M.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,r,s,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),V(o))),this.emit(M.TrackSubscriptionFailed,t);return}const d=e.kind==="video";let c;return d?c=new ps(e,t,r,s):c=new ud(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Or(c)&&et(c)&&c.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;const t=new Map,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const d=E.kindFromProto(r.type);if(!d)return;o=new fm(d,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);const c=Array.from(this.trackPublications.values()).find(l=>l.source===(o==null?void 0:o.source));c&&o.source!==E.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:V(c),newTrack:V(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),V(r))),this.unpublishTrack(r.trackSid,!0))}
39),i.forEach(r=>{this.emit(M.TrackPublished,r)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const r=i.track;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case E.Kind.Audio:this.audioTrackPublications.delete(e);break;case E.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(M.TrackUnpublished,i)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;et(i.track)&&Or(i.track)&&t.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const i of this.dataTracks.entries()){var t=N(i,2);const r=t[0],s=t[1];e===s.info.sid&&this.dataTracks.delete(r)}}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var K;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(K||(K={}));const gm=4*1e3;class ci extends Me.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,r,s,a,o,d;if(super(),t=this,this.state=K.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new fe,this.isVideoPlaybackBlocked=!1,this.log=U,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.connect=(c,l,u)=>m(this,void 0,void 0,function*(){var h;if(!Xu())throw ze()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const p=yield this.disconnectLock.lock();if(this.state===K.Connected)return this.log.info("already connected to room ".concat(this.name)),p(),Promise.resolve();if(this.connectFuture)return p(),this.connectFuture.promise;this.setAndEmitConnectionState(K.Connecting),((h=this.regionUrlProvider)===null||h===void 0?void 0:h.getServerUrl().toString())!==xc(c)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),si(new URL(c))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new W(c,l):this.regionUrlProvider.updateToken(l),this.regionUrlProvider.fetchRegionSettings().then(k=>{var T;(T=this.regionUrlProvider)===null||T===void 0||T.setServerReportedRegions(k)}).catch(k=>{this.log.warn("could not fetch region settings",{error:k})}));const f=(k,T,S)=>m(this,void 0,void 0,function*(){var L,b;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,p==null||p();try{if(yield ei.getInstance().getBackOffPromise(c),y.signal.aborted)throw x.cancelled("Connection attempt aborted");yield this.attemptConnection(S??c,l,u,y),this.abortController=void 0,k()}catch(C){if(this.regionUrlProvider&&C instanceof x&&C.reason!==Q.Cancelled&&C.reason!==Q.NotAllowed){let I=null;try{this.log.debug("Fetching next region"),I=yield this.regionUrlProvider.getNextBestRegionUrl((L=this.abortController)===null||L===void 0?void 0:L.signal)}catch(A){if(A instanceof x&&(A.status===401||A.reason===Q.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),T(A);return}}[Q.InternalError,Q.ServerUnreachable,Q.Timeout].includes(C.reason)&&(this.log.debug("Adding failed connection attempt to back off"),ei.getInstance().addFailedConnectionAttempt(c)),I&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(C.message,". Retrying with another region: ").concat(I)),this.recreateEngine(!0),yield f(k,T,I)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,aa(C)),T(C))}else{let I=He.UNKNOWN_REASON;C instanceof x&&(I=aa(C)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,I),T(C)}}}),g=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new be((k,T)=>{f(k,T,g)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(c,l,u,h,p,f)=>m(this,void 0,void 0,function*(){const g=yield u.join(c,l,{autoSubscribe:h.autoSubscribe,adaptiveStream:typeof p.adaptiveStream=="object"?!0:p.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(p),maxRetries:h.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:h.websocketTimeout},f.signal,!p.singlePeerConnection),k=g.joinResponse,T=g.serverInfo;if(this.serverInfo=T,!T.version)throw new Nu("unknown server version");return T.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),p.dynacast=!1),k}),this.applyJoinResponse=c=>{const l=c.participant;if(this.localParticipant.sid=l.sid,this.localParticipant.identity=l.identity,this.localParticipant.setEnabledPublishCodecs(c.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(c.sifTrailer)}catch(u){this.log.error(u instanceof Error?u.message:"Could not set SifTrailer",{error:u})}this.handleParticipantUpdates([l,...c.otherParticipants]),c.room&&this.handleRoomUpdate(c.room)},this.attemptConnection=(c,l,u,h)=>m(this,void 0,void 0,function*(){var p,f;this.state===K.Reconnecting||this.isResuming||!((p=this.engine)===null||p===void 0)&&p.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),!((f=this.regionUrlProvider)===null||f===void 0)&&f.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},bs),u),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const g=yield this.connectSignal(c,l,this.engine,this.connOptions,this.options,h);this.applyJoinResponse(g),this.setupLocalParticipantEvents(),this.emit
39(w.SignalConnected)}catch(g){yield this.engine.close(),this.recreateEngine();const k=h.signal.aborted?x.cancelled("Signal connection aborted"):x.serverUnreachable("could not establish signal connection");throw g instanceof Error&&(k.message="".concat(k.message,": ").concat(g.message)),g instanceof x&&(k.reason=g.reason,k.status=g.status),this.log.debug("error trying to establish signal connection",{error:g}),k}if(h.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),x.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,h)}catch(g){throw yield this.engine.close(),this.recreateEngine(),g}Ie()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ie()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(K.Connected),this.emit(w.Connected),ei.getInstance().resetFailedConnectionAttempts(c),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var c=arguments.length,l=new Array(c),u=0;u<c;u++)l[u]=arguments[u];return m(t,[...l],void 0,function(){var h=this;let p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var f,g,k;const T=yield h.disconnectLock.lock();try{if(h.state===K.Disconnected){h.log.debug("already disconnected");return}if(h.log.info("disconnect from room"),h.state===K.Connecting||h.state===K.Reconnecting||h.isResuming){const S="Abort connection attempt due to user initiated disconnect";h.log.warn(S),(f=h.abortController)===null||f===void 0||f.abort(S),(k=(g=h.connectFuture)===null||g===void 0?void 0:g.reject)===null||k===void 0||k.call(g,x.cancelled("Client initiated disconnect")),h.connectFuture=void 0}h.engine&&(h.engine.client.isDisconnected||(yield h.engine.client.sendLeave()),yield h.engine.close()),h.handleDisconnect(p,He.CLIENT_INITIATED),h.engine=void 0}finally{T()}})()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const c=[],l=_e();if(l&&l.os==="iOS"){const u="livekit-dummy-audio-el";let h=document.getElementById(u);if(!h){h=document.createElement("audio"),h.id=u,h.autoplay=!0,h.hidden=!0;const p=Jn();p.enabled=!0;const f=new MediaStream([p]);h.srcObject=f,document.addEventListener("visibilitychange",()=>{h&&(h.srcObject=document.hidden?null:f,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))}),document.body.append(h),this.once(w.Disconnected,()=>{h==null||h.remove(),h=null})}c.push(h)}
39this.remoteParticipants.forEach(u=>{u.audioTrackPublications.forEach(h=>{h.track&&h.track.attachedElements.forEach(p=>{c.push(p)})})});try{yield Promise.all([this.acquireAudioContext(),...c.map(u=>(this.options.webAudioMix||(u.muted=!1),u.play()))]),this.handleAudioPlaybackStarted()}catch(u){throw this.handleAudioPlaybackFailed(u),u}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const c=[];for(const l of this.remoteParticipants.values())l.videoTrackPublications.forEach(u=>{var h;(h=u.track)===null||h===void 0||h.attachedElements.forEach(p=>{c.includes(p)||c.push(p)})});yield Promise.all(c.map(l=>l.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(l=>{l.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const c of this.remoteParticipants.values())this.handleParticipantDisconnected(c.identity,c);this.setAndEmitConnectionState(K.Reconnecting)&&this.emit(w.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=c=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(c.serverRegion),{region:c.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(c);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(l){this.log.error("error trying to re-publish tracks after reconnection",{error:l})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:c.serverRegion})}catch{return}this.setAndEmitConnectionState(K.Connected),this.emit(w.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=c=>{var l;for(const h of c){if(h.identity===this.localParticipant.identity){this.localParticipant.updateInfo(h);continue}h.identity===""&&(h.identity=(l=this.sidToIdentity.get(h.sid))!==null&&l!==void 0?l:"");let p=this.remoteParticipants.get(h.identity);h.state===zt.DISCONNECTED?this.handleParticipantDisconnected(h.identity,p):this.getOrCreateParticipant(h.identity,h)}const u=new Map(c.filter(h=>h.identity!==this.localParticipant.identity).map(h=>[h.identity,h.dataTracks.map(p=>cn.from(p))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(u)},this.handleActiveSpeakersUpdate=c=>{const l=[],u={};
39c.forEach(h=>{if(u[h.sid]=!0,h.sid===this.localParticipant.sid)this.localParticipant.audioLevel=h.level,this.localParticipant.setIsSpeaking(!0),l.push(this.localParticipant);else{const p=this.getRemoteParticipantBySid(h.sid);p&&(p.audioLevel=h.level,p.setIsSpeaking(!0),l.push(p))}}),u[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(h=>{u[h.sid]||(h.audioLevel=0,h.setIsSpeaking(!1))}),this.activeSpeakers=l,this.emitWhenConnected(w.ActiveSpeakersChanged,l)},this.handleSpeakersChanged=c=>{const l=new Map;this.activeSpeakers.forEach(h=>{const p=this.remoteParticipants.get(h.identity);p&&p.sid!==h.sid||l.set(h.sid,h)}),c.forEach(h=>{let p=this.getRemoteParticipantBySid(h.sid);h.sid===this.localParticipant.sid&&(p=this.localParticipant),p&&(p.audioLevel=h.level,p.setIsSpeaking(h.active),h.active?l.set(h.sid,p):l.delete(h.sid))});const u=Array.from(l.values());u.sort((h,p)=>p.audioLevel-h.audioLevel),this.activeSpeakers=u,this.emitWhenConnected(w.ActiveSpeakersChanged,u)},this.handleStreamStateUpdate=c=>{c.streamStates.forEach(l=>{const u=this.getRemoteParticipantBySid(l.participantSid);if(!u)return;const h=u.getTrackPublicationBySid(l.trackSid);if(!h||!h.track)return;const p=E.streamStateFromProto(l.state),f=h.track.streamState;h.track.setStreamState(p),p!==f&&(u.emit(M.TrackStreamStateChanged,h,h.track.streamState),this.emitWhenConnected(w.TrackStreamStateChanged,h,h.track.streamState,u))})},this.handleSubscriptionPermissionUpdate=c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const u=l.getTrackPublicationBySid(c.trackSid);u&&u.setAllowed(c.allowed)},this.handleSubscriptionError=c=>{this.cancelPendingTrackAdded(c.trackSid);const l=Array.from(this.remoteParticipants.values()).find(h=>h.trackPublications.has(c.trackSid));if(!l)return;const u=l.getTrackPublicationBySid(c.trackSid);u&&u.setSubscriptionError(c.err)},this.handleDataPacket=(c,l)=>{const u=this.remoteParticipants.get(c.participantIdentity);if(c.value.case==="user")this.handleUserPacket(u,c.value.value,c.kind,l);else if(c.value.case==="transcription")this.handleTranscription(u,c.value.value);else if(c.value.case==="sipDtmf")this.handleSipDtmf(u,c.value.value);else if(c.value.case==="chatMessage")this.handleChatMessage(u,c.value.value);else if(c.value.case==="metrics")this.handleMetrics(c.value.value,u);else if(c.value.case==="streamHeader"||c.value.case==="streamChunk"||c.value.case==="streamTrailer")this.handleDataStream(c,l);else if(c.value.case==="rpcRequest"){const h=c.value.value;this.rpcServerManager.handleIncomingRpcRequest(c.participantIdentity,h)}else if(c.value.case==="rpcResponse"){const h=c.value.value;switch(h.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(h.requestId,h.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(h.requestId,G.fromProto(h.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(h.value.case),this.logContext);break}}else c.value.case==="rpcAck"&&this.rpcClientManager.handleIncomingRpcAck(c.value.value.requestId)},this.handleUserPacket=(c,l,u,h)=>{this.emit(w.DataReceived,l.payload,c,u,l.topic,h),c==null||c.emit(M.DataReceived,l.payload,u,h)},this.handleSipDtmf=(c,l)=>{this.emit(w.SipDTMFReceived,l,c),c==null||c.emit(M.SipDTMFReceived,l)},this.handleTranscription=(c,l)=>{const u=l.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(l.transcribedParticipantIdentity),h=u==null?void 0:u.trackPublications.get(l.trackId),p=ch(l,this.transcriptionReceivedTimes);h==null||h.emit(R.TranscriptionReceived,p),u==null||u.emit(M.TranscriptionReceived,p,h),this.emit(w.TranscriptionReceived,p,u,h)},this.handleChatMessage=(c,l)=>{const u=dh(l);this.emit(w.ChatMessage,u,c)},this.handleMetrics=(c,l)=>{this.emit(w.MetricsReceived,c,l)},this.handleDataStream=(c,l)=>{this.incomingDataStreamManager.handleDataStreamPacket(c,l)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>
39{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(w.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=c=>{this.log.warn("could not playback audio",{error:c}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(w.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(w.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(w.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){var c;((c=_e())===null||c===void 0?void 0:c.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(w.MediaDevicesChanged)}),this.handleRoomUpdate=c=>{const l=this.roomInfo;this.roomInfo=c,l&&l.metadata!==c.metadata&&this.emitWhenConnected(w.RoomMetadataChanged,c.metadata),(l==null?void 0:l.activeRecording)!==c.activeRecording&&this.emitWhenConnected(w.RecordingStatusChanged,c.activeRecording)},this.handleConnectionQualityUpdate=c=>{c.updates.forEach(l=>{if(l.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(l.quality);return}const u=this.getRemoteParticipantBySid(l.participantSid);u&&u.setConnectionQuality(l.quality)})},this.getRemoteParticipantClientProtocol=c=>{var l,u;return(u=(l=this.remoteParticipants.get(c))===null||l===void 0?void 0:l.clientProtocol)!==null&&u!==void 0?u:_c},this.getRemoteParticipantCapabilities=c=>{var l,u;return(u=(l=this.remoteParticipants.get(c))===null||l===void 0?void 0:l.capabilities)!==null&&u!==void 0?u:[]},this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.onLocalParticipantMetadataChanged=c=>{this.emit(w.ParticipantMetadataChanged,c,this.localParticipant)},this.onLocalParticipantNameChanged=c=>{this.emit(w.ParticipantNameChanged,c,this.localParticipant)},this.onLocalAttributesChanged=c=>{this.emit(w.ParticipantAttributesChanged,c,this.localParticipant)},this.onLocalTrackMuted=c=>{this.emit(w.TrackMuted,c,this.localParticipant)},this.onLocalTrackUnmuted=c=>{this.emit(w.TrackUnmuted,c,this.localParticipant)},this.onTrackProcessorUpdate=c=>{var l;(l=c==null?void 0:c.onPublish)===null||l===void 0||l.call(c,this)},this.onLocalTrackPublished=c=>m(this,void 0,void 0,function*(){var l,u,h,p,f,g;(l=c.track)===null||l===void 0||l.on(R.TrackProcessorUpdate,this.onTrackProcessorUpdate),(u=c.track)===null||u===void 0||u.on(R.Restarted,this.onLocalTrackRestarted),(f=(p=(h=c.track)===null||h===void 0?void 0:h.getProcessor())===null||p===void 0?void 0:p.onPublish)===null||f===void 0||f.call(p,this),this.emit(w.LocalTrackPublished,c,this.localParticipant),rt(c.track)&&(yield c.track.checkForSilence())&&this.emit(w.LocalAudioSilenceDetected,c);const k=yield(g=c.track)===null||g===void 0?void 0:g.getDeviceId(!1),T=Rr(c.source);T&&k&&k!==this.localParticipant.activeDeviceMap.get(T)&&(this.localParticipant.activeDeviceMap.set(T,k),this.emit(w.ActiveDeviceChanged,T,k))}),this.onLocalTrackUnpublished=c=>{var l,u;(l=c.track)===null||l===void 0||l.off(R.TrackProcessorUpdate,this.onTrackProcessorUpdate),(u=c.track)===null||u===void 0||u.off(R.Restarted,this.onLocalTrackRestarted),this.emit(w.LocalTrackUnpublished,c,this.localParticipant)},this.onLocalTrackRestarted=c=>m(this,void 0,void 0,function*(){const l=yield c.getDeviceId(!1),u=Rr(c.source);u&&l&&l!==this.localParticipant.activeDeviceMap.get(u)&&(this.log.debug("local track restarted, setting ".concat(u," ").concat(l," active")),this.localParticipant.activeDeviceMap.set(u,l),this.emit(w.ActiveDeviceChanged,u,l))}),this.onLocalConnectionQualityChanged=c=>{this.emit(w.ConnectionQualityChanged,c,this.localParticipant)},this.onMediaDevicesError=(c,l)=>{this.emit(w.MediaDevicesError,c,l)},this.onLocalParticipantPermissionsChanged=c=>{this.emit(w.ParticipantPermissionsChanged,c,this.localParticipant)},this.onLocalChatMessageSent=c=>{this.emit(w.ChatMessage,c,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},ap),e),this.log=ye((i=this.options.loggerName)!==null&&i!==void 0?i:oe.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},qc),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Vc),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},sp),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Vp,this.outgoingDataStreamManager=new Qp(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new rm({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",c=>{this.engine.client.sendUpdateDataSubscription(c.sid,c.subscribe)}).on("trackPublished",c=>{var l;c.track.publisherIdentity!==this.localParticipant.identity&&(this.emit
39(w.DataTrackPublished,c.track),(l=this.remoteParticipants.get(c.track.publisherIdentity))===null||l===void 0||l.addRemoteDataTrack(c.track))}).on("trackUnpublished",c=>{var l;c.publisherIdentity!==this.localParticipant.identity&&(this.emit(w.DataTrackUnpublished,c.sid),(l=this.remoteParticipants.get(c.publisherIdentity))===null||l===void 0||l.removeRemoteDataTrack(c.sid))}),this.outgoingDataTrackManager=new Ts({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",c=>{this.engine.client.sendPublishDataTrackRequest(c.handle,c.name,c.usesE2ee)}).on("sfuUnpublishRequest",c=>{this.engine.client.sendUnPublishDataTrackRequest(c.handle)}).on("trackPublished",c=>{this.emit(w.LocalDataTrackPublished,c.track)}).on("trackUnpublished",c=>{this.emit(w.LocalDataTrackUnpublished,c.sid)}).on("packetAvailable",c=>{let l=c.handle,u=c.bytes;this.engine.sendDataTrackFrame(u).finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(l))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new om(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>{var c,l;return(l=(c=this.engine.latestJoinResponse)===null||c===void 0?void 0:c.serverInfo)===null||l===void 0?void 0:l.version}),this.rpcClientManager.on("sendDataPacket",c=>{let l=c.packet;var u;(u=this.engine)===null||u===void 0||u.sendDataPacket(l,q.RELIABLE)}),this.rpcServerManager=new cm(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",c=>{let l=c.packet;var u;(u=this.engine)===null||u===void 0||u.sendDataPacket(l,q.RELIABLE)}),this.disconnectLock=new fe,this.localParticipant=new pm("","",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((r=this.e2eeManager)!==null&&r!==void 0?r:null),this.outgoingDataTrackManager.updateE2eeManager((s=this.e2eeManager)!==null&&s!==void 0?s:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Xt(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Xt(this.options.audioCaptureDefaults.deviceId)),!((a=this.options.audioOutput)===null||a===void 0)&&a.deviceId&&this.switchActiveDevice("audiooutput",Xt(this.options.audioOutput.deviceId)).catch(c=>this.log.warn("Could not set audio output: ".concat(c.message))),Ie()){const c=new AbortController;let l;if(ci.cleanupRegistry){const u=new WeakRef(this);l=()=>{const h=u.deref();h&&h.handleDeviceChange()},ci.cleanupRegistry.register(this,()=>{c.abort()})}else l=this.handleDeviceChange;(d=(o=navigator.mediaDevices)===null||o===void 0?void 0:o.addEventListener)===null||d===void 0||d.call(o,"devicechange",l,{signal:c.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)}
39registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){const 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;const i=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new Ih(r,i),this.e2eeManager.on(vt.ParticipantEncryptionStatusChanged,(s,a)=>{uh(a)&&(this.isE2EEEnabled=s),this.emit(w.ParticipantEncryptionStatusChanged,s,a)}),this.e2eeManager.on(vt.EncryptionError,(s,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(w.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this),(t=this.e2eeManager)===null||t===void 0||t.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new Ah(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,i;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:(t=this.localParticipant)===null||t===void 0?void 0:t.identity,participantID:(i=this.localParticipant)===null||i===void 0?void 0:i.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===K.Disconnected?Ee.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?Ee.resolve(this.roomInfo.sid):new Ee((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(P.RoomUpdate,i),e(r.sid))};this.engine.on(P.RoomUpdate,i),this.once(w.Disconnected,()=>{this.engine.off(P.RoomUpdate,i),t(new Z("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new Up(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(P.ParticipantUpdate,this.handleParticipantUpdates).on(P.RoomUpdate,this.handleRoomUpdate).on(P.SpeakersChanged,this.handleSpeakersChanged).on(P.StreamStateChanged,this.handleStreamStateUpdate).on(P.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(P.SubscriptionError,this.handleSubscriptionError).on(P.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(P.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(P.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(P.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(P.DataPacketReceived,this.handleDataPacket).on(P.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(K.SignalReconnecting)&&this.emit(w.SignalReconnecting)}).on(P.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.setAndEmitConnectionState(K.Connected)&&this.emit(w.Reconnected),this.emitBufferedEvents()}).on(P.SignalResumed,()=>{(this.state===K.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()}).on(P.Restarting,this.handleRestarting).on(P.Restarted,this.handleRestarted).on(P.SignalRestarted,this.handleSignalRestarted).on(P.Offline,()=>
39{this.setAndEmitConnectionState(K.Reconnecting)&&this.emit(w.Reconnecting)}).on(P.DCBufferStatusChanged,(e,t)=>{this.emit(w.DCBufferStatusChanged,e,t)}).on(P.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(P.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(w.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(P.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}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!==H.NONE}})}).on(P.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(P.DataTrackSubscriberHandles,e=>{const t=new Map(Object.entries(e.subHandles).map(i=>{let r=N(i,2),s=r[0],a=r[1];return[parseInt(s,10),a.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(P.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(P.Joined,e=>{const t=new Map(e.otherParticipants.map(i=>[i.identity,i.dataTracks.map(r=>cn.from(r))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(P.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(P.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Ur})}),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=>m(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return(e=this.regionUrlProvider)===null||e===void 0?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return me.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===K.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(si(new URL(e))&&t){this.regionUrlProvider=new W(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===K.Disconnected&&(this.regionUrl=i,yield fetch(Mi(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(Mi(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",{error:i})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return m(this,void 0,void 0,function*(){let i=()=>m(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":r=new Ye({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Ye({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Ye({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Ye({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":i=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Ye({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Ye({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":r=new Ye({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>m(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Cn({reason:He.CLIENT_INITIATED,action:Jt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Ye({scenario:{case:"subscriberBandwidth",value:Ge(t)}});break;case"leave-full-reconnect":r=new Ye({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return m(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,d,c,l,u,h,p;let f=!0,g=!1;const k=a?{exact:r}:r;if(i==="audioinput"){g=s.localParticipant.audioTrackPublications.size===0;const T=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=k;const S=Array.from(s.localParticipant.audioTrackPublications.values()).filter(b=>b.source===E.Source.Microphone);try{f=(yield Promise.all(S.map(b=>{var y;return(y=b.audioTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(b=>b===!0)}catch(b){throw s.options.audioCaptureDefaults.deviceId=T,b}const L=S.some(b=>{var y,C;return(C=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&C!==void 0?C:!1});f&&L&&(g=!0)}else if(i==="videoinput"){g=s.localParticipant.videoTrackPublications.size===0;const T=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=k;const S=Array.from(s.localParticipant.videoTrackPublications.values()).filter(b=>b.source===E.Source.Camera);try{f=(yield Promise.all(S.map(b=>{var y;return(y=b.videoTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(b=>b===!0)}catch(b){throw s.options.videoCaptureDefaults.deviceId=T,b}const L=S.some(b=>{var y,C;return(C=(y=b.track)===null||y===void 0?void 0:y.isMuted)!==null&&C!==void 0?C:!1});f&&L&&(g=!0)}else if(i==="audiooutput"){if(g=!0,!Dr()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(c=yield me.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(l=(p=s.options).audioOutput)!==null&&l!==void 0||(p.audioOutput={});const T=(u=s.getActiveDevice(i))!==null&&u!==void 0?u:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(S=>S.setAudioOutput({deviceId:r})))}catch(S){throw s.options.audioOutput.deviceId=T,S}}return g&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(w.ActiveDeviceChanged,i,r)),f})()})}setupLocalParticipantEvents(){this.localParticipant.on(M.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(M.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(M.AttributesChanged,this.onLocalAttributesChanged).on(M.TrackMuted,this.onLocalTrackMuted).on(M.TrackUnmuted,this.onLocalTrackUnmuted).on(M.LocalTrackPublished,this.onLocalTrackPublished).on(M.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(M.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(M.MediaDevicesError,this.onMediaDevicesError).on(M.AudioStreamAcquired,this.startAudio).on(M.ChatMessage,this.onLocalChatMessageSent).on(M.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t==null||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){var r,s;if([K.Connecting,K.Reconnecting].includes(this.state)){const p=oa(e,t);this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(k=>k.id)});const f=()=>{g(),this.onTrackAdded(e,t,i)},g=()=>{if(this.off(w.Reconnected,f),this.off(w.Connected,f),this.off(w.Disconnected,g),p){const k=this.pendingTrackAddedCallbacks.get(p);k==null||k.delete(g),(k==null?void 0:k.size)===0&&this.pendingTrackAddedCallbacks.delete(p)}};if(this.once(w.Reconnected,f),this.once(w.Connected,f),this.once(w.Disconnected,g),p){const k=(r=this.pendingTrackAddedCallbacks.get(p))!==null&&r!==void 0?r:new Set;k.add(g),this.pendingTrackAddedCallbacks.set(p,k)}return}if(this.state===K.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if(e.readyState==="ended"){this.log.debug("skipping incoming track as it already ended");return}const a=Dc(t.id),o=a[0],d=a[1];let c=(s=oa(e,t))!==null&&s!==void 0?s:e.id;if(o===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}const l=Array.from(this.remoteParticipants.values()).find(p=>p.sid===o);if(!l){o.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o));return}if(!c.startsWith("TR")){const p=this.engine.getTrackIdForReceiver(i);if(!p){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(o));return}c=p}c.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(d,", trackId: ").concat(c),{remoteParticipantID:o,streamId:d,trackId:c});let u;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?u=this.options.adaptiveStream:u={});const h=l.addSubscribedMediaTrack(e,c,t,i,u);
39h!=null&&h.isEncrypted&&!this.e2eeManager&&this.emit(w.EncryptionError,new Error("Encrypted ".concat(h.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}cancelPendingTrackAdded(e){var t;(t=this.pendingTrackAddedCallbacks.get(e))===null||t===void 0||t.forEach(i=>i())}handleLocalTrackSubscribed(e){const t=()=>this.localParticipant.getTrackPublications().find(d=>d.trackSid===e),i=t();if(i){this.emitLocalTrackSubscribed(i);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});const r=1e4;let s;const a=d=>{d.trackSid===e&&(o(),this.emitLocalTrackSubscribed(d))},o=()=>{clearTimeout(s),this.localParticipant.off(M.LocalTrackPublished,a),this.off(w.Disconnected,o)};this.localParticipant.on(M.LocalTrackPublished,a),this.once(w.Disconnected,o),s=setTimeout(()=>{o();const d=t();d?this.emitLocalTrackSubscribed(d):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},r)}emitLocalTrackSubscribed(e){this.localParticipant.emit(M.LocalTrackSubscribed,e),this.emitWhenConnected(w.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==K.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();
39try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(a=>{s.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var a,o,d;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((a=s.track)===null||a===void 0||a.detach(),(o=s.track)===null||o===void 0||o.stop()):(d=s.track)===null||d===void 0||d.stopMonitor()}),this.localParticipant.off(M.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(M.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(M.AttributesChanged,this.onLocalAttributesChanged).off(M.TrackMuted,this.onLocalTrackMuted).off(M.TrackUnmuted,this.onLocalTrackUnmuted).off(M.LocalTrackPublished,this.onLocalTrackPublished).off(M.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(M.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(M.MediaDevicesError,this.onMediaDevicesError).off(M.AudioStreamAcquired,this.startAudio).off(M.ChatMessage,this.onLocalChatMessageSent).off(M.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&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),Ie()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||r===void 0||r.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(K.Disconnected),this.emit(w.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(w.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return m(this,void 0,void 0,function*(){var e,t,i;const r=me.getInstance().previousDevices,s=yield me.getInstance().getDevices(void 0,!1),a=_e();if((a==null?void 0:a.name)==="Chrome"&&a.os!=="iOS")for(let d of s){const c=r.find(l=>l.deviceId===d.deviceId);c&&c.label!==""&&c.kind===d.kind&&c.label!==d.label&&this.getActiveDevice(d.kind)==="default"&&this.emit(w.ActiveDeviceChanged,d.kind,d.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let d of o){const c=qu(d),l=this.localParticipant.getTrackPublication(c);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=s.filter(p=>p.kind===d),h=this.getActiveDevice(d);if(h===((t=r.filter(p=>p.kind===d)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(d,u[0].deviceId);continue}d==="audioinput"&&!Ii()||d==="videoinput"||u.length>0&&!u.find(p=>p.deviceId===this.getActiveDevice(d))&&(d!=="audiooutput"||!Ii())&&(yield this.switchActiveDevice(d,u[0].deviceId))}})}acquireAudioContext(){return m(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=cs())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEac
39h(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Te(200)])}catch(r){this.log.warn("Could not resume audio context",{error:r})}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(w.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=mn.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):r=new mn(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message))),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(w.ParticipantConnected,i),i.on(M.TrackPublished,r=>{this.emitWhenConnected(w.TrackPublished,r,i)}).on(M.TrackSubscribed,(r,s)=>{r.kind===E.Kind.Audio?(r.on(R.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(R.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===E.Kind.Video&&(r.on(R.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(R.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(w.TrackSubscribed,r,s,i)}).on(M.TrackUnpublished,r=>{this.cancelPendingTrackAdded(r.trackSid),this.emit(w.TrackUnpublished,r,i)}).on(M.TrackUnsubscribed,(r,s)=>{this.emit(w.TrackUnsubscribed,r,s,i)}).on(M.TrackMuted,r=>{this.emitWhenConnected(w.TrackMuted,r,i)}).on(M.TrackUnmuted,r=>{this.emitWhenConnected(w.TrackUnmuted,r,i)}).on(M.ParticipantMetadataChanged,r=>{this.emitWhenConnected(w.ParticipantMetadataChanged,r,i)}).on(M.ParticipantNameChanged,r=>{this.emitWhenConnected(w.ParticipantNameChanged,r,i)}).on(M.AttributesChanged,r=>{this.emitWhenConnected(w.ParticipantAttributesChanged,r,i)}).on(M.ConnectionQualityChanged,r=>{this.emitWhenConnected(w.ConnectionQualityChanged,r,i)}).on(M.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(w.ParticipantPermissionsChanged,r,i)}).on(M.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(w.TrackSubscriptionStatusChanged,r,s,i)}).on(M.TrackSubscriptionFailed,(r,s)=>{this.emit(w.TrackSubscriptionFailed,r,i,s)}).on(M.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(w.TrackSubscriptionPermissionChanged,r,s,i)}).on(M.Active,()=>{this.emitWhenConnected(w.ParticipantActive,i),i.kind===_i.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,s)=>(r.push(...s.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications(),i=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&lh(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){var t;const i=[];return(Ai((t=e.frameMetadata)!==null&&t!==void 0?t:e.packetTrailer)||this.e2eeManager)&&i.push(wi.CAP_PACKET_TRAILER),Ct()&&i.push(wi.CAP_COMPRESSION_DEFLATE_RAW),i}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(cd,(e,t)=>m(this,[e,t],void 0,function(i,r){var s=this;let a=r.identity;return(function*(){var o;const d=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcServerManager.handleIncomingDataStream(i,a,d)})()})),this.incomingDataStreamManager.registerTextStreamHandler(dd,(e,t)=>m(this,[e,t],void 0,function(i,r){var s=this;
39let a=r.identity;return(function*(){var o;const d=(o=i.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcClientManager.handleIncomingDataStream(i,a,d)})()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Y.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(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.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn("detected connection state mismatch, attempting full reconnect"),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,He.STATE_MISMATCH)))):e=0},gm)}clearConnectionReconcile(){this.connectionReconcileInterval&&Y.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===K.Connected),this.emit(w.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=N(e,2),i=t[0],r=t[1];this.emit(i,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(this.state===K.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===K.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return m(this,void 0,void 0,function*(){var t,i,r,s;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new gn({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:te.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ft({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected),this.emit(w.Connected),this.setAndEmitConnectionState(K.Connected),a.video){const d=new Fr(E.Kind.Video,new Kt({source:de.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:qe.AUDIO,name:"video-dummy"}),new un(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:sa(160*((i=o.aspectRatios[0])!==null&&i!==void 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(d),this.localParticipant.emit(M.LocalTrackPublished,d)}if(a.audio){const d=new Fr(E.Kind.Audio,new Kt({source:de.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:qe.AUDIO}),new dn(a.useRealTracks&&(!((r=navigator.mediaDevices)===null||r===void 0)&&r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Jn(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(d),this.localParticipant.emit(M.LocalTrackPublished,d)}for(let d=0;d<o.count-1;d+=1){let c=new Ft({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(d),state:zt.ACTIVE,tracks:[],joinedAt:te.parse(Date.now())});const l=this.getOrCreateParticipant(c.identity,c);if(o.video){const u=sa(160*((s=o.aspectRatios[d%o.aspectRatios.length])!==null&&s!==void 0?s:1),160,!1,!0),h=new Kt({source:de.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:qe.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),c.tracks=[...c.tracks,h]}if(o.audio){const u=Jn(),h=new Kt({source:de.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:qe.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),c.tracks=[...c.tracks,h]}l.updateInfo(c)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(e!==w.ActiveSpeakersChanged&&e!==w.TranscriptionReceived){const s=pd(i).filter(a=>a!==void 0);(e===w.TrackSubscribed||e===w.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:s}),this.log.debug("room event ".concat(e),{event:e,args:s})}return super.emit(e,...i)}}ci.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(n=>{n()});function pd(n){return n.map(e=>{if(e)return Array.isArray(e)?pd(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Be;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Be||(Be={}));class Pt extends Me.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Be.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new ci(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return m(this,void 0,void 0,function*(){if(this.status!==Be.IDLE)throw Error("check is running already");this.setStatus(Be.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Be.SKIPPED&&this.setStatus(this.isSuccess()?Be.SUCCESS:Be.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===K.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)}
vendor: 6,191 bytes, line 39
39)}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==K.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Be.SKIPPED)}switchProtocol(e){return m(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(w.Reconnecting,()=>{t=!0}),this.room.once(w.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Te(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class vm extends Pt{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new W(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return m(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,d=1e6/a,c="A".repeat(a),l=Date.now();for(let f=0;f<d;f++)yield s.write(c);yield s.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),p={region:r,rtt:1e4,duration:u-l};return h==null||h.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(p.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const lr=1e4;class bm extends Pt{get description(){return"Connection via UDP vs TCP"}perform(){return m(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(lr/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(lr/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>m(this,void 0,void 0,function*(){const h=yield c.getRTCStatsReport();h==null||h.forEach(p=>{p.type==="outbound-rtp"?(l.packetsSent=p.packetsSent,l.qualityLimitationDurations=p.qualityLimitationDurations,l.bitrateTotal+=p.targetBitrate,l.count++):p.type==="remote-inbound-rtp"&&(l.packetsLost=p.packetsLost,l.rttTotal+=p.roundTripTime,l.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,lr)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class ym extends Pt{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield lm();if(yield Ic(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class km extends Pt{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield dm();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>
39{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return m(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,d;const c=document.createElement("canvas"),l=e.getSettings(),u=(a=(s=l.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,h=(d=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&d!==void 0?d:720;c.width=u,c.height=h;const p=c.getContext("2d");p.drawImage(i,0,0);const g=p.getImageData(0,0,c.width,c.height).data;let k=!0;for(let T=0;T<g.length;T+=4)if(g[T]!==0||g[T+1]!==0||g[T+2]!==0){k=!1;break}k?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),t.getTracks().forEach(r=>r.stop()),i.remove()})}}class Tm extends Pt{get description(){return"Resuming connection after interruption"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,r=!1,s;const a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{i=!0};t.on(w.SignalReconnecting,o).on(w.Reconnecting,o).on(w.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const d=t.engine.client.onClose;if(d&&d(""),yield a,i){if(!r||t.state!==K.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class Sm extends Pt{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t,i;si(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new W(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new gs,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,d=!1;for(let c of s.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,d=!0):l.startsWith("turns:")&&(o=!0,d=!0,a=!0),l.startsWith("stun:")&&(d=!0);d?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class Cm extends Pt{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(w.SignalConnected,()=>{var i;const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,a)=>{if(s.candidate){const o=new RTCIceCandidate(s);let d="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Em(o.address)?d+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,d+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(d)}r&&r(s,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),U.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function Em(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;
39if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class _m extends Pt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new gs,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(si(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const d=yield new W(this.url,this.token).getNextBestRegionUrl();d&&(s=yield r.join(d,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}s?(this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===wo.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}}class Hm extends Me.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Be.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Be.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(_m)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Cm)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Sm)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Tm)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(ym)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(km)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(bm);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(vm)})}}new TextEncoder;new TextDecoder;class we extends Error{constructor(e,t){var i;super(e,t),j(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}j(we,"code","ERR_JOSE_GENERIC");class wm extends we{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),j(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}}j(wm,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Pm extends we{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),j(this,"code","ERR_JWT_EXPIRED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}}
39j(Pm,"code","ERR_JWT_EXPIRED");class Rm extends we{constructor(){super(...arguments),j(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}j(Rm,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Im extends we{constructor(){super(...arguments),j(this,"code","ERR_JOSE_NOT_SUPPORTED")}}j(Im,"code","ERR_JOSE_NOT_SUPPORTED");class Mm extends we{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWE_DECRYPTION_FAILED")}}j(Mm,"code","ERR_JWE_DECRYPTION_FAILED");class Dm extends we{constructor(){super(...arguments),j(this,"code","ERR_JWE_INVALID")}}j(Dm,"code","ERR_JWE_INVALID");class Am extends we{constructor(){super(...arguments),j(this,"code","ERR_JWS_INVALID")}}j(Am,"code","ERR_JWS_INVALID");class Om extends we{constructor(){super(...arguments),j(this,"code","ERR_JWT_INVALID")}}j(Om,"code","ERR_JWT_INVALID");class Nm extends we{constructor(){super(...arguments),j(this,"code","ERR_JWK_INVALID")}}j(Nm,"code","ERR_JWK_INVALID");class Lm extends we{constructor(){super(...arguments),j(this,"code","ERR_JWKS_INVALID")}}j(Lm,"code","ERR_JWKS_INVALID");class xm extends we{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}j(xm,"code","ERR_JWKS_NO_MATCHING_KEY");class Um extends we{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,Symbol.asyncIterator,void 0),j(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}j(Um,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class Fm extends we{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_TIMEOUT")}}
39j(Fm,"code","ERR_JWKS_TIMEOUT");class Bm extends we{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}j(Bm,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");function Br(n,e){return Br=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,i){return t.__proto__=i,t},Br(n,e)}var qm=new TextDecoder,Km=(function(n){var e,t;function i(){var s;return(s=n.call(this)||this).room=void 0,s.connected=!1,s.isAgentTalking=!1,s.analyzerComponent=void 0,s.captureAudioFrame=void 0,s}t=n,(e=i).prototype=Object.create(t.prototype),e.prototype.constructor=e,Br(e,t);var r=i.prototype;return r.startCall=function(s){try{var a=this,o=(function(d,c){try{var l=(a.room=new ci({audioCaptureDefaults:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,channelCount:1,deviceId:s.captureDeviceId,sampleRate:s.sampleRate},audioOutput:{deviceId:s.playbackDeviceId}}),a.handleRoomEvents(),a.handleAudioEvents(s),a.handleDataEvents(),Promise.resolve(a.room.connect("wss://retell-ai-4ihahnq7.livekit.cloud",s.accessToken)).then(function(){console.log("connected to room",a.room.name),a.room.localParticipant.setMicrophoneEnabled(!0),a.connected=!0,a.emit("call_started")}))}catch(u){return c(u)}return l&&l.then?l.then(void 0,c):l})(0,function(d){a.emit("error","Error starting call"),console.error("Error starting call",d),a.stopCall()});return Promise.resolve(o&&o.then?o.then(function(){}):void 0)}catch(d){return Promise.reject(d)}},r.startAudioPlayback=function(){try{return Promise.resolve(this.room.startAudio()).then(function(){})}catch(s){return Promise.reject(s)}},r.stopCall=function(){var s;this.connected&&(this.connected=!1,this.emit("call_ended"),(s=this.room)==null||s.disconnect(),this.isAgentTalking=!1,delete this.room,this.analyzerComponent&&(this.analyzerComponent.cleanup(),delete this.analyzerComponent),this.captureAudioFrame&&(window.cancelAnimationFrame(this.captureAudioFrame),delete this.captureAudioFrame))},r.mute=function(){this.connected&&this.room.localParticipant.setMicrophoneEnabled(!1)},r.unmute=function(){this.connected&&this.room.localParticipant.setMicrophoneEnabled(!0)},r.captureAudioSamples=function(){var s=this;if(this.connected&&this.analyzerComponent){var a=new Float32Array(this.analyzerComponent.analyser.fftSize);this.analyzerComponent.analyser.getFloatTimeDomainData(a),this.emit("audio",a),this.captureAudioFrame=window.requestAnimationFrame(function(){return s.captureAudioSamples()})}},r.handleRoomEvents=function(){var s=this;this.room.on(w.Disconnected,function(){s.stopCall()})},r.handleAudioEvents=function(s){var a=this;this.room.on(w.TrackSubscribed,function(o,d,c){o.kind===E.Kind.Audio&&o instanceof ud&&(d.trackName==="agent_audio"&&(a.emit("call_ready"),s.emitRawAudioSamples&&(a.analyzerComponent=ah(o),a.captureAudioFrame=window.requestAnimationFrame(function(){return a.captureAudioSamples()}))),o.attach())})},r.handleDataEvents=function(){var s=this;this.room.on(w.DataReceived,function(a,o,d,c){try{if((o==null?void 0:o.identity)!=="server")return;var l=qm.decode(a),u=JSON.parse(l);u.event_type==="update"?s.emit("update",u):u.event_type==="metadata"?s.emit("metadata",u):u.event_type==="agent_start_talking"?(s.isAgentTalking=!0,s.emit("agent_start_talking")):u.event_type==="agent_stop_talking"?(s.isAgentTalking=!1,s.emit("agent_stop_talking")):u.event_type==="node_transition"&&s.emit("node_transition",u)}catch(h){console.error("Error decoding data received",h)}})},i})(fd);export{Km as RetellWebClient};
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.